[clang] [webkit.UncountedLambdaCapturesChecker] Ignore trivial functions and [[clang::noescape]]. (PR #113845)

2024-10-27 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated 
https://github.com/llvm/llvm-project/pull/113845

>From 1524ca532c9c1ef015c162360d4e4688296bbc0d Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 27 Oct 2024 16:30:48 -0700
Subject: [PATCH 1/2] [webkit.UncountedLambdaCapturesChecker] Ignore trivial
 functions and [[clang::noescape]].

This PR makes webkit.UncountedLambdaCapturesChecker ignore trivial functions as 
well as
the one being passed to an argument with [[clang::noescape]] attribute. This 
dramatically
reduces the false positive rate for this checker.

To do this, this PR replaces VisitLambdaExpr in favor of checking lambdas via 
VisitDeclRefExpr
and VisitCallExpr. The idea is that if a lambda is defined but never called or 
stored somewhere,
then capturing whatever variable in such a lambda is harmless.

VisitCallExpr explicitly looks for direct invocation of lambdas and registers 
its DeclRefExpr
to be ignored in VisitDeclRefExpr. If a lambda is being passed to a function, 
it checks whether
its argument is annotated with [[clang::noescape]]. If it's not annotated such, 
it checks
captures for their safety.

Because WTF::switchOn could not be annotated with [[clang::noescape]] as 
function type parameters
are variadic template function so we hard-code this function into the checker.

Finally, this PR also converts the accompanying test to use -verify and adds a 
bunch of tests.
---
 .../Checkers/WebKit/PtrTypesSemantics.h   |   4 +
 .../WebKit/UncountedLambdaCapturesChecker.cpp | 102 +--
 .../Analysis/Checkers/WebKit/mock-types.h |   2 +
 .../WebKit/uncounted-lambda-captures.cpp  | 159 +++---
 4 files changed, 233 insertions(+), 34 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index 4b41ca96e1df1d..814015c311d61e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -63,6 +63,10 @@ std::optional isUncounted(const clang::CXXRecordDecl* 
Class);
 /// class, false if not, std::nullopt if inconclusive.
 std::optional isUncountedPtr(const clang::QualType T);
 
+/// \returns true if \p T is either a raw pointer or reference to an uncounted
+/// or unchecked class, false if not, std::nullopt if inconclusive.
+std::optional isUnsafePtr(const QualType T);
+
 /// \returns true if \p T is a RefPtr, Ref, CheckedPtr, CheckedRef, or its
 /// variant, false if not.
 bool isSafePtrType(const clang::QualType T);
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
index 998bd4ccee07db..02f68ac5e41317 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
@@ -6,6 +6,7 @@
 //
 
//===--===//
 
+#include "ASTUtils.h"
 #include "DiagOutputUtils.h"
 #include "PtrTypesSemantics.h"
 #include "clang/AST/CXXInheritance.h"
@@ -26,6 +27,7 @@ class UncountedLambdaCapturesChecker
   BugType Bug{this, "Lambda capture of uncounted variable",
   "WebKit coding guidelines"};
   mutable BugReporter *BR = nullptr;
+  TrivialFunctionAnalysis TFA;
 
 public:
   void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
@@ -37,6 +39,8 @@ class UncountedLambdaCapturesChecker
 // want to visit those, so we make our own RecursiveASTVisitor.
 struct LocalVisitor : public RecursiveASTVisitor {
   const UncountedLambdaCapturesChecker *Checker;
+  llvm::DenseSet DeclRefExprsToIgnore;
+
   explicit LocalVisitor(const UncountedLambdaCapturesChecker *Checker)
   : Checker(Checker) {
 assert(Checker);
@@ -45,8 +49,61 @@ class UncountedLambdaCapturesChecker
   bool shouldVisitTemplateInstantiations() const { return true; }
   bool shouldVisitImplicitCode() const { return false; }
 
-  bool VisitLambdaExpr(LambdaExpr *L) {
-Checker->visitLambdaExpr(L);
+  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
+if (DeclRefExprsToIgnore.contains(DRE))
+  return true;
+if (auto *VD = dyn_cast_or_null(DRE->getDecl())) {
+  auto *Init = VD->getInit()->IgnoreParenCasts();
+  if (auto *L = dyn_cast_or_null(Init)) {
+Checker->visitLambdaExpr(L);
+return true;
+  }
+}
+return true;
+  }
+
+  // WTF::switchOn(T, F... f) is a variadic template function and couldn't 
be annotated with NOESCAPE.
+  // We hard code it here to workaround that.
+  bool shouldTreatAllArgAsNoEscape(FunctionDecl *Decl) {
+auto *NsDecl = Decl->getParent();
+if (!NsDecl || !isa(NsDecl))
+  return false;
+return safeGetName(NsDecl) == "WTF" && safeGetName(Decl) == "switc

[clang] [llvm] [NVPTX] Remove nvvm.ldg.global.* intrinsics (PR #112834)

2024-10-27 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `openmp-s390x-linux` 
running on `systemz-1` while building `clang,llvm` at step 6 "test-openmp".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/88/builds/3935


Here is the relevant piece of the build log for the reference

```
Step 6 (test-openmp) failure: 1200 seconds without output running [b'ninja', 
b'-j 4', b'check-openmp'], attempting to kill
...
PASS: ompd-test :: openmp_examples/example_3.c (439 of 449)
PASS: ompd-test :: openmp_examples/example_4.c (440 of 449)
PASS: ompd-test :: openmp_examples/example_5.c (441 of 449)
PASS: ompd-test :: openmp_examples/example_task.c (442 of 449)
UNSUPPORTED: ompd-test :: openmp_examples/ompd_bt.c (443 of 449)
PASS: ompd-test :: openmp_examples/fibonacci.c (444 of 449)
UNSUPPORTED: ompd-test :: openmp_examples/ompd_parallel.c (445 of 449)
PASS: ompd-test :: openmp_examples/parallel.c (446 of 449)
PASS: ompd-test :: openmp_examples/nested.c (447 of 449)
PASS: ompd-test :: openmp_examples/ompd_icvs.c (448 of 449)
command timed out: 1200 seconds without output running [b'ninja', b'-j 4', 
b'check-openmp'], attempting to kill
process killed by signal 9
program finished with exit code -1
elapsedTime=1327.211968

```



https://github.com/llvm/llvm-project/pull/112834
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] RFC: [clang-tidy] [analyzer] Move nondeterministic pointer usage check to tidy (PR #110471)

2024-10-27 Thread via cfe-commits

https://github.com/vabridgers updated 
https://github.com/llvm/llvm-project/pull/110471

>From ba04e964207053724db5df8795675b89e533260a Mon Sep 17 00:00:00 2001
From: Vince Bridgers 
Date: Thu, 26 Sep 2024 16:24:59 +0200
Subject: [PATCH] [clang-tidy] [analyzer] Move nondeterministic pointer usage
 check to tidy

This change moves the alpha.nondeterministic.PointerSorting and
alpha.nondeterministic.PointerIteration static analyzer checkers to
a single clang-tidy check. Those checkers were implemented as clang-tidy
checks wrapped in the static analyzer framework. The documentation was
updated to describe what the checks can and cannot do, and testing
was completed on a broad set of open source projects.
---
 .../bugprone/BugproneTidyModule.cpp   |   3 +
 .../clang-tidy/bugprone/CMakeLists.txt|   1 +
 ...eterministicPointerIterationOrderCheck.cpp |  79 +
 ...ndeterministicPointerIterationOrderCheck.h |  39 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 ...ndeterministic-pointer-iteration-order.rst |  44 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../system-header-simulator/sim_algorithm |  31 
 .../system-header-simulator/sim_c++config.h   |  11 ++
 .../sim_initializer_list  |  39 +
 .../system-header-simulator/sim_iterator_base |  22 +++
 .../Inputs/system-header-simulator/sim_map|  34 
 .../Inputs/system-header-simulator/sim_set|  44 +
 .../system-header-simulator/sim_stl_pair  |  32 
 .../system-header-simulator/sim_type_traits   |  19 +++
 .../system-header-simulator/sim_unordered_map |  33 
 .../system-header-simulator/sim_unordered_set |  35 
 .../Inputs/system-header-simulator/sim_vector | 150 ++
 ...ndeterministic-pointer-iteration-order.cpp |  84 ++
 clang/docs/ReleaseNotes.rst   |   6 +
 clang/docs/analyzer/checkers.rst  |  31 
 .../clang/StaticAnalyzer/Checkers/Checkers.td |  18 ---
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   2 -
 .../Checkers/PointerIterationChecker.cpp  | 101 
 .../Checkers/PointerSortingChecker.cpp| 115 --
 clang/test/Analysis/ptr-iter.cpp  |  28 
 clang/test/Analysis/ptr-sort.cpp  |  36 -
 27 files changed, 713 insertions(+), 331 deletions(-)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/nondeterministic-pointer-iteration-order.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_algorithm
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_c++config.h
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_initializer_list
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_iterator_base
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_map
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_set
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_stl_pair
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_type_traits
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_unordered_map
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_unordered_set
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_vector
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/nondeterministic-pointer-iteration-order.cpp
 delete mode 100644 
clang/lib/StaticAnalyzer/Checkers/PointerIterationChecker.cpp
 delete mode 100644 clang/lib/StaticAnalyzer/Checkers/PointerSortingChecker.cpp
 delete mode 100644 clang/test/Analysis/ptr-iter.cpp
 delete mode 100644 clang/test/Analysis/ptr-sort.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 9120c4b6c0d9ae..33ac65e715ce81 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -49,6 +49,7 @@
 #include "MultipleStatementMacroCheck.h"
 #include "NoEscapeCheck.h"
 #include "NonZeroEnumToBoolConversionCheck.h"
+#include "NondeterministicPointerIterationOrderCheck.h"
 #include "NotNullTerminatedResultCheck.h"
 #include "OptionalValueConversionCheck.h"
 #include "ParentVirtual

[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -1398,5 +1807,30 @@ void Sema::DeclareImplicitDeductionGuides(TemplateDecl 
*Template,
   ->getTemplatedDecl())
   ->setDeductionCandidateKind(DeductionCandidate::Copy);
 
+  CXXRecordDecl *TemplatedDecl = Pattern->getTemplatedDecl();
+  if (getLangOpts().CPlusPlus23 && TemplatedDecl->hasDefinition()) {

antangelo wrote:

Given the uncertainty with open CWG issues and the potential breakage of code 
on earlier standards versions, I think it's less risky to keep it constrained 
to C++23 for now. It's probably worth revisiting in the future, though.

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -11758,6 +11795,40 @@ static void DiagnoseBadDeduction(Sema &S, NamedDecl 
*Found, Decl *Templated,
   return;
 }
 
+// Errors in deduction guides from inherited constructors
+// will present as substitution failures in the mapping
+// partial specialization, so we show a generic diagnostic
+// in this case.
+if (auto *DG = dyn_cast(Templated);
+DG && DG->getSourceKind() ==
+  CXXDeductionGuideDecl::SourceKind::InheritedConstructor) {
+  CXXDeductionGuideDecl *Source = DG->getSourceDeductionGuide();
+  assert(Source &&
+ "Inherited constructor deduction guides must have a source");
+  QualType DeducedRecordType(
+  cast(DG->getDeducedTemplate())
+  ->getTemplatedDecl()
+  ->getTypeForDecl(),
+  0);
+  QualType InheritedRecordType(
+  cast(Source->getDeducedTemplate())
+  ->getTemplatedDecl()
+  ->getTypeForDecl(),
+  0);

antangelo wrote:

Done

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [X86][AMX] Support AMX-FP8 (PR #113850)

2024-10-27 Thread Feng Zou via cfe-commits

https://github.com/fzou1 created 
https://github.com/llvm/llvm-project/pull/113850

Ref.: https://cdrdv2.intel.com/v1/dl/getContent/671368

>From fd570cb8d41f5f94b61d515985245fc81aab633e Mon Sep 17 00:00:00 2001
From: Feng Zou 
Date: Thu, 24 Oct 2024 21:56:48 +0800
Subject: [PATCH] Support AMX-FP8

Ref.: https://cdrdv2.intel.com/v1/dl/getContent/671368
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Basic/BuiltinsX86_64.def  |  6 +++
 clang/include/clang/Driver/Options.td |  2 +
 clang/lib/Basic/Targets/X86.cpp   |  6 +++
 clang/lib/Basic/Targets/X86.h |  1 +
 clang/lib/Headers/CMakeLists.txt  |  1 +
 clang/lib/Headers/amxfp8intrin.h  | 24 
 clang/lib/Headers/immintrin.h |  4 ++
 clang/lib/Sema/SemaX86.cpp|  4 ++
 clang/test/CodeGen/X86/amx_fp8.c  | 27 +
 clang/test/CodeGen/X86/amx_fp8_errors.c   | 10 +
 clang/test/CodeGen/X86/amx_fp8_inline_asm.c   | 32 +++
 llvm/include/llvm/IR/IntrinsicsX86.td | 17 
 .../llvm/TargetParser/X86TargetParser.def |  1 +
 llvm/lib/Target/X86/X86.td|  3 ++
 llvm/lib/Target/X86/X86ISelLowering.cpp   | 23 +++
 llvm/lib/Target/X86/X86InstrAMX.td| 39 +++
 llvm/lib/Target/X86/X86InstrPredicates.td |  1 +
 llvm/lib/TargetParser/Host.cpp|  4 ++
 llvm/lib/TargetParser/X86TargetParser.cpp |  1 +
 llvm/test/CodeGen/X86/amx_fp8_intrinsics.ll   | 20 ++
 .../Disassembler/X86/AMX/x86-64-amx-fp8.txt   | 34 
 llvm/test/MC/X86/AMX/x86-64-amx-fp8-att.s | 33 
 llvm/test/MC/X86/AMX/x86-64-amx-fp8-intel.s   | 33 
 24 files changed, 327 insertions(+)
 create mode 100644 clang/lib/Headers/amxfp8intrin.h
 create mode 100644 clang/test/CodeGen/X86/amx_fp8.c
 create mode 100644 clang/test/CodeGen/X86/amx_fp8_errors.c
 create mode 100644 clang/test/CodeGen/X86/amx_fp8_inline_asm.c
 create mode 100644 llvm/test/CodeGen/X86/amx_fp8_intrinsics.ll
 create mode 100644 llvm/test/MC/Disassembler/X86/AMX/x86-64-amx-fp8.txt
 create mode 100644 llvm/test/MC/X86/AMX/x86-64-amx-fp8-att.s
 create mode 100644 llvm/test/MC/X86/AMX/x86-64-amx-fp8-intel.s

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6a95337815174b..da0ab888ce200d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -642,6 +642,7 @@ X86 Support
 
 - Supported intrinsics for ``MOVRS AND AVX10.2``.
   * Supported intrinsics of ``_mm(256|512)_(mask(z))_loadrs_epi(8|16|32|64)``.
+- Support ISA of ``AMX-FP8``.
 
 Arm and AArch64 Support
 ^^^
diff --git a/clang/include/clang/Basic/BuiltinsX86_64.def 
b/clang/include/clang/Basic/BuiltinsX86_64.def
index e1e613560167ac..68904ae8abcd15 100644
--- a/clang/include/clang/Basic/BuiltinsX86_64.def
+++ b/clang/include/clang/Basic/BuiltinsX86_64.def
@@ -155,6 +155,12 @@ TARGET_BUILTIN(__builtin_ia32_cmpccxadd64, 
"SLLiv*SLLiSLLiIi", "n", "cmpccxadd")
 // AMX_FP16 FP16
 TARGET_BUILTIN(__builtin_ia32_tdpfp16ps, "vIUcIUcIUc", "n", "amx-fp16")
 
+// AMX FP8
+TARGET_BUILTIN(__builtin_ia32_tdpbf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+TARGET_BUILTIN(__builtin_ia32_tdpbhf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+TARGET_BUILTIN(__builtin_ia32_tdphbf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+TARGET_BUILTIN(__builtin_ia32_tdphf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+
 // RAO-INT
 TARGET_BUILTIN(__builtin_ia32_aadd64, "vv*SOi", "n", "raoint")
 TARGET_BUILTIN(__builtin_ia32_aand64, "vv*SOi", "n", "raoint")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5df6ddd5e6a0c5..bbada0834526d7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6290,6 +6290,8 @@ def mamx_fp16 : Flag<["-"], "mamx-fp16">, 
Group;
 def mno_amx_fp16 : Flag<["-"], "mno-amx-fp16">, Group;
 def mamx_int8 : Flag<["-"], "mamx-int8">, Group;
 def mno_amx_int8 : Flag<["-"], "mno-amx-int8">, Group;
+def mamx_fp8 : Flag<["-"], "mamx-fp8">, Group;
+def mno_amx_fp8 : Flag<["-"], "mno-amx-fp8">, Group;
 def mamx_tile : Flag<["-"], "mamx-tile">, Group;
 def mno_amx_tile : Flag<["-"], "mno-amx-tile">, Group;
 def mcmpccxadd : Flag<["-"], "mcmpccxadd">, Group;
diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index d067ec218b5270..b95261c39a5993 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -420,6 +420,8 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
   HasAMXTILE = true;
 } else if (Feature == "+amx-complex") {
   HasAMXCOMPLEX = true;
+} else if (Feature == "+amx-fp8") {
+  HasAMXFP8 = true;
 } else if (Feature == "+cmpccxadd") {
   HasCMPCCXADD = true;
 } else if (Feature == "+raoint") {
@@ -939,6 +941,8 @@ void X86TargetInfo::getTargetDefines(const LangOptions 

[clang] [llvm] [X86][AMX] Support AMX-FP8 (PR #113850)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-x86

Author: Feng Zou (fzou1)


Changes

Ref.: https://cdrdv2.intel.com/v1/dl/getContent/671368

---

Patch is 24.90 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/113850.diff


24 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1) 
- (modified) clang/include/clang/Basic/BuiltinsX86_64.def (+6) 
- (modified) clang/include/clang/Driver/Options.td (+2) 
- (modified) clang/lib/Basic/Targets/X86.cpp (+6) 
- (modified) clang/lib/Basic/Targets/X86.h (+1) 
- (modified) clang/lib/Headers/CMakeLists.txt (+1) 
- (added) clang/lib/Headers/amxfp8intrin.h (+24) 
- (modified) clang/lib/Headers/immintrin.h (+4) 
- (modified) clang/lib/Sema/SemaX86.cpp (+4) 
- (added) clang/test/CodeGen/X86/amx_fp8.c (+27) 
- (added) clang/test/CodeGen/X86/amx_fp8_errors.c (+10) 
- (added) clang/test/CodeGen/X86/amx_fp8_inline_asm.c (+32) 
- (modified) llvm/include/llvm/IR/IntrinsicsX86.td (+17) 
- (modified) llvm/include/llvm/TargetParser/X86TargetParser.def (+1) 
- (modified) llvm/lib/Target/X86/X86.td (+3) 
- (modified) llvm/lib/Target/X86/X86ISelLowering.cpp (+23) 
- (modified) llvm/lib/Target/X86/X86InstrAMX.td (+39) 
- (modified) llvm/lib/Target/X86/X86InstrPredicates.td (+1) 
- (modified) llvm/lib/TargetParser/Host.cpp (+4) 
- (modified) llvm/lib/TargetParser/X86TargetParser.cpp (+1) 
- (added) llvm/test/CodeGen/X86/amx_fp8_intrinsics.ll (+20) 
- (added) llvm/test/MC/Disassembler/X86/AMX/x86-64-amx-fp8.txt (+34) 
- (added) llvm/test/MC/X86/AMX/x86-64-amx-fp8-att.s (+33) 
- (added) llvm/test/MC/X86/AMX/x86-64-amx-fp8-intel.s (+33) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6a95337815174b..da0ab888ce200d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -642,6 +642,7 @@ X86 Support
 
 - Supported intrinsics for ``MOVRS AND AVX10.2``.
   * Supported intrinsics of ``_mm(256|512)_(mask(z))_loadrs_epi(8|16|32|64)``.
+- Support ISA of ``AMX-FP8``.
 
 Arm and AArch64 Support
 ^^^
diff --git a/clang/include/clang/Basic/BuiltinsX86_64.def 
b/clang/include/clang/Basic/BuiltinsX86_64.def
index e1e613560167ac..68904ae8abcd15 100644
--- a/clang/include/clang/Basic/BuiltinsX86_64.def
+++ b/clang/include/clang/Basic/BuiltinsX86_64.def
@@ -155,6 +155,12 @@ TARGET_BUILTIN(__builtin_ia32_cmpccxadd64, 
"SLLiv*SLLiSLLiIi", "n", "cmpccxadd")
 // AMX_FP16 FP16
 TARGET_BUILTIN(__builtin_ia32_tdpfp16ps, "vIUcIUcIUc", "n", "amx-fp16")
 
+// AMX FP8
+TARGET_BUILTIN(__builtin_ia32_tdpbf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+TARGET_BUILTIN(__builtin_ia32_tdpbhf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+TARGET_BUILTIN(__builtin_ia32_tdphbf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+TARGET_BUILTIN(__builtin_ia32_tdphf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+
 // RAO-INT
 TARGET_BUILTIN(__builtin_ia32_aadd64, "vv*SOi", "n", "raoint")
 TARGET_BUILTIN(__builtin_ia32_aand64, "vv*SOi", "n", "raoint")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5df6ddd5e6a0c5..bbada0834526d7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6290,6 +6290,8 @@ def mamx_fp16 : Flag<["-"], "mamx-fp16">, 
Group;
 def mno_amx_fp16 : Flag<["-"], "mno-amx-fp16">, Group;
 def mamx_int8 : Flag<["-"], "mamx-int8">, Group;
 def mno_amx_int8 : Flag<["-"], "mno-amx-int8">, Group;
+def mamx_fp8 : Flag<["-"], "mamx-fp8">, Group;
+def mno_amx_fp8 : Flag<["-"], "mno-amx-fp8">, Group;
 def mamx_tile : Flag<["-"], "mamx-tile">, Group;
 def mno_amx_tile : Flag<["-"], "mno-amx-tile">, Group;
 def mcmpccxadd : Flag<["-"], "mcmpccxadd">, Group;
diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index d067ec218b5270..b95261c39a5993 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -420,6 +420,8 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
   HasAMXTILE = true;
 } else if (Feature == "+amx-complex") {
   HasAMXCOMPLEX = true;
+} else if (Feature == "+amx-fp8") {
+  HasAMXFP8 = true;
 } else if (Feature == "+cmpccxadd") {
   HasCMPCCXADD = true;
 } else if (Feature == "+raoint") {
@@ -939,6 +941,8 @@ void X86TargetInfo::getTargetDefines(const LangOptions 
&Opts,
 Builder.defineMacro("__AMX_FP16__");
   if (HasAMXCOMPLEX)
 Builder.defineMacro("__AMX_COMPLEX__");
+  if (HasAMXFP8)
+Builder.defineMacro("__AMX_FP8__");
   if (HasCMPCCXADD)
 Builder.defineMacro("__CMPCCXADD__");
   if (HasRAOINT)
@@ -1069,6 +1073,7 @@ bool X86TargetInfo::isValidFeatureName(StringRef Name) 
const {
   .Case("amx-fp16", true)
   .Case("amx-int8", true)
   .Case("amx-tile", true)
+  .Case("amx-fp8", true)
   .Case("avx", true)
   .Case("avx10.1-256", true)
   .Case("avx10.1-512", true)
@@ -1187,6 +1192,7 @@ bool X86TargetInfo::hasFeature(StringRef Feature) const {
   .Case("amx-fp16", HasAMX

[clang] [llvm] [X86][AMX] Support AMX-FP8 (PR #113850)

2024-10-27 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 1fe8e7838bb5118b9e48fa15fa21a4638bae8ae1 
fd570cb8d41f5f94b61d515985245fc81aab633e --extensions c,cpp,h -- 
clang/lib/Headers/amxfp8intrin.h clang/test/CodeGen/X86/amx_fp8.c 
clang/test/CodeGen/X86/amx_fp8_errors.c 
clang/test/CodeGen/X86/amx_fp8_inline_asm.c clang/lib/Basic/Targets/X86.cpp 
clang/lib/Basic/Targets/X86.h clang/lib/Headers/immintrin.h 
clang/lib/Sema/SemaX86.cpp llvm/lib/Target/X86/X86ISelLowering.cpp 
llvm/lib/TargetParser/Host.cpp llvm/lib/TargetParser/X86TargetParser.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/Target/X86/X86ISelLowering.cpp 
b/llvm/lib/Target/X86/X86ISelLowering.cpp
index 5a7313ac3e..a83f392581 100644
--- a/llvm/lib/Target/X86/X86ISelLowering.cpp
+++ b/llvm/lib/Target/X86/X86ISelLowering.cpp
@@ -37509,12 +37509,21 @@ 
X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
   case X86::PTDPHF8PS: {
 const DebugLoc &DL = MI.getDebugLoc();
 unsigned Opc;
-switch(MI.getOpcode()) {
-  default: llvm_unreachable("Unexpected instruction!");
-  case X86::PTDPBF8PS: Opc = X86::TDPBF8PS; break;
-  case X86::PTDPBHF8PS: Opc = X86::TDPBHF8PS; break;
-  case X86::PTDPHBF8PS: Opc = X86::TDPHBF8PS; break;
-  case X86::PTDPHF8PS: Opc = X86::TDPHF8PS; break;
+switch (MI.getOpcode()) {
+default:
+  llvm_unreachable("Unexpected instruction!");
+case X86::PTDPBF8PS:
+  Opc = X86::TDPBF8PS;
+  break;
+case X86::PTDPBHF8PS:
+  Opc = X86::TDPBHF8PS;
+  break;
+case X86::PTDPHBF8PS:
+  Opc = X86::TDPHBF8PS;
+  break;
+case X86::PTDPHF8PS:
+  Opc = X86::TDPHF8PS;
+  break;
 }
 
 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));

``




https://github.com/llvm/llvm-project/pull/113850
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [X86][AMX] Support AMX-FP8 (PR #113850)

2024-10-27 Thread Feng Zou via cfe-commits

https://github.com/fzou1 updated 
https://github.com/llvm/llvm-project/pull/113850

>From fd570cb8d41f5f94b61d515985245fc81aab633e Mon Sep 17 00:00:00 2001
From: Feng Zou 
Date: Thu, 24 Oct 2024 21:56:48 +0800
Subject: [PATCH 1/2] Support AMX-FP8

Ref.: https://cdrdv2.intel.com/v1/dl/getContent/671368
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Basic/BuiltinsX86_64.def  |  6 +++
 clang/include/clang/Driver/Options.td |  2 +
 clang/lib/Basic/Targets/X86.cpp   |  6 +++
 clang/lib/Basic/Targets/X86.h |  1 +
 clang/lib/Headers/CMakeLists.txt  |  1 +
 clang/lib/Headers/amxfp8intrin.h  | 24 
 clang/lib/Headers/immintrin.h |  4 ++
 clang/lib/Sema/SemaX86.cpp|  4 ++
 clang/test/CodeGen/X86/amx_fp8.c  | 27 +
 clang/test/CodeGen/X86/amx_fp8_errors.c   | 10 +
 clang/test/CodeGen/X86/amx_fp8_inline_asm.c   | 32 +++
 llvm/include/llvm/IR/IntrinsicsX86.td | 17 
 .../llvm/TargetParser/X86TargetParser.def |  1 +
 llvm/lib/Target/X86/X86.td|  3 ++
 llvm/lib/Target/X86/X86ISelLowering.cpp   | 23 +++
 llvm/lib/Target/X86/X86InstrAMX.td| 39 +++
 llvm/lib/Target/X86/X86InstrPredicates.td |  1 +
 llvm/lib/TargetParser/Host.cpp|  4 ++
 llvm/lib/TargetParser/X86TargetParser.cpp |  1 +
 llvm/test/CodeGen/X86/amx_fp8_intrinsics.ll   | 20 ++
 .../Disassembler/X86/AMX/x86-64-amx-fp8.txt   | 34 
 llvm/test/MC/X86/AMX/x86-64-amx-fp8-att.s | 33 
 llvm/test/MC/X86/AMX/x86-64-amx-fp8-intel.s   | 33 
 24 files changed, 327 insertions(+)
 create mode 100644 clang/lib/Headers/amxfp8intrin.h
 create mode 100644 clang/test/CodeGen/X86/amx_fp8.c
 create mode 100644 clang/test/CodeGen/X86/amx_fp8_errors.c
 create mode 100644 clang/test/CodeGen/X86/amx_fp8_inline_asm.c
 create mode 100644 llvm/test/CodeGen/X86/amx_fp8_intrinsics.ll
 create mode 100644 llvm/test/MC/Disassembler/X86/AMX/x86-64-amx-fp8.txt
 create mode 100644 llvm/test/MC/X86/AMX/x86-64-amx-fp8-att.s
 create mode 100644 llvm/test/MC/X86/AMX/x86-64-amx-fp8-intel.s

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6a95337815174b..da0ab888ce200d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -642,6 +642,7 @@ X86 Support
 
 - Supported intrinsics for ``MOVRS AND AVX10.2``.
   * Supported intrinsics of ``_mm(256|512)_(mask(z))_loadrs_epi(8|16|32|64)``.
+- Support ISA of ``AMX-FP8``.
 
 Arm and AArch64 Support
 ^^^
diff --git a/clang/include/clang/Basic/BuiltinsX86_64.def 
b/clang/include/clang/Basic/BuiltinsX86_64.def
index e1e613560167ac..68904ae8abcd15 100644
--- a/clang/include/clang/Basic/BuiltinsX86_64.def
+++ b/clang/include/clang/Basic/BuiltinsX86_64.def
@@ -155,6 +155,12 @@ TARGET_BUILTIN(__builtin_ia32_cmpccxadd64, 
"SLLiv*SLLiSLLiIi", "n", "cmpccxadd")
 // AMX_FP16 FP16
 TARGET_BUILTIN(__builtin_ia32_tdpfp16ps, "vIUcIUcIUc", "n", "amx-fp16")
 
+// AMX FP8
+TARGET_BUILTIN(__builtin_ia32_tdpbf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+TARGET_BUILTIN(__builtin_ia32_tdpbhf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+TARGET_BUILTIN(__builtin_ia32_tdphbf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+TARGET_BUILTIN(__builtin_ia32_tdphf8ps, "vIUcUIcUIc", "n", "amx-fp8")
+
 // RAO-INT
 TARGET_BUILTIN(__builtin_ia32_aadd64, "vv*SOi", "n", "raoint")
 TARGET_BUILTIN(__builtin_ia32_aand64, "vv*SOi", "n", "raoint")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5df6ddd5e6a0c5..bbada0834526d7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6290,6 +6290,8 @@ def mamx_fp16 : Flag<["-"], "mamx-fp16">, 
Group;
 def mno_amx_fp16 : Flag<["-"], "mno-amx-fp16">, Group;
 def mamx_int8 : Flag<["-"], "mamx-int8">, Group;
 def mno_amx_int8 : Flag<["-"], "mno-amx-int8">, Group;
+def mamx_fp8 : Flag<["-"], "mamx-fp8">, Group;
+def mno_amx_fp8 : Flag<["-"], "mno-amx-fp8">, Group;
 def mamx_tile : Flag<["-"], "mamx-tile">, Group;
 def mno_amx_tile : Flag<["-"], "mno-amx-tile">, Group;
 def mcmpccxadd : Flag<["-"], "mcmpccxadd">, Group;
diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index d067ec218b5270..b95261c39a5993 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -420,6 +420,8 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
   HasAMXTILE = true;
 } else if (Feature == "+amx-complex") {
   HasAMXCOMPLEX = true;
+} else if (Feature == "+amx-fp8") {
+  HasAMXFP8 = true;
 } else if (Feature == "+cmpccxadd") {
   HasCMPCCXADD = true;
 } else if (Feature == "+raoint") {
@@ -939,6 +941,8 @@ void X86TargetInfo::getTargetDefines(const LangOptions 
&Opts,
 Builder.defineMacro("__AMX_FP16__");
   

[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -1216,10 +1308,225 @@ void DeclareImplicitDeductionGuidesForTypeAlias(
 ->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
   continue;
 
-BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate, F, Loc);
+BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate, F, Loc,
+DeducingTemplate, DerivedClassMapperType);
   }
 }
 
+void DeclareImplicitDeductionGuidesFromInheritedConstructors(
+Sema &SemaRef, TemplateDecl *Template, ClassTemplateDecl *Pattern,
+TypeSourceInfo *BaseTSI, unsigned BaseIdx) {
+  auto &Context = SemaRef.Context;
+  DeclContext *DC = Template->getDeclContext();
+  const auto *BaseTST = 
BaseTSI->getType()->getAs();
+  if (!BaseTST)
+return;
+  SourceLocation BaseLoc = BaseTSI->getTypeLoc().getBeginLoc();
+
+  TemplateDecl *BaseTD = BaseTST->getTemplateName().getAsTemplateDecl();
+  if (!BaseTD)
+return;
+
+  // Subsitute any parameters with default arguments not present in the base,
+  // since partial specializations cannot have default parameters

antangelo wrote:

I have added a link to the github issue for this and the other CWG issue. If 
CWG assigns a number to those issues I'll update the comment to use the proper 
number instead.

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits

antangelo wrote:

Thanks for the reviews!

> * can you give a description  if what needs to be done in subsequent PRs? 
> (maybe cxx_status.html should say "partial"
The remaining tasks are:
- Supporting dependent using-declarators such as `using Derived::Base::Base`. 
These are somewhat annoying to deal with, there isn't much of an existing 
mechanism (that I could find, at least) to look up the base type from the raw 
dependent identifier.
- Supporting deduction guides that are declared after the first lookup of 
deduction guides on the derived class. This is unimplemented due to a similar 
issue in alias template deduction that needs to be resolved first.

I have updated the cxx_status to partial, and added a note about the 
unsupported depdendent using-declarators. This aligns with the status for alias 
template deduction, which is partial due to the feature macro not being set. I 
presume the issue of deduction guides declared after the first lookup of 
deduction guides would be fixed in both features at the same time, either in 
this patch set if it is fixed in upstream first, or after this patch set as a 
followup.

> * can you add a release notes
There should already be a clang release note, are there any other spots besides 
ReleaseNotes.rst and cxx_status.html that need updating?

> * can you add PCH or module tests for the changes to ASTReader/ASTWriter?
I have added module tests that cover the feature.

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -58,7 +58,7 @@ inline InheritableAttr *getDLLAttr(Decl *D) {
 }
 
 /// Retrieve the depth and index of a template parameter.
-inline std::pair getDepthAndIndex(NamedDecl *ND) {
+inline std::pair getDepthAndIndex(const NamedDecl *ND) {

antangelo wrote:

I'll split this out into a separate patch

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)

2024-10-27 Thread via cfe-commits


@@ -0,0 +1,62 @@
+//===--- IncorrectEnableSharedFromThisCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "IncorrectEnableSharedFromThisCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void IncorrectEnableSharedFromThisCheck::registerMatchers(MatchFinder *Finder) 
{
+  const auto EnableSharedFromThis =
+  cxxRecordDecl(hasName("enable_shared_from_this"), isInStdNamespace());
+  const auto QType = hasCanonicalType(hasDeclaration(
+  cxxRecordDecl(
+  anyOf(EnableSharedFromThis.bind("enable_rec"),
+cxxRecordDecl(hasAnyBase(cxxBaseSpecifier(
+isPublic(), hasType(hasCanonicalType(
+hasDeclaration(EnableSharedFromThis
+  .bind("base_rec")));
+  Finder->addMatcher(
+  cxxRecordDecl(
+  hasDirectBase(cxxBaseSpecifier(unless(isPublic()), hasType(QType))
+.bind("base")))
+  .bind("derived"),
+  this);
+}
+
+void IncorrectEnableSharedFromThisCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *BaseSpec = Result.Nodes.getNodeAs("base");
+  const auto *Base = Result.Nodes.getNodeAs("base_rec");
+  const auto *Derived = Result.Nodes.getNodeAs("derived");
+  const bool IsEnableSharedFromThisDirectBase =
+  Result.Nodes.getNodeAs("enable_rec") == Base;
+  const SourceRange ReplacementRange = BaseSpec->getSourceRange();
+  const std::string ReplacementString =
+  // BaseSpec->getType().getAsString() results in
+  // std::enable_shared_from_this or
+  // alias/typedefs of std::enable_shared_from_this
+  "public " + BaseSpec->getType().getAsString();

MichelleCDjunaidi wrote:

will implement soon when I have the bandwidth.

https://github.com/llvm/llvm-project/pull/102299
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)

2024-10-27 Thread via cfe-commits


@@ -0,0 +1,62 @@
+//===--- IncorrectEnableSharedFromThisCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "IncorrectEnableSharedFromThisCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void IncorrectEnableSharedFromThisCheck::registerMatchers(MatchFinder *Finder) 
{
+  const auto EnableSharedFromThis =
+  cxxRecordDecl(hasName("enable_shared_from_this"), isInStdNamespace());
+  const auto QType = hasCanonicalType(hasDeclaration(
+  cxxRecordDecl(
+  anyOf(EnableSharedFromThis.bind("enable_rec"),
+cxxRecordDecl(hasAnyBase(cxxBaseSpecifier(
+isPublic(), hasType(hasCanonicalType(
+hasDeclaration(EnableSharedFromThis
+  .bind("base_rec")));
+  Finder->addMatcher(
+  cxxRecordDecl(
+  hasDirectBase(cxxBaseSpecifier(unless(isPublic()), hasType(QType))
+.bind("base")))
+  .bind("derived"),
+  this);
+}
+
+void IncorrectEnableSharedFromThisCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *BaseSpec = Result.Nodes.getNodeAs("base");
+  const auto *Base = Result.Nodes.getNodeAs("base_rec");
+  const auto *Derived = Result.Nodes.getNodeAs("derived");
+  const bool IsEnableSharedFromThisDirectBase =
+  Result.Nodes.getNodeAs("enable_rec") == Base;
+  const SourceRange ReplacementRange = BaseSpec->getSourceRange();
+  const std::string ReplacementString =
+  // BaseSpec->getType().getAsString() results in
+  // std::enable_shared_from_this or
+  // alias/typedefs of std::enable_shared_from_this
+  "public " + BaseSpec->getType().getAsString();
+  const FixItHint Hint =
+  FixItHint::CreateReplacement(ReplacementRange, ReplacementString);

MichelleCDjunaidi wrote:

fair enough, then just emit the warning and not the fix on transitive, is that 
what you're saying?

https://github.com/llvm/llvm-project/pull/102299
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)

2024-10-27 Thread via cfe-commits


@@ -0,0 +1,35 @@
+//===--- IncorrectEnableSharedFromThisCheck.h - clang-tidy --*- 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_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTENABLESHAREDFROMTHISCHECK_H
+#define 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTENABLESHAREDFROMTHISCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::bugprone {
+
+/// Detects if a class or struct publicly inherits from
+/// ``std::enable_shared_from_this``, because unintended behavior will
+/// otherwise occur when calling ``shared_from_this``.

MichelleCDjunaidi wrote:

fair enough, will do.

https://github.com/llvm/llvm-project/pull/102299
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [X86] Don't allow '+f' as an inline asm constraint. (PR #113871)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Craig Topper (topperc)


Changes

f cannot be used as an output constraint. We already errored for '=f' but not 
'+f'.

Fixes #113692.

---
Full diff: https://github.com/llvm/llvm-project/pull/113871.diff


2 Files Affected:

- (modified) clang/lib/Basic/Targets/X86.cpp (+1-1) 
- (modified) clang/test/Sema/asm.c (+6) 


``diff
diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index d067ec218b5270..700c2f9a5dbd18 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -1465,7 +1465,7 @@ bool X86TargetInfo::validateAsmConstraint(
 }
   case 'f': // Any x87 floating point stack register.
 // Constraint 'f' cannot be used for output operands.
-if (Info.ConstraintStr[0] == '=')
+if (Info.ConstraintStr[0] == '=' || Info.ConstraintStr[0] == '+')
   return false;
 Info.setAllowsRegister();
 return true;
diff --git a/clang/test/Sema/asm.c b/clang/test/Sema/asm.c
index 6cd95c71604d44..28ef3ec6ce09c2 100644
--- a/clang/test/Sema/asm.c
+++ b/clang/test/Sema/asm.c
@@ -204,6 +204,12 @@ double f_output_constraint(void) {
   return result;
 }
 
+double f_output_constraint_2(void) {
+  double result;
+  __asm("foo1": "+f" (result)); // expected-error {{invalid output constraint 
'+f' in asm}}
+  return result;
+}
+
 void fn1(void) {
   int l;
   __asm__(""

``




https://github.com/llvm/llvm-project/pull/113871
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [X86] Don't allow '+f' as an inline asm constraint. (PR #113871)

2024-10-27 Thread Craig Topper via cfe-commits

https://github.com/topperc created 
https://github.com/llvm/llvm-project/pull/113871

f cannot be used as an output constraint. We already errored for '=f' but not 
'+f'.

Fixes #113692.

>From 48c30e1a7d82c7124abbe6980b0495f6e05a5753 Mon Sep 17 00:00:00 2001
From: Craig Topper 
Date: Sun, 27 Oct 2024 23:44:31 -0700
Subject: [PATCH] [X86] Don't allow '+f' as an inline asm constraint.

f cannot be used as an output constraint. We already errored for
'=f' but not '+f'.

Fixes #113692.
---
 clang/lib/Basic/Targets/X86.cpp | 2 +-
 clang/test/Sema/asm.c   | 6 ++
 2 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index d067ec218b5270..700c2f9a5dbd18 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -1465,7 +1465,7 @@ bool X86TargetInfo::validateAsmConstraint(
 }
   case 'f': // Any x87 floating point stack register.
 // Constraint 'f' cannot be used for output operands.
-if (Info.ConstraintStr[0] == '=')
+if (Info.ConstraintStr[0] == '=' || Info.ConstraintStr[0] == '+')
   return false;
 Info.setAllowsRegister();
 return true;
diff --git a/clang/test/Sema/asm.c b/clang/test/Sema/asm.c
index 6cd95c71604d44..28ef3ec6ce09c2 100644
--- a/clang/test/Sema/asm.c
+++ b/clang/test/Sema/asm.c
@@ -204,6 +204,12 @@ double f_output_constraint(void) {
   return result;
 }
 
+double f_output_constraint_2(void) {
+  double result;
+  __asm("foo1": "+f" (result)); // expected-error {{invalid output constraint 
'+f' in asm}}
+  return result;
+}
+
 void fn1(void) {
   int l;
   __asm__(""

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] Insert `// NOLINTNEXTLINE(...)` for clang-tidy diagnostics (PR #111640)

2024-10-27 Thread Richard Li via cfe-commits

https://github.com/chomosuke closed 
https://github.com/llvm/llvm-project/pull/111640
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)

2024-10-27 Thread via cfe-commits

MichelleCDjunaidi wrote:

@5chmidti ah, so if I'm getting you correctly, next time I shouldn't rebase and 
just wait to fix the conflict on merge?

https://github.com/llvm/llvm-project/pull/102299
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add -ConfigFile option (PR #113864)

2024-10-27 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/113864

>From b5f89c18b22bbc07d2f4fcbc2896996efea52478 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 27 Oct 2024 22:22:11 -0700
Subject: [PATCH] [clang-format] Add -ConfigFile option

Close #107808.
---
 clang/include/clang/Format/Format.h |  5 +
 clang/lib/Format/Format.cpp | 17 +
 2 files changed, 22 insertions(+)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index c9b72e65cb236d..1380223493187a 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2481,6 +2481,10 @@ struct FormatStyle {
   /// \version 5
   bool CompactNamespaces;
 
+  ///
+  /// \version 20
+  std::string ConfigFile;
+
   /// This option is **deprecated**. See ``CurrentLine`` of
   /// ``PackConstructorInitializers``.
   /// \version 3.7
@@ -5195,6 +5199,7 @@ struct FormatStyle {
BreakTemplateDeclarations == R.BreakTemplateDeclarations &&
ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas 
&&
CompactNamespaces == R.CompactNamespaces &&
+   ConfigFile == R.ConfigFile &&
ConstructorInitializerIndentWidth ==
R.ConstructorInitializerIndentWidth &&
ContinuationIndentWidth == R.ContinuationIndentWidth &&
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 0cf4cdbeab31f3..379aec9e19a5fb 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1163,6 +1163,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TemplateNames", Style.TemplateNames);
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
+IO.mapOptional("ConfigFile", Style.ConfigFile);
 IO.mapOptional("UseTab", Style.UseTab);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
@@ -2046,6 +2047,11 @@ ParseError validateQualifierOrder(FormatStyle *Style) {
   return ParseError::Success;
 }
 
+llvm::ErrorOr>
+loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
+   FormatStyle *Style, bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler);
+
 std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
FormatStyle *Style, bool 
AllowUnknownOptions,
llvm::SourceMgr::DiagHandlerTy DiagHandler,
@@ -2102,6 +2108,17 @@ std::error_code parseConfiguration(llvm::MemoryBufferRef 
Config,
 StyleSet.Add(std::move(DefaultStyle));
   }
   *Style = *StyleSet.Get(Language);
+  std::string ConfigFile;
+  if (!Style->ConfigFile.empty()) {
+auto *FS = llvm::vfs::getRealFileSystem().get();
+assert(FS);
+ConfigFile = Style->ConfigFile;
+Style->ConfigFile.clear();
+const auto Text = loadAndParseConfigFile(ConfigFile, FS, Style,
+ AllowUnknownOptions, DiagHandler);
+if (Text.getError())
+  return make_error_code(ParseError::Error);
+  }
   if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
   Style->BinPackArguments) {
 // See comment on FormatStyle::TSC_Wrapped.

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [RISCV] Add the Sha extension (PR #113820)

2024-10-27 Thread Alex Bradbury via cfe-commits

https://github.com/asb created https://github.com/llvm/llvm-project/pull/113820

This was introduced in the now-ratified RVA23 profile (and also added to the 
RVA22 text) as a simple way of referring to H plus the set of supervisor 
extensions required by RVA23. 
https://github.com/riscv/riscv-profiles/blob/main/src/rva23-profile.adoc

This patch simply defines the extension. The next patch will adjust the RVA23 
profile to use it, and at that point I think we will be ready to mark RVA23 as 
non-experimental.

Note that I haven't made it so if you enable all extensions that constitute 
Sha, Sha is implied. Per #76893 (adding 'B'), the concern is making this 
implication might break older external assemblers. Perhaps this is less of a 
concern given the relative frequency of `-march=${foo}_zba_zbb_zbs` vs the 
collection of H extensions. If we did want to add that implication, we'd 
probably want to add it in a separate patch so it can be easily reverted if 
found to cause problems.

>From 0a6e4734def4cb8a3a601c0f4a4f4d5cdea3c990 Mon Sep 17 00:00:00 2001
From: Alex Bradbury 
Date: Sun, 27 Oct 2024 15:40:21 +
Subject: [PATCH] [RISCV] Add the Sha extension

This was introduced in the now-ratified RVA23 profile (and also added to
the RVA22 text) as a simple way of referring to H plus the set of
supervisor extensions required by RVA23.
---
 clang/test/Driver/print-supported-extensions-riscv.c | 1 +
 clang/test/Preprocessor/riscv-target-features.c  | 9 +
 llvm/docs/RISCVUsage.rst | 1 +
 llvm/docs/ReleaseNotes.md| 1 +
 llvm/lib/Target/RISCV/RISCVFeatures.td   | 7 +++
 llvm/test/CodeGen/RISCV/attributes.ll| 4 
 llvm/unittests/TargetParser/RISCVISAInfoTest.cpp | 1 +
 7 files changed, 24 insertions(+)

diff --git a/clang/test/Driver/print-supported-extensions-riscv.c 
b/clang/test/Driver/print-supported-extensions-riscv.c
index 342d6e921a5a83..fc8a9c04667b6b 100644
--- a/clang/test/Driver/print-supported-extensions-riscv.c
+++ b/clang/test/Driver/print-supported-extensions-riscv.c
@@ -110,6 +110,7 @@
 // CHECK-NEXT: zvl8192b 1.0   'Zvl' (Minimum Vector 
Length) 8192
 // CHECK-NEXT: zhinx1.0   'Zhinx' (Half Float in 
Integer)
 // CHECK-NEXT: zhinxmin 1.0   'Zhinxmin' (Half Float in 
Integer Minimal)
+// CHECK-NEXT: sha  1.0   'Sha' (Augmented Hypervisor)
 // CHECK-NEXT: shcounterenw 1.0   'Shcounterenw' (Support 
writeable hcounteren enable bit for any hpmcounter that is not read-only zero)
 // CHECK-NEXT: shgatpa  1.0   'Sgatpa' (SvNNx4 mode 
supported for all modes supported by satp, as well as Bare)
 // CHECK-NEXT: shtvala  1.0   'Shtvala' (htval provides 
all needed values)
diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 98ad564d2b8408..6e586714af84d3 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -20,6 +20,7 @@
 // CHECK-NOT: __riscv_m {{.*$}}
 // CHECK-NOT: __riscv_mul {{.*$}}
 // CHECK-NOT: __riscv_muldiv {{.*$}}
+// CHECK-NOT: __riscv_sha {{.*$}}
 // CHECK-NOT: __riscv_shcounterenw {{.*$}}
 // CHECK-NOT: __riscv_shgatpa {{.*$}}
 // CHECK-NOT: __riscv_shtvala {{.*$}}
@@ -323,6 +324,14 @@
 // CHECK-M-EXT: __riscv_mul 1
 // CHECK-M-EXT: __riscv_muldiv 1
 
+// RUN: %clang --target=riscv32-unknown-linux-gnu \
+// RUN:   -march=rv32isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// RUN: %clang --target=riscv64-unknown-linux-gnu \
+// RUN:   -march=rv64isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// CHECK-SHA-EXT: __riscv_sha 100{{$}}
+
 // RUN: %clang --target=riscv32-unknown-linux-gnu \
 // RUN:   -march=rv32ishcounterenw -E -dM %s \
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index ab58cdaa1b2f95..6075a2289d473d 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -119,6 +119,7 @@ on support follow.
  ``E`` Supported (`See note <#riscv-rve-note>`__)
  ``H`` Assembly Support
  ``M`` Supported
+ ``Sha``   Supported
  ``Shcounterenw``  Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shgatpa``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shtvala``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
diff --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md
index e3d93f0dfd0ec5..6ee312aee8c53c 100644
--- a/llvm/docs/ReleaseNotes.md
+++ b/llvm/docs/ReleaseNotes.md
@@ -176,6 +176,7 @@ Changes to the RISC-V Backend
 * The `Zacas` extension is no longer marked as experimental.
 * The `Smm

[clang] [llvm] [RISCV] Add the Sha extension (PR #113820)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-risc-v

Author: Alex Bradbury (asb)


Changes

This was introduced in the now-ratified RVA23 profile (and also added to the 
RVA22 text) as a simple way of referring to H plus the set of supervisor 
extensions required by RVA23. 
https://github.com/riscv/riscv-profiles/blob/main/src/rva23-profile.adoc

This patch simply defines the extension. The next patch will adjust the RVA23 
profile to use it, and at that point I think we will be ready to mark RVA23 as 
non-experimental.

Note that I haven't made it so if you enable all extensions that constitute 
Sha, Sha is implied. Per #76893 (adding 'B'), the concern is making 
this implication might break older external assemblers. Perhaps this is less of 
a concern given the relative frequency of `-march=${foo}_zba_zbb_zbs` vs the 
collection of H extensions. If we did want to add that implication, we'd 
probably want to add it in a separate patch so it can be easily reverted if 
found to cause problems.

---
Full diff: https://github.com/llvm/llvm-project/pull/113820.diff


7 Files Affected:

- (modified) clang/test/Driver/print-supported-extensions-riscv.c (+1) 
- (modified) clang/test/Preprocessor/riscv-target-features.c (+9) 
- (modified) llvm/docs/RISCVUsage.rst (+1) 
- (modified) llvm/docs/ReleaseNotes.md (+1) 
- (modified) llvm/lib/Target/RISCV/RISCVFeatures.td (+7) 
- (modified) llvm/test/CodeGen/RISCV/attributes.ll (+4) 
- (modified) llvm/unittests/TargetParser/RISCVISAInfoTest.cpp (+1) 


``diff
diff --git a/clang/test/Driver/print-supported-extensions-riscv.c 
b/clang/test/Driver/print-supported-extensions-riscv.c
index 342d6e921a5a83..fc8a9c04667b6b 100644
--- a/clang/test/Driver/print-supported-extensions-riscv.c
+++ b/clang/test/Driver/print-supported-extensions-riscv.c
@@ -110,6 +110,7 @@
 // CHECK-NEXT: zvl8192b 1.0   'Zvl' (Minimum Vector 
Length) 8192
 // CHECK-NEXT: zhinx1.0   'Zhinx' (Half Float in 
Integer)
 // CHECK-NEXT: zhinxmin 1.0   'Zhinxmin' (Half Float in 
Integer Minimal)
+// CHECK-NEXT: sha  1.0   'Sha' (Augmented Hypervisor)
 // CHECK-NEXT: shcounterenw 1.0   'Shcounterenw' (Support 
writeable hcounteren enable bit for any hpmcounter that is not read-only zero)
 // CHECK-NEXT: shgatpa  1.0   'Sgatpa' (SvNNx4 mode 
supported for all modes supported by satp, as well as Bare)
 // CHECK-NEXT: shtvala  1.0   'Shtvala' (htval provides 
all needed values)
diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 98ad564d2b8408..6e586714af84d3 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -20,6 +20,7 @@
 // CHECK-NOT: __riscv_m {{.*$}}
 // CHECK-NOT: __riscv_mul {{.*$}}
 // CHECK-NOT: __riscv_muldiv {{.*$}}
+// CHECK-NOT: __riscv_sha {{.*$}}
 // CHECK-NOT: __riscv_shcounterenw {{.*$}}
 // CHECK-NOT: __riscv_shgatpa {{.*$}}
 // CHECK-NOT: __riscv_shtvala {{.*$}}
@@ -323,6 +324,14 @@
 // CHECK-M-EXT: __riscv_mul 1
 // CHECK-M-EXT: __riscv_muldiv 1
 
+// RUN: %clang --target=riscv32-unknown-linux-gnu \
+// RUN:   -march=rv32isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// RUN: %clang --target=riscv64-unknown-linux-gnu \
+// RUN:   -march=rv64isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// CHECK-SHA-EXT: __riscv_sha 100{{$}}
+
 // RUN: %clang --target=riscv32-unknown-linux-gnu \
 // RUN:   -march=rv32ishcounterenw -E -dM %s \
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index ab58cdaa1b2f95..6075a2289d473d 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -119,6 +119,7 @@ on support follow.
  ``E`` Supported (`See note <#riscv-rve-note>`__)
  ``H`` Assembly Support
  ``M`` Supported
+ ``Sha``   Supported
  ``Shcounterenw``  Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shgatpa``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shtvala``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
diff --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md
index e3d93f0dfd0ec5..6ee312aee8c53c 100644
--- a/llvm/docs/ReleaseNotes.md
+++ b/llvm/docs/ReleaseNotes.md
@@ -176,6 +176,7 @@ Changes to the RISC-V Backend
 * The `Zacas` extension is no longer marked as experimental.
 * The `Smmpm`, `Smnpm`, `Ssnpm`, `Supm`, and `Sspm` pointer masking extensions
   are no longer marked as experimental.
+* The `Sha` extension is now supported.
 
 Changes to the WebAssembly Backend
 --
diff --git a/llvm/lib/Target/RISCV/RISCVFeatures.td 
b/llvm/lib/Target/RISCV/RI

[clang] [llvm] [RISCV] Add the Sha extension (PR #113820)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alex Bradbury (asb)


Changes

This was introduced in the now-ratified RVA23 profile (and also added to the 
RVA22 text) as a simple way of referring to H plus the set of supervisor 
extensions required by RVA23. 
https://github.com/riscv/riscv-profiles/blob/main/src/rva23-profile.adoc

This patch simply defines the extension. The next patch will adjust the RVA23 
profile to use it, and at that point I think we will be ready to mark RVA23 as 
non-experimental.

Note that I haven't made it so if you enable all extensions that constitute 
Sha, Sha is implied. Per #76893 (adding 'B'), the concern is making 
this implication might break older external assemblers. Perhaps this is less of 
a concern given the relative frequency of `-march=${foo}_zba_zbb_zbs` vs the 
collection of H extensions. If we did want to add that implication, we'd 
probably want to add it in a separate patch so it can be easily reverted if 
found to cause problems.

---
Full diff: https://github.com/llvm/llvm-project/pull/113820.diff


7 Files Affected:

- (modified) clang/test/Driver/print-supported-extensions-riscv.c (+1) 
- (modified) clang/test/Preprocessor/riscv-target-features.c (+9) 
- (modified) llvm/docs/RISCVUsage.rst (+1) 
- (modified) llvm/docs/ReleaseNotes.md (+1) 
- (modified) llvm/lib/Target/RISCV/RISCVFeatures.td (+7) 
- (modified) llvm/test/CodeGen/RISCV/attributes.ll (+4) 
- (modified) llvm/unittests/TargetParser/RISCVISAInfoTest.cpp (+1) 


``diff
diff --git a/clang/test/Driver/print-supported-extensions-riscv.c 
b/clang/test/Driver/print-supported-extensions-riscv.c
index 342d6e921a5a83..fc8a9c04667b6b 100644
--- a/clang/test/Driver/print-supported-extensions-riscv.c
+++ b/clang/test/Driver/print-supported-extensions-riscv.c
@@ -110,6 +110,7 @@
 // CHECK-NEXT: zvl8192b 1.0   'Zvl' (Minimum Vector 
Length) 8192
 // CHECK-NEXT: zhinx1.0   'Zhinx' (Half Float in 
Integer)
 // CHECK-NEXT: zhinxmin 1.0   'Zhinxmin' (Half Float in 
Integer Minimal)
+// CHECK-NEXT: sha  1.0   'Sha' (Augmented Hypervisor)
 // CHECK-NEXT: shcounterenw 1.0   'Shcounterenw' (Support 
writeable hcounteren enable bit for any hpmcounter that is not read-only zero)
 // CHECK-NEXT: shgatpa  1.0   'Sgatpa' (SvNNx4 mode 
supported for all modes supported by satp, as well as Bare)
 // CHECK-NEXT: shtvala  1.0   'Shtvala' (htval provides 
all needed values)
diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 98ad564d2b8408..6e586714af84d3 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -20,6 +20,7 @@
 // CHECK-NOT: __riscv_m {{.*$}}
 // CHECK-NOT: __riscv_mul {{.*$}}
 // CHECK-NOT: __riscv_muldiv {{.*$}}
+// CHECK-NOT: __riscv_sha {{.*$}}
 // CHECK-NOT: __riscv_shcounterenw {{.*$}}
 // CHECK-NOT: __riscv_shgatpa {{.*$}}
 // CHECK-NOT: __riscv_shtvala {{.*$}}
@@ -323,6 +324,14 @@
 // CHECK-M-EXT: __riscv_mul 1
 // CHECK-M-EXT: __riscv_muldiv 1
 
+// RUN: %clang --target=riscv32-unknown-linux-gnu \
+// RUN:   -march=rv32isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// RUN: %clang --target=riscv64-unknown-linux-gnu \
+// RUN:   -march=rv64isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// CHECK-SHA-EXT: __riscv_sha 100{{$}}
+
 // RUN: %clang --target=riscv32-unknown-linux-gnu \
 // RUN:   -march=rv32ishcounterenw -E -dM %s \
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index ab58cdaa1b2f95..6075a2289d473d 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -119,6 +119,7 @@ on support follow.
  ``E`` Supported (`See note <#riscv-rve-note>`__)
  ``H`` Assembly Support
  ``M`` Supported
+ ``Sha``   Supported
  ``Shcounterenw``  Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shgatpa``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shtvala``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
diff --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md
index e3d93f0dfd0ec5..6ee312aee8c53c 100644
--- a/llvm/docs/ReleaseNotes.md
+++ b/llvm/docs/ReleaseNotes.md
@@ -176,6 +176,7 @@ Changes to the RISC-V Backend
 * The `Zacas` extension is no longer marked as experimental.
 * The `Smmpm`, `Smnpm`, `Ssnpm`, `Supm`, and `Sspm` pointer masking extensions
   are no longer marked as experimental.
+* The `Sha` extension is now supported.
 
 Changes to the WebAssembly Backend
 --
diff --git a/llvm/lib/Target/RISCV/RISCVFeatures.td 
b/llvm/lib/Target/RISCV/RISCVFeatur

[clang] [clang] Prefer StringRef::substr(0, N) to slice(0, N) (NFC) (PR #113784)

2024-10-27 Thread Michael Maitland via cfe-commits

michaelmaitland wrote:

Should we agree on https://github.com/llvm/llvm-project/pull/113793, and then 
the same decision taken here?

https://github.com/llvm/llvm-project/pull/113784
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Add __ugly__ spelling for the msvc attribute scope (PR #113765)

2024-10-27 Thread Stephan T. Lavavej via cfe-commits

StephanTLavavej wrote:

Yeah, it would be great if C1XX (MSVC's frontend) supported `__meow__` as a 
synonym for `meow`.

I've occasionally gone into the FE and just implemented features; this one 
might be within my reach.

https://github.com/llvm/llvm-project/pull/113765
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Prefer StringRef::substr(0, N) to slice(0, N) (NFC) (PR #113784)

2024-10-27 Thread Jakub Kuderski via cfe-commits

https://github.com/kuhar approved this pull request.


https://github.com/llvm/llvm-project/pull/113784
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [SYCL] The sycl_kernel_entry_point attribute. (PR #111389)

2024-10-27 Thread Tom Honermann via cfe-commits


@@ -14296,6 +14296,30 @@ void 
ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap,
   }
 }
 
+static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context,

tahonermann wrote:

Done.

https://github.com/llvm/llvm-project/pull/111389
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [RISCV] Use Sha extension in RVA23S64 profile (PR #113823)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alex Bradbury (asb)


Changes

Stacks on top of #113820

In the ratified version of the RVA23S64 definition, the Sha extension is
now used to group together the set of hypervisor related extensions.

;


---
Full diff: https://github.com/llvm/llvm-project/pull/113823.diff


8 Files Affected:

- (modified) clang/test/Driver/print-supported-extensions-riscv.c (+1) 
- (modified) clang/test/Preprocessor/riscv-target-features.c (+9) 
- (modified) llvm/docs/RISCVUsage.rst (+1) 
- (modified) llvm/docs/ReleaseNotes.md (+1) 
- (modified) llvm/lib/Target/RISCV/RISCVFeatures.td (+7) 
- (modified) llvm/lib/Target/RISCV/RISCVProfiles.td (+1-8) 
- (modified) llvm/test/CodeGen/RISCV/attributes.ll (+5-1) 
- (modified) llvm/unittests/TargetParser/RISCVISAInfoTest.cpp (+1) 


``diff
diff --git a/clang/test/Driver/print-supported-extensions-riscv.c 
b/clang/test/Driver/print-supported-extensions-riscv.c
index 342d6e921a5a83..fc8a9c04667b6b 100644
--- a/clang/test/Driver/print-supported-extensions-riscv.c
+++ b/clang/test/Driver/print-supported-extensions-riscv.c
@@ -110,6 +110,7 @@
 // CHECK-NEXT: zvl8192b 1.0   'Zvl' (Minimum Vector 
Length) 8192
 // CHECK-NEXT: zhinx1.0   'Zhinx' (Half Float in 
Integer)
 // CHECK-NEXT: zhinxmin 1.0   'Zhinxmin' (Half Float in 
Integer Minimal)
+// CHECK-NEXT: sha  1.0   'Sha' (Augmented Hypervisor)
 // CHECK-NEXT: shcounterenw 1.0   'Shcounterenw' (Support 
writeable hcounteren enable bit for any hpmcounter that is not read-only zero)
 // CHECK-NEXT: shgatpa  1.0   'Sgatpa' (SvNNx4 mode 
supported for all modes supported by satp, as well as Bare)
 // CHECK-NEXT: shtvala  1.0   'Shtvala' (htval provides 
all needed values)
diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 98ad564d2b8408..6e586714af84d3 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -20,6 +20,7 @@
 // CHECK-NOT: __riscv_m {{.*$}}
 // CHECK-NOT: __riscv_mul {{.*$}}
 // CHECK-NOT: __riscv_muldiv {{.*$}}
+// CHECK-NOT: __riscv_sha {{.*$}}
 // CHECK-NOT: __riscv_shcounterenw {{.*$}}
 // CHECK-NOT: __riscv_shgatpa {{.*$}}
 // CHECK-NOT: __riscv_shtvala {{.*$}}
@@ -323,6 +324,14 @@
 // CHECK-M-EXT: __riscv_mul 1
 // CHECK-M-EXT: __riscv_muldiv 1
 
+// RUN: %clang --target=riscv32-unknown-linux-gnu \
+// RUN:   -march=rv32isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// RUN: %clang --target=riscv64-unknown-linux-gnu \
+// RUN:   -march=rv64isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// CHECK-SHA-EXT: __riscv_sha 100{{$}}
+
 // RUN: %clang --target=riscv32-unknown-linux-gnu \
 // RUN:   -march=rv32ishcounterenw -E -dM %s \
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index ab58cdaa1b2f95..6075a2289d473d 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -119,6 +119,7 @@ on support follow.
  ``E`` Supported (`See note <#riscv-rve-note>`__)
  ``H`` Assembly Support
  ``M`` Supported
+ ``Sha``   Supported
  ``Shcounterenw``  Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shgatpa``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shtvala``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
diff --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md
index e3d93f0dfd0ec5..6ee312aee8c53c 100644
--- a/llvm/docs/ReleaseNotes.md
+++ b/llvm/docs/ReleaseNotes.md
@@ -176,6 +176,7 @@ Changes to the RISC-V Backend
 * The `Zacas` extension is no longer marked as experimental.
 * The `Smmpm`, `Smnpm`, `Ssnpm`, `Supm`, and `Sspm` pointer masking extensions
   are no longer marked as experimental.
+* The `Sha` extension is now supported.
 
 Changes to the WebAssembly Backend
 --
diff --git a/llvm/lib/Target/RISCV/RISCVFeatures.td 
b/llvm/lib/Target/RISCV/RISCVFeatures.td
index 778df542022f22..559f0e5950eddd 100644
--- a/llvm/lib/Target/RISCV/RISCVFeatures.td
+++ b/llvm/lib/Target/RISCV/RISCVFeatures.td
@@ -1029,6 +1029,13 @@ def FeatureStdExtSvpbmt
 : RISCVExtension<"svpbmt", 1, 0,
  "'Svpbmt' (Page-Based Memory Types)">;
 
+def FeatureStdExtSha
+: RISCVExtension<"sha", 1, 0,
+ "'Sha' (Augmented Hypervisor)",
+ [FeatureStdExtH, FeatureStdExtSsstateen, 
FeatureStdExtShcounterenw,
+  FeatureStdExtShvstvala, FeatureStdExtShtvala, 
FeatureStdExtShvstvecd,
+  F

[clang] [llvm] [RISCV] Use Sha extension in RVA23S64 profile (PR #113823)

2024-10-27 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-risc-v

@llvm/pr-subscribers-clang-driver

Author: Alex Bradbury (asb)


Changes

Stacks on top of #113820

In the ratified version of the RVA23S64 definition, the Sha extension is
now used to group together the set of hypervisor related extensions.

;


---
Full diff: https://github.com/llvm/llvm-project/pull/113823.diff


8 Files Affected:

- (modified) clang/test/Driver/print-supported-extensions-riscv.c (+1) 
- (modified) clang/test/Preprocessor/riscv-target-features.c (+9) 
- (modified) llvm/docs/RISCVUsage.rst (+1) 
- (modified) llvm/docs/ReleaseNotes.md (+1) 
- (modified) llvm/lib/Target/RISCV/RISCVFeatures.td (+7) 
- (modified) llvm/lib/Target/RISCV/RISCVProfiles.td (+1-8) 
- (modified) llvm/test/CodeGen/RISCV/attributes.ll (+5-1) 
- (modified) llvm/unittests/TargetParser/RISCVISAInfoTest.cpp (+1) 


``diff
diff --git a/clang/test/Driver/print-supported-extensions-riscv.c 
b/clang/test/Driver/print-supported-extensions-riscv.c
index 342d6e921a5a83..fc8a9c04667b6b 100644
--- a/clang/test/Driver/print-supported-extensions-riscv.c
+++ b/clang/test/Driver/print-supported-extensions-riscv.c
@@ -110,6 +110,7 @@
 // CHECK-NEXT: zvl8192b 1.0   'Zvl' (Minimum Vector 
Length) 8192
 // CHECK-NEXT: zhinx1.0   'Zhinx' (Half Float in 
Integer)
 // CHECK-NEXT: zhinxmin 1.0   'Zhinxmin' (Half Float in 
Integer Minimal)
+// CHECK-NEXT: sha  1.0   'Sha' (Augmented Hypervisor)
 // CHECK-NEXT: shcounterenw 1.0   'Shcounterenw' (Support 
writeable hcounteren enable bit for any hpmcounter that is not read-only zero)
 // CHECK-NEXT: shgatpa  1.0   'Sgatpa' (SvNNx4 mode 
supported for all modes supported by satp, as well as Bare)
 // CHECK-NEXT: shtvala  1.0   'Shtvala' (htval provides 
all needed values)
diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 98ad564d2b8408..6e586714af84d3 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -20,6 +20,7 @@
 // CHECK-NOT: __riscv_m {{.*$}}
 // CHECK-NOT: __riscv_mul {{.*$}}
 // CHECK-NOT: __riscv_muldiv {{.*$}}
+// CHECK-NOT: __riscv_sha {{.*$}}
 // CHECK-NOT: __riscv_shcounterenw {{.*$}}
 // CHECK-NOT: __riscv_shgatpa {{.*$}}
 // CHECK-NOT: __riscv_shtvala {{.*$}}
@@ -323,6 +324,14 @@
 // CHECK-M-EXT: __riscv_mul 1
 // CHECK-M-EXT: __riscv_muldiv 1
 
+// RUN: %clang --target=riscv32-unknown-linux-gnu \
+// RUN:   -march=rv32isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// RUN: %clang --target=riscv64-unknown-linux-gnu \
+// RUN:   -march=rv64isha -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
+// CHECK-SHA-EXT: __riscv_sha 100{{$}}
+
 // RUN: %clang --target=riscv32-unknown-linux-gnu \
 // RUN:   -march=rv32ishcounterenw -E -dM %s \
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SHCOUNTERENW-EXT %s
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index ab58cdaa1b2f95..6075a2289d473d 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -119,6 +119,7 @@ on support follow.
  ``E`` Supported (`See note <#riscv-rve-note>`__)
  ``H`` Assembly Support
  ``M`` Supported
+ ``Sha``   Supported
  ``Shcounterenw``  Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shgatpa``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
  ``Shtvala``   Assembly Support (`See note 
<#riscv-profiles-extensions-note>`__)
diff --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md
index e3d93f0dfd0ec5..6ee312aee8c53c 100644
--- a/llvm/docs/ReleaseNotes.md
+++ b/llvm/docs/ReleaseNotes.md
@@ -176,6 +176,7 @@ Changes to the RISC-V Backend
 * The `Zacas` extension is no longer marked as experimental.
 * The `Smmpm`, `Smnpm`, `Ssnpm`, `Supm`, and `Sspm` pointer masking extensions
   are no longer marked as experimental.
+* The `Sha` extension is now supported.
 
 Changes to the WebAssembly Backend
 --
diff --git a/llvm/lib/Target/RISCV/RISCVFeatures.td 
b/llvm/lib/Target/RISCV/RISCVFeatures.td
index 778df542022f22..559f0e5950eddd 100644
--- a/llvm/lib/Target/RISCV/RISCVFeatures.td
+++ b/llvm/lib/Target/RISCV/RISCVFeatures.td
@@ -1029,6 +1029,13 @@ def FeatureStdExtSvpbmt
 : RISCVExtension<"svpbmt", 1, 0,
  "'Svpbmt' (Page-Based Memory Types)">;
 
+def FeatureStdExtSha
+: RISCVExtension<"sha", 1, 0,
+ "'Sha' (Augmented Hypervisor)",
+ [FeatureStdExtH, FeatureStdExtSsstateen, 
FeatureStdExtShcounterenw,
+  FeatureStdExtShvstvala, FeatureStdExtShtvala, 
Featu

[clang] [SYCL] The sycl_kernel_entry_point attribute. (PR #111389)

2024-10-27 Thread Tom Honermann via cfe-commits

https://github.com/tahonermann updated 
https://github.com/llvm/llvm-project/pull/111389

>From 3c4a2b8a52d3f1c730df88a308dece21a67834ef Mon Sep 17 00:00:00 2001
From: Tom Honermann 
Date: Fri, 4 Oct 2024 11:10:32 -0700
Subject: [PATCH 1/4] [SYCL] The sycl_kernel_entry_point attribute.

The `sycl_kernel_entry_point` attribute is used to declare a function that
defines a pattern for an offload kernel to be emitted. The attribute requires
a single type argument that specifies the type used as a SYCL kernel name as
described in section 5.2, "Naming of kernels", of the SYCL 2020 specification.

Properties of the offload kernel are collected when a function declared with
the `sycl_kernel_entry_point` attribute is parsed or instantiated. These
properties, such as the kernel name type, are stored in the AST context where
they are (or will be) used for diagnostic purposes and to facilitate reflection
to a SYCL run-time library. These properties are not serialized with the AST
but are recreated upon deserialization.

The `sycl_kernel_entry_point` attribute is intended to replace the existing
`sycl_kernel` attribute which is intended to be deprecated in a future change
and removed following an appropriate deprecation period. The new attribute
differs in that it is enabled for both SYCL host and device compilation, may
be used with non-template functions, explicitly indicates the type used as
the kernel name type, and will impact AST generation.

This change adds the basic infrastructure for the new attribute. Future
changes will add diagnostics and new AST support that will be used to drive
generation of the corresponding offload kernel.
---
 clang/include/clang/AST/ASTContext.h  |  12 ++
 clang/include/clang/AST/SYCLKernelInfo.h  |  47 ++
 clang/include/clang/Basic/Attr.td |  16 +-
 clang/include/clang/Basic/AttrDocs.td |  58 +++
 clang/include/clang/Sema/SemaSYCL.h   |   1 +
 clang/lib/AST/ASTContext.cpp  |  25 +++
 clang/lib/Sema/SemaDecl.cpp   |   4 +
 clang/lib/Sema/SemaDeclAttr.cpp   |   3 +
 clang/lib/Sema/SemaSYCL.cpp   |   9 ++
 clang/lib/Serialization/ASTReaderDecl.cpp |   9 ++
 .../ast-dump-sycl-kernel-entry-point.cpp  | 144 ++
 ...a-attribute-supported-attributes-list.test |   1 +
 .../sycl-kernel-entry-point-attr-grammar.cpp  | 137 +
 .../sycl-kernel-entry-point-attr-ignored.cpp  |  17 +++
 14 files changed, 480 insertions(+), 3 deletions(-)
 create mode 100644 clang/include/clang/AST/SYCLKernelInfo.h
 create mode 100644 clang/test/ASTSYCL/ast-dump-sycl-kernel-entry-point.cpp
 create mode 100644 clang/test/SemaSYCL/sycl-kernel-entry-point-attr-grammar.cpp
 create mode 100644 clang/test/SemaSYCL/sycl-kernel-entry-point-attr-ignored.cpp

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index b65a1f7dff5bc1..e68f0a4da57b16 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -23,6 +23,7 @@
 #include "clang/AST/ExternalASTSource.h"
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/RawCommentList.h"
+#include "clang/AST/SYCLKernelInfo.h"
 #include "clang/AST/TemplateName.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/PartialDiagnostic.h"
@@ -1222,6 +1223,11 @@ class ASTContext : public RefCountedBase {
   /// in device compilation.
   llvm::DenseSet CUDAImplicitHostDeviceFunUsedByDevice;
 
+  /// Map of SYCL kernels indexed by the unique type used to name the kernel.
+  /// Entries are not serialized but are recreated on deserialization of a
+  /// sycl_kernel_entry_point attributed function declaration.
+  llvm::DenseMap SYCLKernels;
+
   /// For capturing lambdas with an explicit object parameter whose type is
   /// derived from the lambda type, we need to perform derived-to-base
   /// conversion so we can access the captures; the cast paths for that
@@ -3301,6 +3307,12 @@ class ASTContext : public RefCountedBase {
   void getFunctionFeatureMap(llvm::StringMap &FeatureMap,
  GlobalDecl GD) const;
 
+  /// Generates and stores SYCL kernel metadata for the provided
+  /// SYCL kernel entry point function. The provided function must have
+  /// an attached sycl_kernel_entry_point attribute that specifies a unique
+  /// type for the name of a SYCL kernel.
+  void registerSYCLEntryPointFunction(FunctionDecl *FD);
+
   
//======//
   //Statistics
   
//======//
diff --git a/clang/include/clang/AST/SYCLKernelInfo.h 
b/clang/include/clang/AST/SYCLKernelInfo.h
new file mode 100644
index 00..79a83330f1d23b
--- /dev/null
+++ b/clang/include/clang/AST/SYCLKernelInfo.h
@@ -0,0 +1,47 @@
+//===--- SYCLKernelInfo.h --- Information about SYCL kernels 
--===//
+//
+// P

[clang] [clang-tools-extra] [clangd] Support parsing comments without ASTContext (PR #78491)

2024-10-27 Thread Tom Praschan via cfe-commits

tom-anders wrote:

Hi everyone, I shifted focus to other projects and currently don't have time to 
work on this PR anymore. If somebody wants to take over, feel free to do so

https://github.com/llvm/llvm-project/pull/78491
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [RISCV]Add svvptc extension (PR #113758)

2024-10-27 Thread Pengcheng Wang via cfe-commits

https://github.com/wangpc-pp commented:

Please update ReleaseNotes.

https://github.com/llvm/llvm-project/pull/113758
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] fix false positive for implicit conversion of comparison result in C23 (PR #113639)

2024-10-27 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 closed 
https://github.com/llvm/llvm-project/pull/113639
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][NFC] Accept const NamedDecl pointer for getDepthAndIndex (PR #113857)

2024-10-27 Thread via cfe-commits

https://github.com/antangelo created 
https://github.com/llvm/llvm-project/pull/113857

None

>From 9ba109b5e3eae0fc42939ead72991fc17dcd3d0a Mon Sep 17 00:00:00 2001
From: antangelo 
Date: Sun, 27 Oct 2024 22:41:24 -0400
Subject: [PATCH] [clang][NFC] Accept const NamedDecl pointer for
 getDepthAndIndex

---
 clang/include/clang/Sema/SemaInternal.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Sema/SemaInternal.h 
b/clang/include/clang/Sema/SemaInternal.h
index d994d1819b4423..41d05b2bfb078e 100644
--- a/clang/include/clang/Sema/SemaInternal.h
+++ b/clang/include/clang/Sema/SemaInternal.h
@@ -58,7 +58,7 @@ inline InheritableAttr *getDLLAttr(Decl *D) {
 }
 
 /// Retrieve the depth and index of a template parameter.
-inline std::pair getDepthAndIndex(NamedDecl *ND) {
+inline std::pair getDepthAndIndex(const NamedDecl *ND) {
   if (const auto *TTP = dyn_cast(ND))
 return std::make_pair(TTP->getDepth(), TTP->getIndex());
 

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c876d71 - [clang][NFC] Accept const NamedDecl pointer for getDepthAndIndex (#113857)

2024-10-27 Thread via cfe-commits

Author: antangelo
Date: 2024-10-28T00:25:56-04:00
New Revision: c876d719ef5b10128eca6d8677068248b4831017

URL: 
https://github.com/llvm/llvm-project/commit/c876d719ef5b10128eca6d8677068248b4831017
DIFF: 
https://github.com/llvm/llvm-project/commit/c876d719ef5b10128eca6d8677068248b4831017.diff

LOG: [clang][NFC] Accept const NamedDecl pointer for getDepthAndIndex (#113857)

Added: 


Modified: 
clang/include/clang/Sema/SemaInternal.h

Removed: 




diff  --git a/clang/include/clang/Sema/SemaInternal.h 
b/clang/include/clang/Sema/SemaInternal.h
index d994d1819b4423..41d05b2bfb078e 100644
--- a/clang/include/clang/Sema/SemaInternal.h
+++ b/clang/include/clang/Sema/SemaInternal.h
@@ -58,7 +58,7 @@ inline InheritableAttr *getDLLAttr(Decl *D) {
 }
 
 /// Retrieve the depth and index of a template parameter.
-inline std::pair getDepthAndIndex(NamedDecl *ND) {
+inline std::pair getDepthAndIndex(const NamedDecl *ND) {
   if (const auto *TTP = dyn_cast(ND))
 return std::make_pair(TTP->getDepth(), TTP->getIndex());
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [RISCV] Mark the RVA23S64 and RVA23U64 profiles as non-experimental (PR #113826)

2024-10-27 Thread Pengcheng Wang via cfe-commits

https://github.com/wangpc-pp approved this pull request.

LGTM.

https://github.com/llvm/llvm-project/pull/113826
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [RISCV] Add the Sha extension (PR #113820)

2024-10-27 Thread Pengcheng Wang via cfe-commits

https://github.com/wangpc-pp approved this pull request.

LGTM.

https://github.com/llvm/llvm-project/pull/113820
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][NFC] Accept const NamedDecl pointer for getDepthAndIndex (PR #113857)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (antangelo)


Changes



---
Full diff: https://github.com/llvm/llvm-project/pull/113857.diff


1 Files Affected:

- (modified) clang/include/clang/Sema/SemaInternal.h (+1-1) 


``diff
diff --git a/clang/include/clang/Sema/SemaInternal.h 
b/clang/include/clang/Sema/SemaInternal.h
index d994d1819b4423..41d05b2bfb078e 100644
--- a/clang/include/clang/Sema/SemaInternal.h
+++ b/clang/include/clang/Sema/SemaInternal.h
@@ -58,7 +58,7 @@ inline InheritableAttr *getDLLAttr(Decl *D) {
 }
 
 /// Retrieve the depth and index of a template parameter.
-inline std::pair getDepthAndIndex(NamedDecl *ND) {
+inline std::pair getDepthAndIndex(const NamedDecl *ND) {
   if (const auto *TTP = dyn_cast(ND))
 return std::make_pair(TTP->getDepth(), TTP->getIndex());
 

``




https://github.com/llvm/llvm-project/pull/113857
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add -ConfigFile option (PR #113864)

2024-10-27 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/113864

Close #107808.

>From 4cbc31029c5d773dd68c80030e896b3fed88ab77 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 27 Oct 2024 22:22:11 -0700
Subject: [PATCH] [clang-format] Add -ConfigFile option

Close #107808.
---
 clang/include/clang/Format/Format.h |  5 +
 clang/lib/Format/Format.cpp | 14 ++
 2 files changed, 19 insertions(+)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index c9b72e65cb236d..1380223493187a 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2481,6 +2481,10 @@ struct FormatStyle {
   /// \version 5
   bool CompactNamespaces;
 
+  ///
+  /// \version 20
+  std::string ConfigFile;
+
   /// This option is **deprecated**. See ``CurrentLine`` of
   /// ``PackConstructorInitializers``.
   /// \version 3.7
@@ -5195,6 +5199,7 @@ struct FormatStyle {
BreakTemplateDeclarations == R.BreakTemplateDeclarations &&
ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas 
&&
CompactNamespaces == R.CompactNamespaces &&
+   ConfigFile == R.ConfigFile &&
ConstructorInitializerIndentWidth ==
R.ConstructorInitializerIndentWidth &&
ContinuationIndentWidth == R.ContinuationIndentWidth &&
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 0cf4cdbeab31f3..172578092066e1 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1163,6 +1163,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TemplateNames", Style.TemplateNames);
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
+IO.mapOptional("ConfigFile", Style.ConfigFile);
 IO.mapOptional("UseTab", Style.UseTab);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
@@ -2046,6 +2047,11 @@ ParseError validateQualifierOrder(FormatStyle *Style) {
   return ParseError::Success;
 }
 
+llvm::ErrorOr>
+loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
+   FormatStyle *Style, bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler);
+
 std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
FormatStyle *Style, bool 
AllowUnknownOptions,
llvm::SourceMgr::DiagHandlerTy DiagHandler,
@@ -2102,6 +2108,14 @@ std::error_code parseConfiguration(llvm::MemoryBufferRef 
Config,
 StyleSet.Add(std::move(DefaultStyle));
   }
   *Style = *StyleSet.Get(Language);
+  if (const StringRef ConfigFile{Style->ConfigFile}; !ConfigFile.empty()) {
+auto *FS = llvm::vfs::getRealFileSystem().get();
+assert(FS);
+const auto Text = loadAndParseConfigFile(ConfigFile, FS, Style,
+ AllowUnknownOptions, DiagHandler);
+if (Text.getError())
+  return make_error_code(ParseError::Error);
+  }
   if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
   Style->BinPackArguments) {
 // See comment on FormatStyle::TSC_Wrapped.

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add -ConfigFile option (PR #113864)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Close #107808.

---
Full diff: https://github.com/llvm/llvm-project/pull/113864.diff


2 Files Affected:

- (modified) clang/include/clang/Format/Format.h (+5) 
- (modified) clang/lib/Format/Format.cpp (+14) 


``diff
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index c9b72e65cb236d..1380223493187a 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2481,6 +2481,10 @@ struct FormatStyle {
   /// \version 5
   bool CompactNamespaces;
 
+  ///
+  /// \version 20
+  std::string ConfigFile;
+
   /// This option is **deprecated**. See ``CurrentLine`` of
   /// ``PackConstructorInitializers``.
   /// \version 3.7
@@ -5195,6 +5199,7 @@ struct FormatStyle {
BreakTemplateDeclarations == R.BreakTemplateDeclarations &&
ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas 
&&
CompactNamespaces == R.CompactNamespaces &&
+   ConfigFile == R.ConfigFile &&
ConstructorInitializerIndentWidth ==
R.ConstructorInitializerIndentWidth &&
ContinuationIndentWidth == R.ContinuationIndentWidth &&
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 0cf4cdbeab31f3..172578092066e1 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1163,6 +1163,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TemplateNames", Style.TemplateNames);
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
+IO.mapOptional("ConfigFile", Style.ConfigFile);
 IO.mapOptional("UseTab", Style.UseTab);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
@@ -2046,6 +2047,11 @@ ParseError validateQualifierOrder(FormatStyle *Style) {
   return ParseError::Success;
 }
 
+llvm::ErrorOr>
+loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
+   FormatStyle *Style, bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler);
+
 std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
FormatStyle *Style, bool 
AllowUnknownOptions,
llvm::SourceMgr::DiagHandlerTy DiagHandler,
@@ -2102,6 +2108,14 @@ std::error_code parseConfiguration(llvm::MemoryBufferRef 
Config,
 StyleSet.Add(std::move(DefaultStyle));
   }
   *Style = *StyleSet.Get(Language);
+  if (const StringRef ConfigFile{Style->ConfigFile}; !ConfigFile.empty()) {
+auto *FS = llvm::vfs::getRealFileSystem().get();
+assert(FS);
+const auto Text = loadAndParseConfigFile(ConfigFile, FS, Style,
+ AllowUnknownOptions, DiagHandler);
+if (Text.getError())
+  return make_error_code(ParseError::Error);
+  }
   if (Style->InsertTrailingCommas != FormatStyle::TCS_None &&
   Style->BinPackArguments) {
 // See comment on FormatStyle::TSC_Wrapped.

``




https://github.com/llvm/llvm-project/pull/113864
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add -ConfigFile option (PR #113864)

2024-10-27 Thread Owen Pan via cfe-commits

https://github.com/owenca converted_to_draft 
https://github.com/llvm/llvm-project/pull/113864
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] fix false positive for implicit conversion of comparison result in C23 (PR #113639)

2024-10-27 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`sanitizer-x86_64-linux-bootstrap-asan` running on `sanitizer-buildbot1` while 
building `clang-tools-extra` at step 2 "annotate".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/52/builds/3266


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: 86543 of 86544 tests, 88 workers --
Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90.
FAIL: lld :: ELF/allow-shlib-undefined.s (84218 of 86543)
 TEST 'lld :: ELF/allow-shlib-undefined.s' FAILED 

Exit Code: 1

Command Output (stderr):
--
RUN: at line 3: rm -rf 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp
 && split-file 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/allow-shlib-undefined.s
 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp
 && cd 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp
+ rm -rf 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp
+ split-file 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/allow-shlib-undefined.s
 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp
+ cd 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/allow-shlib-undefined.s.tmp
RUN: at line 4: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64 main.s -o main.o
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64 main.s -o main.o
RUN: at line 5: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64 def.s -o def.o
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64 def.s -o def.o
RUN: at line 6: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64 def-hidden.s -o def-hidden.o
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64 def-hidden.s -o def-hidden.o
RUN: at line 7: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64 ref.s -o ref.o
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64 ref.s -o ref.o
RUN: at line 8: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64 a.s -o a.o && 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld.lld 
-shared a.o -o a.so
+ 
/

[clang] [clang][NFC] Accept const NamedDecl pointer for getDepthAndIndex (PR #113857)

2024-10-27 Thread via cfe-commits

https://github.com/antangelo closed 
https://github.com/llvm/llvm-project/pull/113857
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][RISCV] Support -fcf-protection=return for RISC-V (PR #112477)

2024-10-27 Thread Jesse Huang via cfe-commits

https://github.com/jaidTw updated 
https://github.com/llvm/llvm-project/pull/112477

>From fe4a28fb691b69d9af384f1dc2f0667761adef44 Mon Sep 17 00:00:00 2001
From: Jesse Huang 
Date: Sun, 13 Oct 2024 15:11:06 +0800
Subject: [PATCH 1/7] [Clang][RISCV] Support -fcf-protection=return for RISC-V

---
 clang/lib/Basic/Targets/RISCV.h   | 7 +++
 clang/lib/CodeGen/CodeGenFunction.cpp | 4 
 2 files changed, 11 insertions(+)

diff --git a/clang/lib/Basic/Targets/RISCV.h b/clang/lib/Basic/Targets/RISCV.h
index bf40edb8683b3e..3f2cee72fc3731 100644
--- a/clang/lib/Basic/Targets/RISCV.h
+++ b/clang/lib/Basic/Targets/RISCV.h
@@ -141,6 +141,13 @@ class RISCVTargetInfo : public TargetInfo {
 return true;
   }
 
+  bool
+  checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const override {
+if (ISAInfo->hasExtension("zimop"))
+  return true;
+return TargetInfo::checkCFProtectionReturnSupported(Diags);
+  }
+
   CFBranchLabelSchemeKind getDefaultCFBranchLabelScheme() const override {
 return CFBranchLabelSchemeKind::FuncSig;
   }
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 2306043c90f406..d8f0f7c14f6b40 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -899,6 +899,10 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
   if (CodeGenOpts.PointerAuth.IndirectGotos)
 Fn->addFnAttr("ptrauth-indirect-gotos");
 
+  // Add return control flow integrity attributes.
+  if (CodeGenOpts.CFProtectionReturn)
+Fn->addFnAttr("hw-shadow-stack");
+
   // Apply xray attributes to the function (as a string, for now)
   bool AlwaysXRayAttr = false;
   if (const auto *XRayAttr = D ? D->getAttr() : nullptr) {

>From 7dc168af5758d130042c71ba5d6249c042bc356c Mon Sep 17 00:00:00 2001
From: Jesse Huang 
Date: Wed, 23 Oct 2024 14:42:35 +0800
Subject: [PATCH 2/7] [Clang][RISCV] Add RISCV check for hw-shadow-stack

---
 clang/lib/CodeGen/CodeGenFunction.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index d8f0f7c14f6b40..cca52f3769845e 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -899,8 +899,9 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
   if (CodeGenOpts.PointerAuth.IndirectGotos)
 Fn->addFnAttr("ptrauth-indirect-gotos");
 
-  // Add return control flow integrity attributes.
-  if (CodeGenOpts.CFProtectionReturn)
+  // Add return control flow integrity attributes for RISCV.
+  if (CodeGenOpts.CFProtectionReturn &&
+  getContext().getTargetInfo().getTriple().isRISCV())
 Fn->addFnAttr("hw-shadow-stack");
 
   // Apply xray attributes to the function (as a string, for now)

>From 42132c246058f6c1aaa646266847a3b8c854 Mon Sep 17 00:00:00 2001
From: Jesse Huang 
Date: Thu, 24 Oct 2024 15:39:07 +0800
Subject: [PATCH 3/7] [Clang][RISCV] Add function attribute in RISC-V specific
 code

---
 clang/lib/CodeGen/CodeGenFunction.cpp | 5 -
 clang/lib/CodeGen/Targets/RISCV.cpp   | 7 +--
 2 files changed, 5 insertions(+), 7 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index cca52f3769845e..2306043c90f406 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -899,11 +899,6 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
   if (CodeGenOpts.PointerAuth.IndirectGotos)
 Fn->addFnAttr("ptrauth-indirect-gotos");
 
-  // Add return control flow integrity attributes for RISCV.
-  if (CodeGenOpts.CFProtectionReturn &&
-  getContext().getTargetInfo().getTriple().isRISCV())
-Fn->addFnAttr("hw-shadow-stack");
-
   // Apply xray attributes to the function (as a string, for now)
   bool AlwaysXRayAttr = false;
   if (const auto *XRayAttr = D ? D->getAttr() : nullptr) {
diff --git a/clang/lib/CodeGen/Targets/RISCV.cpp 
b/clang/lib/CodeGen/Targets/RISCV.cpp
index fd72fe673b9b14..b04e436c665f52 100644
--- a/clang/lib/CodeGen/Targets/RISCV.cpp
+++ b/clang/lib/CodeGen/Targets/RISCV.cpp
@@ -594,6 +594,11 @@ class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
 const auto *FD = dyn_cast_or_null(D);
 if (!FD) return;
 
+auto *Fn = cast(GV);
+
+if (CGM.getCodeGenOpts().CFProtectionReturn)
+  Fn->addFnAttr("hw-shadow-stack");
+
 const auto *Attr = FD->getAttr();
 if (!Attr)
   return;
@@ -604,8 +609,6 @@ class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
 case RISCVInterruptAttr::machine: Kind = "machine"; break;
 }
 
-auto *Fn = cast(GV);
-
 Fn->addFnAttr("interrupt", Kind);
   }
 };

>From 2b6bdc5e95043a0f481314c0c2e5441804addf06 Mon Sep 17 00:00:00 2001
From: Jesse Huang 
Date: Fri, 25 Oct 2024 14:13:45 +0800
Subject: [PATCH 4/7] [Clang] Add test for hw-shadodw-stack

---
 clang/test/CodeGen/RISCV/attr-hw-shadow-stack

[clang-tools-extra] Insert `// NOLINTNEXTLINE(...)` for clang-tidy diagnostics (PR #111640)

2024-10-27 Thread Richard Li via cfe-commits

https://github.com/chomosuke updated 
https://github.com/llvm/llvm-project/pull/111640

>From e1c2a46487c42c17dc0bbfab56cde194c15e14b3 Mon Sep 17 00:00:00 2001
From: chomosuke 
Date: Fri, 16 Aug 2024 13:31:21 +
Subject: [PATCH 01/17] Fixing one error

---
 clang-tools-extra/clangd/ClangdServer.cpp | 23 ++-
 1 file changed, 22 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 9b38be04e7ddd7..e08ce12223f6b0 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -44,6 +44,7 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/Format.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
@@ -672,6 +673,21 @@ tryConvertToRename(const Diag *Diag, const Fix &Fix) {
   return std::nullopt;
 }
 
+// Add NOLINT insert as code actions
+std::optional tryAddClangTidySuppression(const Diag *Diag) {
+  if (Diag->Source == Diag::ClangTidy) {
+Fix F;
+F.Message = llvm::formatv("ignore [{0}] for this line", Diag->Name);
+TextEdit &E = F.Edits.emplace_back();
+E.newText = llvm::formatv("// NOLINTNEXTLINE({0})\n", Diag->Name);
+Position InsertPos = Diag->Range.start;
+InsertPos.character = 0;
+E.range = {InsertPos, InsertPos};
+return F;
+  }
+  return std::nullopt;
+}
+
 } // namespace
 
 void ClangdServer::codeAction(const CodeActionInputs &Params,
@@ -701,7 +717,7 @@ void ClangdServer::codeAction(const CodeActionInputs 
&Params,
 return nullptr;
   };
   for (const auto &DiagRef : Params.Diagnostics) {
-if (const auto *Diag = FindMatchedDiag(DiagRef))
+if (const auto *Diag = FindMatchedDiag(DiagRef)) {
   for (const auto &Fix : Diag->Fixes) {
 if (auto Rename = tryConvertToRename(Diag, Fix)) {
   Result.Renames.emplace_back(std::move(*Rename));
@@ -709,6 +725,11 @@ void ClangdServer::codeAction(const CodeActionInputs 
&Params,
   Result.QuickFixes.push_back({DiagRef, Fix});
 }
   }
+
+  if (auto Fix = tryAddClangTidySuppression(Diag)) {
+Result.QuickFixes.push_back({DiagRef, std::move(*Fix)});
+  }
+}
   }
 }
 

>From 433040437830935d7a0822984cd5de53213b8af3 Mon Sep 17 00:00:00 2001
From: chomosuke 
Date: Sun, 18 Aug 2024 17:15:21 +
Subject: [PATCH 02/17] Revert "Fixing one error"

This reverts commit 17989044ad480628a2f7814674dbe7cd985abd17.
---
 clang-tools-extra/clangd/ClangdServer.cpp | 23 +--
 1 file changed, 1 insertion(+), 22 deletions(-)

diff --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index e08ce12223f6b0..9b38be04e7ddd7 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -44,7 +44,6 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
-#include "llvm/Support/Format.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
@@ -673,21 +672,6 @@ tryConvertToRename(const Diag *Diag, const Fix &Fix) {
   return std::nullopt;
 }
 
-// Add NOLINT insert as code actions
-std::optional tryAddClangTidySuppression(const Diag *Diag) {
-  if (Diag->Source == Diag::ClangTidy) {
-Fix F;
-F.Message = llvm::formatv("ignore [{0}] for this line", Diag->Name);
-TextEdit &E = F.Edits.emplace_back();
-E.newText = llvm::formatv("// NOLINTNEXTLINE({0})\n", Diag->Name);
-Position InsertPos = Diag->Range.start;
-InsertPos.character = 0;
-E.range = {InsertPos, InsertPos};
-return F;
-  }
-  return std::nullopt;
-}
-
 } // namespace
 
 void ClangdServer::codeAction(const CodeActionInputs &Params,
@@ -717,7 +701,7 @@ void ClangdServer::codeAction(const CodeActionInputs 
&Params,
 return nullptr;
   };
   for (const auto &DiagRef : Params.Diagnostics) {
-if (const auto *Diag = FindMatchedDiag(DiagRef)) {
+if (const auto *Diag = FindMatchedDiag(DiagRef))
   for (const auto &Fix : Diag->Fixes) {
 if (auto Rename = tryConvertToRename(Diag, Fix)) {
   Result.Renames.emplace_back(std::move(*Rename));
@@ -725,11 +709,6 @@ void ClangdServer::codeAction(const CodeActionInputs 
&Params,
   Result.QuickFixes.push_back({DiagRef, Fix});
 }
   }
-
-  if (auto Fix = tryAddClangTidySuppression(Diag)) {
-Result.QuickFixes.push_back({DiagRef, std::move(*Fix)});
-  }
-}
   }
 }
 

>From 7b64a8fafd93af944f72b987d7abf4e167f03205 Mon Sep 17 00:00:00 2001
From: chomosuke 
Date: Mon, 19 Aug 2024 15:17:05 +
Subject: [PATCH 03/17] inserted NOLINT with indent

Retrieved CurLine and PrevLine
---
 clang-tools-extra/clangd/Diagnostics.cpp |  4 +-
 clang-tools-extra/cl

[clang] [llvm] [RISCV] Use Sha extension in RVA23S64 profile (PR #113823)

2024-10-27 Thread Pengcheng Wang via cfe-commits

https://github.com/wangpc-pp approved this pull request.

LGTM.

https://github.com/llvm/llvm-project/pull/113823
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] a1d31ca - [clang-tidy] fix false positive for implicit conversion of comparison result in C23 (#113639)

2024-10-27 Thread via cfe-commits

Author: Congcong Cai
Date: 2024-10-28T11:36:37+08:00
New Revision: a1d31caa8c53082d12f580122dcf2b2ff8285e78

URL: 
https://github.com/llvm/llvm-project/commit/a1d31caa8c53082d12f580122dcf2b2ff8285e78
DIFF: 
https://github.com/llvm/llvm-project/commit/a1d31caa8c53082d12f580122dcf2b2ff8285e78.diff

LOG: [clang-tidy] fix false positive for implicit conversion of comparison 
result in C23 (#113639)

Fixed #111013
bool will be builtin type in C23 but comparison result in C is still
int.
It is no need to change this kind of implicit cast to explicit cast.

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 968a4a55a6d798..f9fd1d903e231e 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -10,6 +10,7 @@
 #include "../utils/FixItHintUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/FixIt.h"
 #include 
@@ -26,6 +27,8 @@ AST_MATCHER(Stmt, isMacroExpansion) {
   return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc);
 }
 
+AST_MATCHER(Stmt, isC23) { return Finder->getASTContext().getLangOpts().C23; }
+
 bool isNULLMacroExpansion(const Stmt *Statement, ASTContext &Context) {
   SourceManager &SM = Context.getSourceManager();
   const LangOptions &LO = Context.getLangOpts();
@@ -298,6 +301,11 @@ void 
ImplicitBoolConversionCheck::registerMatchers(MatchFinder *Finder) {
  hasCastKind(CK_FloatingToBoolean),
  hasCastKind(CK_PointerToBoolean),
  hasCastKind(CK_MemberPointerToBoolean)),
+   // Exclude cases of C23 comparison result.
+   unless(allOf(isC23(),
+hasSourceExpression(ignoringParens(
+binaryOperator(hasAnyOperatorName(
+">", ">=", "==", "!=", "<", "<=")),
// Exclude case of using if or while statements with 
variable
// declaration, e.g.:
//   if (int var = functionCall()) {}

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 876689c40fcdb2..4cc4c2146d7e33 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -249,7 +249,8 @@ Changes in existing checks
 - Improved :doc:`readability-implicit-bool-conversion
   ` check
   by adding the option `UseUpperCaseLiteralSuffix` to select the
-  case of the literal suffix in fixes.
+  case of the literal suffix in fixes and fixing false positive for implicit
+  conversion of comparison result in C23.
 
 - Improved :doc:`readability-redundant-smartptr-get
   ` check to

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
index f3dc32c10d640a..0b231d10adf8fc 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
@@ -304,6 +304,15 @@ void 
implicitConversionToBoolFromUnaryMinusAndZeroLiterals() {
   // CHECK-FIXES: functionTakingBool((-0.0) != 0.0);
 }
 
+void ignoreImplicitCastToBoolForComparisonResult() {
+  bool boolFromComparison0 = 1 != 0;
+  bool boolFromComparison1 = 1 == 0;
+  bool boolFromComparison2 = 1 > 0;
+  bool boolFromComparison3 = 1 >= 0;
+  bool boolFromComparison4 = 1 < 0;
+  bool boolFromComparison5 = 1 <= 0;
+}
+
 void ignoreExplicitCastsToBool() {
   int integer = 10;
   bool boolComingFromInt = (bool)integer;



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -58,7 +58,7 @@ inline InheritableAttr *getDLLAttr(Decl *D) {
 }
 
 /// Retrieve the depth and index of a template parameter.
-inline std::pair getDepthAndIndex(NamedDecl *ND) {
+inline std::pair getDepthAndIndex(const NamedDecl *ND) {

antangelo wrote:

Done, see https://github.com/llvm/llvm-project/pull/113857

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-27 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa created 
https://github.com/llvm/llvm-project/pull/113859

This checker has a notion of a guardian variable which is a variable and keeps 
the object pointed to by a raw pointer / reference in an inner scope alive long 
enough to "guard" it from use-after-free. But such a guardian variable fails to 
flawed to keep the object alive if it ever gets mutated within the scope of a 
raw pointer / reference.

This PR fixes this bug by introducing a new AST visitor class, GuardianVisitor, 
which traverses the compound statements of a guarded variable (raw pointer / 
reference) and looks for any operator=, move constructor, or calls to "swap", 
"leakRef", or "releaseNonNull" functions.

>From 8fce7f69eb5e28f6ec648ee0dc4cc23c793f64c0 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 27 Oct 2024 21:43:24 -0700
Subject: [PATCH] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a
 raw pointer/reference when the guardian variable gets mutated.

This checker has a notion of a guardian variable which is a variable and keeps 
the object pointed to by a raw pointer /
reference in an inner scope alive long enough to "guard" it from 
use-after-free. But such a guardian variable fails to
flawed to keep the object alive if it ever gets mutated within the scope of a 
raw pointer / reference.

This PR fixes this bug by introducing a new AST visitor class, GuardianVisitor, 
which traverses the compound statements
of a guarded variable (raw pointer / reference) and looks for any operator=, 
move constructor, or calls to "swap",
"leakRef", or "releaseNonNull" functions.
---
 .../WebKit/UncountedLocalVarsChecker.cpp  | 72 +--
 .../Analysis/Checkers/WebKit/mock-types.h | 34 -
 .../Checkers/WebKit/uncounted-local-vars.cpp  | 59 +++
 3 files changed, 159 insertions(+), 6 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
index 5cdf047738abcb..5f5fb6e2bf1f87 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
@@ -48,6 +48,65 @@ bool isRefcountedStringsHack(const VarDecl *V) {
   return false;
 }
 
+struct GuardianVisitor : public RecursiveASTVisitor {
+  using Base = RecursiveASTVisitor;
+
+  const VarDecl *Guardian { nullptr };
+
+public:
+  explicit GuardianVisitor(const VarDecl *Guardian)
+  : Guardian(Guardian) {
+assert(Guardian);
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) {
+if (BO->isAssignmentOp()) {
+  if (auto *VarRef = dyn_cast(BO->getLHS())) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXConstructExpr(const CXXConstructExpr* CE) {
+if (auto *Ctor = CE->getConstructor()) {
+  if (Ctor->isMoveConstructor() && CE->getNumArgs() == 1) {
+auto *Arg = CE->getArg(0)->IgnoreParenCasts();
+if (auto *VarRef = dyn_cast(Arg)) {
+  if (VarRef->getDecl() == Guardian)
+return false;
+}
+  }
+}
+return true;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr* MCE) {
+auto MethodName = safeGetName(MCE->getMethodDecl());
+if (MethodName == "swap" || MethodName == "leakRef" ||
+MethodName == "releaseNonNull") {
+  auto *ThisArg = MCE->getImplicitObjectArgument()->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr* OCE) {
+if (OCE->isAssignmentOp() && OCE->getNumArgs() == 2) {
+  auto *ThisArg = OCE->getArg(0)->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+};
+
 bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl *Guarded,
const VarDecl *MaybeGuardian) {
   assert(Guarded);
@@ -81,7 +140,7 @@ bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl 
*Guarded,
 
   // We need to skip the first CompoundStmt to avoid situation when guardian is
   // defined in the same scope as guarded variable.
-  bool HaveSkippedFirstCompoundStmt = false;
+  const CompoundStmt *FirstCompondStmt = nullptr;
   for (DynTypedNodeList guardedVarAncestors = ctx.getParents(*Guarded);
!guardedVarAncestors.empty();
guardedVarAncestors = ctx.getParents(
@@ -90,12 +149,15 @@ bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl 
*Guarded,
   ) {
 for (auto &guardedVarAncestor : guardedVarAncestors) {
   if (auto *CStmtAncestor = guardedVarAncestor.get()) {
-if (!HaveSkippedFirstCompoundStmt) {
-  HaveSkippedFirstCompoundStmt = true;
+if (!FirstCo

[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1

Author: Ryosuke Niwa (rniwa)


Changes

This checker has a notion of a guardian variable which is a variable and keeps 
the object pointed to by a raw pointer / reference in an inner scope alive long 
enough to "guard" it from use-after-free. But such a guardian variable fails to 
flawed to keep the object alive if it ever gets mutated within the scope of a 
raw pointer / reference.

This PR fixes this bug by introducing a new AST visitor class, GuardianVisitor, 
which traverses the compound statements of a guarded variable (raw pointer / 
reference) and looks for any operator=, move constructor, or calls to "swap", 
"leakRef", or "releaseNonNull" functions.

---
Full diff: https://github.com/llvm/llvm-project/pull/113859.diff


3 Files Affected:

- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp (+67-5) 
- (modified) clang/test/Analysis/Checkers/WebKit/mock-types.h (+33-1) 
- (modified) clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp (+59) 


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
index 5cdf047738abcb..5f5fb6e2bf1f87 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
@@ -48,6 +48,65 @@ bool isRefcountedStringsHack(const VarDecl *V) {
   return false;
 }
 
+struct GuardianVisitor : public RecursiveASTVisitor {
+  using Base = RecursiveASTVisitor;
+
+  const VarDecl *Guardian { nullptr };
+
+public:
+  explicit GuardianVisitor(const VarDecl *Guardian)
+  : Guardian(Guardian) {
+assert(Guardian);
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) {
+if (BO->isAssignmentOp()) {
+  if (auto *VarRef = dyn_cast(BO->getLHS())) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXConstructExpr(const CXXConstructExpr* CE) {
+if (auto *Ctor = CE->getConstructor()) {
+  if (Ctor->isMoveConstructor() && CE->getNumArgs() == 1) {
+auto *Arg = CE->getArg(0)->IgnoreParenCasts();
+if (auto *VarRef = dyn_cast(Arg)) {
+  if (VarRef->getDecl() == Guardian)
+return false;
+}
+  }
+}
+return true;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr* MCE) {
+auto MethodName = safeGetName(MCE->getMethodDecl());
+if (MethodName == "swap" || MethodName == "leakRef" ||
+MethodName == "releaseNonNull") {
+  auto *ThisArg = MCE->getImplicitObjectArgument()->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr* OCE) {
+if (OCE->isAssignmentOp() && OCE->getNumArgs() == 2) {
+  auto *ThisArg = OCE->getArg(0)->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+};
+
 bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl *Guarded,
const VarDecl *MaybeGuardian) {
   assert(Guarded);
@@ -81,7 +140,7 @@ bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl 
*Guarded,
 
   // We need to skip the first CompoundStmt to avoid situation when guardian is
   // defined in the same scope as guarded variable.
-  bool HaveSkippedFirstCompoundStmt = false;
+  const CompoundStmt *FirstCompondStmt = nullptr;
   for (DynTypedNodeList guardedVarAncestors = ctx.getParents(*Guarded);
!guardedVarAncestors.empty();
guardedVarAncestors = ctx.getParents(
@@ -90,12 +149,15 @@ bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl 
*Guarded,
   ) {
 for (auto &guardedVarAncestor : guardedVarAncestors) {
   if (auto *CStmtAncestor = guardedVarAncestor.get()) {
-if (!HaveSkippedFirstCompoundStmt) {
-  HaveSkippedFirstCompoundStmt = true;
+if (!FirstCompondStmt) {
+  FirstCompondStmt = CStmtAncestor;
   continue;
 }
-if (CStmtAncestor == guardiansClosestCompStmtAncestor)
-  return true;
+if (CStmtAncestor == guardiansClosestCompStmtAncestor) {
+  GuardianVisitor guardianVisitor(MaybeGuardian);
+  auto *GuardedScope = const_cast(FirstCompondStmt);
+  return guardianVisitor.TraverseCompoundStmt(GuardedScope);
+}
   }
 }
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/mock-types.h 
b/clang/test/Analysis/Checkers/WebKit/mock-types.h
index 8d8a90f0afae0e..82c79c97a83de6 100644
--- a/clang/test/Analysis/Checkers/WebKit/mock-types.h
+++ b/clang/test/Analysis/Checkers/WebKit/mock-types.h
@@ -49,7 +49,23 @@ template , 
typename RefDer

[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ryosuke Niwa (rniwa)


Changes

This checker has a notion of a guardian variable which is a variable and keeps 
the object pointed to by a raw pointer / reference in an inner scope alive long 
enough to "guard" it from use-after-free. But such a guardian variable fails to 
flawed to keep the object alive if it ever gets mutated within the scope of a 
raw pointer / reference.

This PR fixes this bug by introducing a new AST visitor class, GuardianVisitor, 
which traverses the compound statements of a guarded variable (raw pointer / 
reference) and looks for any operator=, move constructor, or calls to "swap", 
"leakRef", or "releaseNonNull" functions.

---
Full diff: https://github.com/llvm/llvm-project/pull/113859.diff


3 Files Affected:

- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp (+67-5) 
- (modified) clang/test/Analysis/Checkers/WebKit/mock-types.h (+33-1) 
- (modified) clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp (+59) 


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
index 5cdf047738abcb..5f5fb6e2bf1f87 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
@@ -48,6 +48,65 @@ bool isRefcountedStringsHack(const VarDecl *V) {
   return false;
 }
 
+struct GuardianVisitor : public RecursiveASTVisitor {
+  using Base = RecursiveASTVisitor;
+
+  const VarDecl *Guardian { nullptr };
+
+public:
+  explicit GuardianVisitor(const VarDecl *Guardian)
+  : Guardian(Guardian) {
+assert(Guardian);
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) {
+if (BO->isAssignmentOp()) {
+  if (auto *VarRef = dyn_cast(BO->getLHS())) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXConstructExpr(const CXXConstructExpr* CE) {
+if (auto *Ctor = CE->getConstructor()) {
+  if (Ctor->isMoveConstructor() && CE->getNumArgs() == 1) {
+auto *Arg = CE->getArg(0)->IgnoreParenCasts();
+if (auto *VarRef = dyn_cast(Arg)) {
+  if (VarRef->getDecl() == Guardian)
+return false;
+}
+  }
+}
+return true;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr* MCE) {
+auto MethodName = safeGetName(MCE->getMethodDecl());
+if (MethodName == "swap" || MethodName == "leakRef" ||
+MethodName == "releaseNonNull") {
+  auto *ThisArg = MCE->getImplicitObjectArgument()->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+
+  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr* OCE) {
+if (OCE->isAssignmentOp() && OCE->getNumArgs() == 2) {
+  auto *ThisArg = OCE->getArg(0)->IgnoreParenCasts();
+  if (auto *VarRef = dyn_cast(ThisArg)) {
+if (VarRef->getDecl() == Guardian)
+  return false;
+  }
+}
+return true;
+  }
+};
+
 bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl *Guarded,
const VarDecl *MaybeGuardian) {
   assert(Guarded);
@@ -81,7 +140,7 @@ bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl 
*Guarded,
 
   // We need to skip the first CompoundStmt to avoid situation when guardian is
   // defined in the same scope as guarded variable.
-  bool HaveSkippedFirstCompoundStmt = false;
+  const CompoundStmt *FirstCompondStmt = nullptr;
   for (DynTypedNodeList guardedVarAncestors = ctx.getParents(*Guarded);
!guardedVarAncestors.empty();
guardedVarAncestors = ctx.getParents(
@@ -90,12 +149,15 @@ bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl 
*Guarded,
   ) {
 for (auto &guardedVarAncestor : guardedVarAncestors) {
   if (auto *CStmtAncestor = guardedVarAncestor.get()) {
-if (!HaveSkippedFirstCompoundStmt) {
-  HaveSkippedFirstCompoundStmt = true;
+if (!FirstCompondStmt) {
+  FirstCompondStmt = CStmtAncestor;
   continue;
 }
-if (CStmtAncestor == guardiansClosestCompStmtAncestor)
-  return true;
+if (CStmtAncestor == guardiansClosestCompStmtAncestor) {
+  GuardianVisitor guardianVisitor(MaybeGuardian);
+  auto *GuardedScope = const_cast(FirstCompondStmt);
+  return guardianVisitor.TraverseCompoundStmt(GuardedScope);
+}
   }
 }
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/mock-types.h 
b/clang/test/Analysis/Checkers/WebKit/mock-types.h
index 8d8a90f0afae0e..82c79c97a83de6 100644
--- a/clang/test/Analysis/Checkers/WebKit/mock-types.h
+++ b/clang/test/Analysis/Checkers/WebKit/mock-types.h
@@ -49,7 +49,23 @@ template , 
typename RefDerefTra
   Ref() : t

[clang-tools-extra] [clang-tidy] fix false positive for implicit conversion of comparison result in C23 (PR #113639)

2024-10-27 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/113639

>From 53ff1325281e37b164abc8705f2d75d7caeec3a4 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Fri, 25 Oct 2024 11:07:14 +0800
Subject: [PATCH 1/2] [clang-tidy] fix false positive for implicit conversion
 of comparison result in C23

Fixed #111013
bool will be builtin type in C23 but comparison result in C is still int.
It is no need to change this kind of implicit cast to explicit cast.
---
 .../readability/ImplicitBoolConversionCheck.cpp  | 7 +++
 clang-tools-extra/docs/ReleaseNotes.rst  | 3 ++-
 .../checkers/readability/implicit-bool-conversion.c  | 9 +
 3 files changed, 18 insertions(+), 1 deletion(-)

diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 968a4a55a6d798..06415c1346a4f0 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -26,6 +26,8 @@ AST_MATCHER(Stmt, isMacroExpansion) {
   return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc);
 }
 
+AST_MATCHER(Stmt, isC23) { return Finder->getASTContext().getLangOpts().C23; }
+
 bool isNULLMacroExpansion(const Stmt *Statement, ASTContext &Context) {
   SourceManager &SM = Context.getSourceManager();
   const LangOptions &LO = Context.getLangOpts();
@@ -298,6 +300,11 @@ void 
ImplicitBoolConversionCheck::registerMatchers(MatchFinder *Finder) {
  hasCastKind(CK_FloatingToBoolean),
  hasCastKind(CK_PointerToBoolean),
  hasCastKind(CK_MemberPointerToBoolean)),
+   // Exclude cases of C23 comparison result.
+   unless(allOf(
+   isC23(),
+   hasSourceExpression(binaryOperator(hasAnyOperatorName(
+   ">", ">=", "==", "!=", "<", "<="),
// Exclude case of using if or while statements with 
variable
// declaration, e.g.:
//   if (int var = functionCall()) {}
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a9b1ab367f538a..e42082806fd308 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:`readability-implicit-bool-conversion
   ` check
   by adding the option `UseUpperCaseLiteralSuffix` to select the
-  case of the literal suffix in fixes.
+  case of the literal suffix in fixes and fixing false positive for implicit
+  conversion of comparison result in C23.
 
 - Improved :doc:`readability-redundant-smartptr-get
   ` check to
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
index f3dc32c10d640a..0b231d10adf8fc 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.c
@@ -304,6 +304,15 @@ void 
implicitConversionToBoolFromUnaryMinusAndZeroLiterals() {
   // CHECK-FIXES: functionTakingBool((-0.0) != 0.0);
 }
 
+void ignoreImplicitCastToBoolForComparisonResult() {
+  bool boolFromComparison0 = 1 != 0;
+  bool boolFromComparison1 = 1 == 0;
+  bool boolFromComparison2 = 1 > 0;
+  bool boolFromComparison3 = 1 >= 0;
+  bool boolFromComparison4 = 1 < 0;
+  bool boolFromComparison5 = 1 <= 0;
+}
+
 void ignoreExplicitCastsToBool() {
   int integer = 10;
   bool boolComingFromInt = (bool)integer;

>From 39afbaff319f2a9e7b5259ac87cf1a3c80ffc0a6 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Mon, 28 Oct 2024 11:36:22 +0800
Subject: [PATCH 2/2] fix

---
 .../readability/ImplicitBoolConversionCheck.cpp  | 9 +
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 06415c1346a4f0..f9fd1d903e231e 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -10,6 +10,7 @@
 #include "../utils/FixItHintUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/FixIt.h"
 #include 
@@ -301,10 +302,10 @@ void 
ImplicitBoolConversionCheck::registerMatchers(MatchFinder *Finder) {
  hasCastKind(CK_PointerToBoolean),
  hasCastKind(CK_MemberPointerToBoolean)),
// Exclude cases of C23 comparis

[clang] [alpha.webkit.UncountedLocalVarsChecker] Warn the use of a raw pointer/reference when the guardian variable gets mutated. (PR #113859)

2024-10-27 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff fb33af08e4c105a05855f8beeb972d493410e72f 
8fce7f69eb5e28f6ec648ee0dc4cc23c793f64c0 --extensions cpp,h -- 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
clang/test/Analysis/Checkers/WebKit/mock-types.h 
clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp
``





View the diff from clang-format here.


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
index 5f5fb6e2bf..5978b23760 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
@@ -51,11 +51,10 @@ bool isRefcountedStringsHack(const VarDecl *V) {
 struct GuardianVisitor : public RecursiveASTVisitor {
   using Base = RecursiveASTVisitor;
 
-  const VarDecl *Guardian { nullptr };
+  const VarDecl *Guardian{nullptr};
 
 public:
-  explicit GuardianVisitor(const VarDecl *Guardian)
-  : Guardian(Guardian) {
+  explicit GuardianVisitor(const VarDecl *Guardian) : Guardian(Guardian) {
 assert(Guardian);
   }
 
@@ -69,7 +68,7 @@ public:
 return true;
   }
 
-  bool VisitCXXConstructExpr(const CXXConstructExpr* CE) {
+  bool VisitCXXConstructExpr(const CXXConstructExpr *CE) {
 if (auto *Ctor = CE->getConstructor()) {
   if (Ctor->isMoveConstructor() && CE->getNumArgs() == 1) {
 auto *Arg = CE->getArg(0)->IgnoreParenCasts();
@@ -82,7 +81,7 @@ public:
 return true;
   }
 
-  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr* MCE) {
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
 auto MethodName = safeGetName(MCE->getMethodDecl());
 if (MethodName == "swap" || MethodName == "leakRef" ||
 MethodName == "releaseNonNull") {
@@ -95,7 +94,7 @@ public:
 return true;
   }
 
-  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr* OCE) {
+  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE) {
 if (OCE->isAssignmentOp() && OCE->getNumArgs() == 2) {
   auto *ThisArg = OCE->getArg(0)->IgnoreParenCasts();
   if (auto *VarRef = dyn_cast(ThisArg)) {

``




https://github.com/llvm/llvm-project/pull/113859
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] support `return c ? a : b;` in bugprone-return-const-ref-from-parameter (PR #107657)

2024-10-27 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 approved this pull request.


https://github.com/llvm/llvm-project/pull/107657
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][RISCV] Support -fcf-protection=return for RISC-V (PR #112477)

2024-10-27 Thread Jesse Huang via cfe-commits

https://github.com/jaidTw updated 
https://github.com/llvm/llvm-project/pull/112477

>From fe4a28fb691b69d9af384f1dc2f0667761adef44 Mon Sep 17 00:00:00 2001
From: Jesse Huang 
Date: Sun, 13 Oct 2024 15:11:06 +0800
Subject: [PATCH 1/8] [Clang][RISCV] Support -fcf-protection=return for RISC-V

---
 clang/lib/Basic/Targets/RISCV.h   | 7 +++
 clang/lib/CodeGen/CodeGenFunction.cpp | 4 
 2 files changed, 11 insertions(+)

diff --git a/clang/lib/Basic/Targets/RISCV.h b/clang/lib/Basic/Targets/RISCV.h
index bf40edb8683b3e..3f2cee72fc3731 100644
--- a/clang/lib/Basic/Targets/RISCV.h
+++ b/clang/lib/Basic/Targets/RISCV.h
@@ -141,6 +141,13 @@ class RISCVTargetInfo : public TargetInfo {
 return true;
   }
 
+  bool
+  checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const override {
+if (ISAInfo->hasExtension("zimop"))
+  return true;
+return TargetInfo::checkCFProtectionReturnSupported(Diags);
+  }
+
   CFBranchLabelSchemeKind getDefaultCFBranchLabelScheme() const override {
 return CFBranchLabelSchemeKind::FuncSig;
   }
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 2306043c90f406..d8f0f7c14f6b40 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -899,6 +899,10 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
   if (CodeGenOpts.PointerAuth.IndirectGotos)
 Fn->addFnAttr("ptrauth-indirect-gotos");
 
+  // Add return control flow integrity attributes.
+  if (CodeGenOpts.CFProtectionReturn)
+Fn->addFnAttr("hw-shadow-stack");
+
   // Apply xray attributes to the function (as a string, for now)
   bool AlwaysXRayAttr = false;
   if (const auto *XRayAttr = D ? D->getAttr() : nullptr) {

>From 7dc168af5758d130042c71ba5d6249c042bc356c Mon Sep 17 00:00:00 2001
From: Jesse Huang 
Date: Wed, 23 Oct 2024 14:42:35 +0800
Subject: [PATCH 2/8] [Clang][RISCV] Add RISCV check for hw-shadow-stack

---
 clang/lib/CodeGen/CodeGenFunction.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index d8f0f7c14f6b40..cca52f3769845e 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -899,8 +899,9 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
   if (CodeGenOpts.PointerAuth.IndirectGotos)
 Fn->addFnAttr("ptrauth-indirect-gotos");
 
-  // Add return control flow integrity attributes.
-  if (CodeGenOpts.CFProtectionReturn)
+  // Add return control flow integrity attributes for RISCV.
+  if (CodeGenOpts.CFProtectionReturn &&
+  getContext().getTargetInfo().getTriple().isRISCV())
 Fn->addFnAttr("hw-shadow-stack");
 
   // Apply xray attributes to the function (as a string, for now)

>From 42132c246058f6c1aaa646266847a3b8c854 Mon Sep 17 00:00:00 2001
From: Jesse Huang 
Date: Thu, 24 Oct 2024 15:39:07 +0800
Subject: [PATCH 3/8] [Clang][RISCV] Add function attribute in RISC-V specific
 code

---
 clang/lib/CodeGen/CodeGenFunction.cpp | 5 -
 clang/lib/CodeGen/Targets/RISCV.cpp   | 7 +--
 2 files changed, 5 insertions(+), 7 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index cca52f3769845e..2306043c90f406 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -899,11 +899,6 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
   if (CodeGenOpts.PointerAuth.IndirectGotos)
 Fn->addFnAttr("ptrauth-indirect-gotos");
 
-  // Add return control flow integrity attributes for RISCV.
-  if (CodeGenOpts.CFProtectionReturn &&
-  getContext().getTargetInfo().getTriple().isRISCV())
-Fn->addFnAttr("hw-shadow-stack");
-
   // Apply xray attributes to the function (as a string, for now)
   bool AlwaysXRayAttr = false;
   if (const auto *XRayAttr = D ? D->getAttr() : nullptr) {
diff --git a/clang/lib/CodeGen/Targets/RISCV.cpp 
b/clang/lib/CodeGen/Targets/RISCV.cpp
index fd72fe673b9b14..b04e436c665f52 100644
--- a/clang/lib/CodeGen/Targets/RISCV.cpp
+++ b/clang/lib/CodeGen/Targets/RISCV.cpp
@@ -594,6 +594,11 @@ class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
 const auto *FD = dyn_cast_or_null(D);
 if (!FD) return;
 
+auto *Fn = cast(GV);
+
+if (CGM.getCodeGenOpts().CFProtectionReturn)
+  Fn->addFnAttr("hw-shadow-stack");
+
 const auto *Attr = FD->getAttr();
 if (!Attr)
   return;
@@ -604,8 +609,6 @@ class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
 case RISCVInterruptAttr::machine: Kind = "machine"; break;
 }
 
-auto *Fn = cast(GV);
-
 Fn->addFnAttr("interrupt", Kind);
   }
 };

>From 2b6bdc5e95043a0f481314c0c2e5441804addf06 Mon Sep 17 00:00:00 2001
From: Jesse Huang 
Date: Fri, 25 Oct 2024 14:13:45 +0800
Subject: [PATCH 4/8] [Clang] Add test for hw-shadodw-stack

---
 clang/test/CodeGen/RISCV/attr-hw-shadow-stack

[clang] Add /Zc:tlsGuards- option (PR #113830)

2024-10-27 Thread Maurice Heumann via cfe-commits

https://github.com/momo5502 updated 
https://github.com/llvm/llvm-project/pull/113830

>From 433a059884ce4bbfada60a300666fe58aecede4f Mon Sep 17 00:00:00 2001
From: momo5502 
Date: Sun, 27 Oct 2024 20:02:00 +0100
Subject: [PATCH] Add /Zc:tlsGuards option to control to control tls guard
 emission

---
 clang/include/clang/Basic/LangOptions.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/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 68db400c22e6c1..bf2f23a2828176 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -186,6 +186,7 @@ COMPATIBLE_LANGOPT(RecoveryAST, 1, 1, "Preserve expressions 
in AST when encounte
 COMPATIBLE_LANGOPT(RecoveryASTType, 1, 1, "Preserve the type in recovery 
expressions")
 
 BENIGN_LANGOPT(ThreadsafeStatics , 1, 1, "thread-safe static initializers")
+BENIGN_LANGOPT(TlsGuards , 1, 1, "on-demand TLS initialization")
 LANGOPT(POSIXThreads  , 1, 0, "POSIX thread support")
 LANGOPT(Blocks, 1, 0, "blocks extension to C")
 BENIGN_LANGOPT(EmitAllDecls  , 1, 0, "emitting all declarations")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5df6ddd5e6a0c5..84b1404c214511 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4063,6 +4063,11 @@ defm threadsafe_statics : 
BoolFOption<"threadsafe-statics",
   NegFlag,
   PosFlag>;
+defm tls_guards : BoolFOption<"tls-guards",
+  LangOpts<"TlsGuards">, DefaultTrue,
+  NegFlag,
+  PosFlag>;
 def ftime_report : Flag<["-"], "ftime-report">, Group,
   Visibility<[ClangOption, CC1Option]>,
   MarshallingInfoFlag>;
@@ -8610,6 +8615,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 0b0b45ffead92f..c705f3ad6e32ed 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) &&
+   getContext().getLangOpts().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 04b3832327a99c..63d55d5ad615dd 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7291,6 +7291,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 (!IsWindowsMSVC || IsMSVC2015Compatible)))
 CmdArgs.push_back("-fno-threadsafe-statics");
 
+  if (!Args.hasFlag(options::OPT_ftls_guards, options::OPT_fno_tls_guards,
+true))
+CmdArgs.push_back("-fno-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..cbd5647ee5032d 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-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 = A();
 // CHECK-LD-DAG: @"__tls_ini

[clang] Add /Zc:tlsGuards option to control to control tls guard emission (PR #113830)

2024-10-27 Thread Maurice Heumann via cfe-commits

https://github.com/momo5502 edited 
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] Add /Zc:tlsGuards option to control to control tls guard emission (PR #113830)

2024-10-27 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-clang

Author: Maurice Heumann (momo5502)


Changes

This fixes #103484

---
Full diff: https://github.com/llvm/llvm-project/pull/113830.diff


6 Files Affected:

- (modified) clang/include/clang/Basic/LangOptions.def (+1) 
- (modified) clang/include/clang/Driver/Options.td (+11) 
- (modified) clang/lib/CodeGen/MicrosoftCXXABI.cpp (+1) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+4) 
- (modified) clang/test/CodeGenCXX/ms-thread_local.cpp (+4) 
- (modified) clang/test/Driver/cl-zc.cpp (+3) 


``diff
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 68db400c22e6c1..bf2f23a2828176 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -186,6 +186,7 @@ COMPATIBLE_LANGOPT(RecoveryAST, 1, 1, "Preserve expressions 
in AST when encounte
 COMPATIBLE_LANGOPT(RecoveryASTType, 1, 1, "Preserve the type in recovery 
expressions")
 
 BENIGN_LANGOPT(ThreadsafeStatics , 1, 1, "thread-safe static initializers")
+BENIGN_LANGOPT(TlsGuards , 1, 1, "on-demand TLS initialization")
 LANGOPT(POSIXThreads  , 1, 0, "POSIX thread support")
 LANGOPT(Blocks, 1, 0, "blocks extension to C")
 BENIGN_LANGOPT(EmitAllDecls  , 1, 0, "emitting all declarations")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5df6ddd5e6a0c5..84b1404c214511 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4063,6 +4063,11 @@ defm threadsafe_statics : 
BoolFOption<"threadsafe-statics",
   NegFlag,
   PosFlag>;
+defm tls_guards : BoolFOption<"tls-guards",
+  LangOpts<"TlsGuards">, DefaultTrue,
+  NegFlag,
+  PosFlag>;
 def ftime_report : Flag<["-"], "ftime-report">, Group,
   Visibility<[ClangOption, CC1Option]>,
   MarshallingInfoFlag>;
@@ -8610,6 +8615,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 0b0b45ffead92f..c705f3ad6e32ed 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) &&
+   getContext().getLangOpts().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 04b3832327a99c..63d55d5ad615dd 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7291,6 +7291,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 (!IsWindowsMSVC || IsMSVC2015Compatible)))
 CmdArgs.push_back("-fno-threadsafe-statics");
 
+  if (!Args.hasFlag(options::OPT_ftls_guards, options::OPT_fno_tls_guards,
+true))
+CmdArgs.push_back("-fno-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..cbd5647ee5032d 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-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 = A();
 // CHECK-LD-DAG: @"__tls_init$initializer$" = internal constant ptr 
@__tls_init, sectio

[clang] Add /Zc:tlsGuards option to control to control tls guard emission (PR #113830)

2024-10-27 Thread Maurice Heumann via cfe-commits

https://github.com/momo5502 edited 
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] [MS] Add /Zc:tlsGuards option to control tls guard emission (PR #113830)

2024-10-27 Thread Maurice Heumann via cfe-commits

https://github.com/momo5502 edited 
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] [MS] Add /Zc:tlsGuards option to control to control tls guard emission (PR #113830)

2024-10-27 Thread Maurice Heumann via cfe-commits

https://github.com/momo5502 edited 
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] Add /Zc:tlsGuards option to control to control tls guard emission (PR #113830)

2024-10-27 Thread Maurice Heumann via cfe-commits

https://github.com/momo5502 ready_for_review 
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] [MS] Add /Zc:tlsGuards option to control tls guard emission (PR #113830)

2024-10-27 Thread Maurice Heumann via cfe-commits

https://github.com/momo5502 updated 
https://github.com/llvm/llvm-project/pull/113830

>From 23d4562382b753c604fffa078f8bdd0f75d57ac4 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/LangOptions.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/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 68db400c22e6c1..bf2f23a2828176 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -186,6 +186,7 @@ COMPATIBLE_LANGOPT(RecoveryAST, 1, 1, "Preserve expressions 
in AST when encounte
 COMPATIBLE_LANGOPT(RecoveryASTType, 1, 1, "Preserve the type in recovery 
expressions")
 
 BENIGN_LANGOPT(ThreadsafeStatics , 1, 1, "thread-safe static initializers")
+BENIGN_LANGOPT(TlsGuards , 1, 1, "on-demand TLS initialization")
 LANGOPT(POSIXThreads  , 1, 0, "POSIX thread support")
 LANGOPT(Blocks, 1, 0, "blocks extension to C")
 BENIGN_LANGOPT(EmitAllDecls  , 1, 0, "emitting all declarations")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5df6ddd5e6a0c5..84b1404c214511 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4063,6 +4063,11 @@ defm threadsafe_statics : 
BoolFOption<"threadsafe-statics",
   NegFlag,
   PosFlag>;
+defm tls_guards : BoolFOption<"tls-guards",
+  LangOpts<"TlsGuards">, DefaultTrue,
+  NegFlag,
+  PosFlag>;
 def ftime_report : Flag<["-"], "ftime-report">, Group,
   Visibility<[ClangOption, CC1Option]>,
   MarshallingInfoFlag>;
@@ -8610,6 +8615,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 0b0b45ffead92f..c705f3ad6e32ed 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) &&
+   getContext().getLangOpts().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 04b3832327a99c..63d55d5ad615dd 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7291,6 +7291,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 (!IsWindowsMSVC || IsMSVC2015Compatible)))
 CmdArgs.push_back("-fno-threadsafe-statics");
 
+  if (!Args.hasFlag(options::OPT_ftls_guards, options::OPT_fno_tls_guards,
+true))
+CmdArgs.push_back("-fno-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..cbd5647ee5032d 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-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 = A();
 // CHECK-LD-DAG: @"__tls_init$initi

[clang] [Clang] Add __ugly__ spelling for the msvc attribute scope (PR #113765)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Nikolas Klauser (philnik777)


Changes

This is required to avoid macro clashing when using attributes like 
`[[msvc::no_unique_address]]`.

This patch also refactor the logic for attribute scope __uglification__ into a 
single place to make it easier to add additional cases in case another one is 
required at some point again.



---
Full diff: https://github.com/llvm/llvm-project/pull/113765.diff


4 Files Affected:

- (modified) clang/include/clang/Basic/Attributes.h (+24) 
- (modified) clang/lib/Basic/Attributes.cpp (+9-14) 
- (modified) clang/lib/Sema/SemaCodeComplete.cpp (+4-19) 
- (modified) clang/test/SemaCXX/cxx2a-ms-no-unique-address.cpp (+3) 


``diff
diff --git a/clang/include/clang/Basic/Attributes.h 
b/clang/include/clang/Basic/Attributes.h
index 61666a6f4d9ac4..9fa7e5ce55d491 100644
--- a/clang/include/clang/Basic/Attributes.h
+++ b/clang/include/clang/Basic/Attributes.h
@@ -23,6 +23,30 @@ int hasAttribute(AttributeCommonInfo::Syntax Syntax,
  const IdentifierInfo *Scope, const IdentifierInfo *Attr,
  const TargetInfo &Target, const LangOptions &LangOpts);
 
+inline const char* deuglifyAttrScope(StringRef Scope) {
+  if (Scope == "_Clang")
+return "clang";
+  if (Scope == "__gnu__")
+return "gnu";
+  if (Scope == "__msvc__")
+return "msvc";
+  return nullptr;
+}
+
+inline const char* uglifyAttrScope(StringRef Scope) {
+  if (Scope == "clang")
+return "_Clang";
+  if (Scope == "gnu")
+return "__gnu__";
+  if (Scope == "msvc")
+return "__msvc__";
+  return nullptr;
+}
+
+inline bool isPotentiallyUglyScope(StringRef Scope) {
+  return Scope == "gnu" || Scope == "clang" || Scope == "msvc";
+}
+
 } // end namespace clang
 
 #endif // LLVM_CLANG_BASIC_ATTRIBUTES_H
diff --git a/clang/lib/Basic/Attributes.cpp b/clang/lib/Basic/Attributes.cpp
index 867d241a2cf847..4afa129e3b 100644
--- a/clang/lib/Basic/Attributes.cpp
+++ b/clang/lib/Basic/Attributes.cpp
@@ -38,10 +38,8 @@ int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
 
   // Normalize the scope name, but only for gnu and clang attributes.
   StringRef ScopeName = Scope ? Scope->getName() : "";
-  if (ScopeName == "__gnu__")
-ScopeName = "gnu";
-  else if (ScopeName == "_Clang")
-ScopeName = "clang";
+  if (const char *prettyName = deuglifyAttrScope(ScopeName))
+ScopeName = prettyName;
 
   // As a special case, look for the omp::sequence and omp::directive
   // attributes. We support those, but not through the typical attribute
@@ -87,10 +85,8 @@ normalizeAttrScopeName(const IdentifierInfo *Scope,
   StringRef ScopeName = Scope->getName();
   if (SyntaxUsed == AttributeCommonInfo::AS_CXX11 ||
   SyntaxUsed == AttributeCommonInfo::AS_C23) {
-if (ScopeName == "__gnu__")
-  ScopeName = "gnu";
-else if (ScopeName == "_Clang")
-  ScopeName = "clang";
+if (const char *prettySpelling = deuglifyAttrScope(ScopeName))
+  return prettySpelling;
   }
   return ScopeName;
 }
@@ -100,12 +96,11 @@ static StringRef normalizeAttrName(const IdentifierInfo 
*Name,
AttributeCommonInfo::Syntax SyntaxUsed) {
   // Normalize the attribute name, __foo__ becomes foo. This is only allowable
   // for GNU attributes, and attributes using the double square bracket syntax.
-  bool ShouldNormalize =
-  SyntaxUsed == AttributeCommonInfo::AS_GNU ||
-  ((SyntaxUsed == AttributeCommonInfo::AS_CXX11 ||
-SyntaxUsed == AttributeCommonInfo::AS_C23) &&
-   (NormalizedScopeName.empty() || NormalizedScopeName == "gnu" ||
-NormalizedScopeName == "clang"));
+  bool ShouldNormalize = SyntaxUsed == AttributeCommonInfo::AS_GNU ||
+ ((SyntaxUsed == AttributeCommonInfo::AS_CXX11 ||
+   SyntaxUsed == AttributeCommonInfo::AS_C23) &&
+  (NormalizedScopeName.empty() ||
+   isPotentiallyUglyScope(NormalizedScopeName)));
   StringRef AttrName = Name->getName();
   if (ShouldNormalize && AttrName.size() >= 4 && AttrName.starts_with("__") &&
   AttrName.ends_with("__"))
diff --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index 3e31f3d82657a3..732da9ceb0628f 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -25,6 +25,7 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/AttributeCommonInfo.h"
+#include "clang/Basic/Attributes.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/Specifiers.h"
@@ -4579,22 +4580,6 @@ void SemaCodeCompletion::CodeCompleteDeclSpec(Scope *S, 
DeclSpec &DS,
 Results.size());
 }
 
-static const char *underscoreAttrScope(llvm::StringRef Scope) {
-  if (Scope == "clang")
-return "_Clang";
-  if (Scope == "gnu")
-return "__gnu__";
-  retur

[clang] [Clang] Add __ugly__ spelling for the msvc attribute scope (PR #113765)

2024-10-27 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 ready_for_review 
https://github.com/llvm/llvm-project/pull/113765
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits




5chmidti wrote:

Please add tests where templates and macros are involved

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);
+}
+
+void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
+  const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression");
+  const auto UnSignedIntCastExpr =
+  intCastExpression(false, "uIntCastExpression");
+
+  // Flag all operators "==", "<=", ">=", "<", ">", "!="
+  // that are used between signed/unsigned
+  const auto CompareOperator =
+  expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="),
+  anyOf(allOf(hasLHS(SignedIntCastExpr),
+  hasRHS(UnSignedIntCastExpr)),
+allOf(hasLHS(UnSignedIntCastExpr),
+  hasRHS(SignedIntCastExpr)
+  .bind("intComparison");
+
+  Finder->addMatcher(CompareOperator, this);
+}
+
+BindableMatcher UseIntegerSignComparisonCheck::intCastExpression(
+bool IsSigned, const std::string &CastBindName) const {
+  auto IntTypeExpr = expr();
+  if (IsSigned) {
+IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(;
+  } else {
+IntTypeExpr =
+expr(hasType(qualType(isInteger(), unless(isSignedInteger();
+  }
+
+  const auto ImplicitCastExpr =
+  implicitCastExpr(hasSourceExpression(IntTypeExpr)).bind(CastBindName);
+
+  const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr));
+  const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr));
+  const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr));
+
+  return traverse(TK_AsIs, expr(anyOf(ImplicitCastExpr, CStyleCastExpr,
+  StaticCastExpr, FunctionalCastExpr)));
+}
+
+std::string
+UseIntegerSignComparisonCheck::parseOpCode(BinaryOperator::Opcode code) const {
+  switch (code) {
+  case BO_LT:
+return std::string("cmp_less");
+  case BO_GT:
+return std::string("cmp_greater");
+  case BO_LE:
+return std::string("cmp_less_equal");
+  case BO_GE:
+return std::string("cmp_greater_equal");
+  case BO_EQ:
+return std::string("cmp_equal");
+  case BO_NE:
+return std::string("cmp_not_equal");
+  default:
+return {};
+  }
+}

5chmidti wrote:

Instead of constructing a `std::string`, please return an `llvm::StringRef`, 
and this function could be a free, `static` function as well

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);
+}
+
+void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
+  const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression");
+  const auto UnSignedIntCastExpr =
+  intCastExpression(false, "uIntCastExpression");
+
+  // Flag all operators "==", "<=", ">=", "<", ">", "!="
+  // that are used between signed/unsigned
+  const auto CompareOperator =
+  expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="),

5chmidti wrote:

Please add `unless(isInstantiationDependent())` into `binaryOperator`. We would 
not want to replace the code of a template that is instantiated with integral 
types, and types that have an overloaded operator implemented.

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);
+}
+
+void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
+  const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression");
+  const auto UnSignedIntCastExpr =
+  intCastExpression(false, "uIntCastExpression");
+
+  // Flag all operators "==", "<=", ">=", "<", ">", "!="
+  // that are used between signed/unsigned
+  const auto CompareOperator =
+  expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="),
+  anyOf(allOf(hasLHS(SignedIntCastExpr),
+  hasRHS(UnSignedIntCastExpr)),
+allOf(hasLHS(UnSignedIntCastExpr),
+  hasRHS(SignedIntCastExpr)
+  .bind("intComparison");
+
+  Finder->addMatcher(CompareOperator, this);
+}
+
+BindableMatcher UseIntegerSignComparisonCheck::intCastExpression(
+bool IsSigned, const std::string &CastBindName) const {
+  auto IntTypeExpr = expr();
+  if (IsSigned) {
+IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(;
+  } else {
+IntTypeExpr =
+expr(hasType(qualType(isInteger(), unless(isSignedInteger();
+  }
+
+  const auto ImplicitCastExpr =
+  implicitCastExpr(hasSourceExpression(IntTypeExpr)).bind(CastBindName);
+
+  const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr));
+  const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr));
+  const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr));
+
+  return traverse(TK_AsIs, expr(anyOf(ImplicitCastExpr, CStyleCastExpr,
+  StaticCastExpr, FunctionalCastExpr)));
+}
+
+std::string
+UseIntegerSignComparisonCheck::parseOpCode(BinaryOperator::Opcode code) const {
+  switch (code) {
+  case BO_LT:
+return std::string("cmp_less");
+  case BO_GT:
+return std::string("cmp_greater");
+  case BO_LE:
+return std::string("cmp_less_equal");
+  case BO_GE:
+return std::string("cmp_greater_equal");
+  case BO_EQ:
+return std::string("cmp_equal");
+  case BO_NE:
+return std::string("cmp_not_equal");
+  default:
+return {};
+  }
+}
+
+void UseIntegerSignComparisonCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  IncludeInserter.registerPreprocessor(PP);
+}
+
+void UseIntegerSignComparisonCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *SignedCastExpression =
+  Result.Nodes.getNodeAs("sIntCastExpression");
+  const auto *UnSignedCastExpression =
+  Result.Nodes.getNodeAs("uIntCastExpression");
+  assert(SignedCastExpression);
+  assert(UnSignedCastExpression);
+
+  // Ignore the match if we know that the signed int value is not negative.
+  Expr::EvalResult EVResult;
+  if (!SignedCastExpression->isValueDependent() &&
+  SignedCastExpression->getSubExpr()->EvaluateAsInt(EVResult,
+*Result.Context)) {
+const llvm::APSInt SValue = EVResult.Val.getInt();
+if (SValue.isNonNegative())
+  return;
+  }
+
+  const auto *BinaryOp =
+  Result.Nodes.getNodeAs("intComparison");
+  if (BinaryOp == nullptr)
+return;
+
+  const BinaryOperator::Opcode OpCode = BinaryOp->getOpcode();
+  const Expr *LHS = BinaryOp->getLHS()->IgnoreParenImpCasts();
+  const Expr *RHS = BinaryOp->getRHS()->IgnoreParenImpCasts();

5chmidti wrote:

Because you determine LHS and RHS like this, the replacement will include the 
explicit cast if there is any, while it could have removed that

[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);

5chmidti wrote:

If instead, you provide the header as an option and a namespace, then the check 
would be even more generic and the Qt module would not be needed (not saying a 
Qt module wouldn't make sense, just that this check may not require adding it). 
Though a quick look at boost, gsl and abseil did not show them having such 
functions.

(You could mention the settings for QT in the documentation as an example)

It would be best to check what others think, though. Thoughts?

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);
+}
+
+void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
+  const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression");
+  const auto UnSignedIntCastExpr =
+  intCastExpression(false, "uIntCastExpression");
+
+  // Flag all operators "==", "<=", ">=", "<", ">", "!="
+  // that are used between signed/unsigned
+  const auto CompareOperator =
+  expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="),
+  anyOf(allOf(hasLHS(SignedIntCastExpr),
+  hasRHS(UnSignedIntCastExpr)),
+allOf(hasLHS(UnSignedIntCastExpr),
+  hasRHS(SignedIntCastExpr)
+  .bind("intComparison");
+
+  Finder->addMatcher(CompareOperator, this);
+}
+
+BindableMatcher UseIntegerSignComparisonCheck::intCastExpression(
+bool IsSigned, const std::string &CastBindName) const {
+  auto IntTypeExpr = expr();
+  if (IsSigned) {
+IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(;
+  } else {
+IntTypeExpr =
+expr(hasType(qualType(isInteger(), unless(isSignedInteger();
+  }
+
+  const auto ImplicitCastExpr =
+  implicitCastExpr(hasSourceExpression(IntTypeExpr)).bind(CastBindName);
+
+  const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr));
+  const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr));
+  const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr));
+
+  return traverse(TK_AsIs, expr(anyOf(ImplicitCastExpr, CStyleCastExpr,
+  StaticCastExpr, FunctionalCastExpr)));
+}
+
+std::string
+UseIntegerSignComparisonCheck::parseOpCode(BinaryOperator::Opcode code) const {
+  switch (code) {
+  case BO_LT:
+return std::string("cmp_less");
+  case BO_GT:
+return std::string("cmp_greater");
+  case BO_LE:
+return std::string("cmp_less_equal");
+  case BO_GE:
+return std::string("cmp_greater_equal");
+  case BO_EQ:
+return std::string("cmp_equal");
+  case BO_NE:
+return std::string("cmp_not_equal");
+  default:
+return {};
+  }
+}
+
+void UseIntegerSignComparisonCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  IncludeInserter.registerPreprocessor(PP);
+}
+
+void UseIntegerSignComparisonCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *SignedCastExpression =
+  Result.Nodes.getNodeAs("sIntCastExpression");
+  const auto *UnSignedCastExpression =
+  Result.Nodes.getNodeAs("uIntCastExpression");

5chmidti wrote:

`UnSignedCastExpression` is only ever asserted upon, and the bound not is not 
needed by the matcher itself. Please remove it and the binding of 
`uIntCastExpression`.

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,26 @@
+set(LLVM_LINK_COMPONENTS
+FrontendOpenMP
+Support
+)
+
+add_clang_library(clangTidyQtModule

5chmidti wrote:

Please add `STATIC` at the end of this line. This was changed just a few days 
ago to be explicit

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);
+}
+
+void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
+  const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression");
+  const auto UnSignedIntCastExpr =
+  intCastExpression(false, "uIntCastExpression");
+
+  // Flag all operators "==", "<=", ">=", "<", ">", "!="
+  // that are used between signed/unsigned
+  const auto CompareOperator =
+  expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="),
+  anyOf(allOf(hasLHS(SignedIntCastExpr),
+  hasRHS(UnSignedIntCastExpr)),
+allOf(hasLHS(UnSignedIntCastExpr),
+  hasRHS(SignedIntCastExpr)
+  .bind("intComparison");
+
+  Finder->addMatcher(CompareOperator, this);
+}
+
+BindableMatcher UseIntegerSignComparisonCheck::intCastExpression(
+bool IsSigned, const std::string &CastBindName) const {
+  auto IntTypeExpr = expr();
+  if (IsSigned) {
+IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(;
+  } else {
+IntTypeExpr =
+expr(hasType(qualType(isInteger(), unless(isSignedInteger();
+  }
+
+  const auto ImplicitCastExpr =
+  implicitCastExpr(hasSourceExpression(IntTypeExpr)).bind(CastBindName);
+
+  const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr));
+  const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr));
+  const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr));
+
+  return traverse(TK_AsIs, expr(anyOf(ImplicitCastExpr, CStyleCastExpr,
+  StaticCastExpr, FunctionalCastExpr)));

5chmidti wrote:

This `traverse` has no effect, as the default traversal is already `AsIs` 
traversal.

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);
+}
+
+void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
+  const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression");
+  const auto UnSignedIntCastExpr =
+  intCastExpression(false, "uIntCastExpression");
+
+  // Flag all operators "==", "<=", ">=", "<", ">", "!="
+  // that are used between signed/unsigned
+  const auto CompareOperator =
+  expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="),
+  anyOf(allOf(hasLHS(SignedIntCastExpr),
+  hasRHS(UnSignedIntCastExpr)),
+allOf(hasLHS(UnSignedIntCastExpr),
+  hasRHS(SignedIntCastExpr)
+  .bind("intComparison");
+
+  Finder->addMatcher(CompareOperator, this);
+}
+
+BindableMatcher UseIntegerSignComparisonCheck::intCastExpression(
+bool IsSigned, const std::string &CastBindName) const {
+  auto IntTypeExpr = expr();
+  if (IsSigned) {
+IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(;
+  } else {
+IntTypeExpr =
+expr(hasType(qualType(isInteger(), unless(isSignedInteger();
+  }
+
+  const auto ImplicitCastExpr =
+  implicitCastExpr(hasSourceExpression(IntTypeExpr)).bind(CastBindName);
+
+  const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr));
+  const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr));
+  const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr));
+
+  return traverse(TK_AsIs, expr(anyOf(ImplicitCastExpr, CStyleCastExpr,
+  StaticCastExpr, FunctionalCastExpr)));
+}

5chmidti wrote:

This could be a free, `static` function instead.

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,47 @@
+//===--- UseIntegerSignComparisonCheck.h - clang-tidy ---*- 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_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USEINTEGERSIGNCOMPARISONCHECK_H
+#define 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USEINTEGERSIGNCOMPARISONCHECK_H
+
+#include "../ClangTidyCheck.h"
+#include "../utils/IncludeInserter.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+namespace clang::tidy::modernize {
+
+/// Class detects comparisons between signed and unsigned integers
+///
+/// For the user-facing documentation see:
+/// 
http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-integer-sign-comparison.html
+class UseIntegerSignComparisonCheck : public ClangTidyCheck {
+public:
+  UseIntegerSignComparisonCheck(StringRef Name, ClangTidyContext *Context);
+
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+  void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
+   Preprocessor *ModuleExpanderPP) override;
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+return LangOpts.CPlusPlus;
+  }

5chmidti wrote:

You are currently checking the C++ version after matching and only for the 
FixIt, which means that this check runs even in e.g., C++11 and offers a 
replacement for `cmp_...`, which does not actually exist.
Instead, do something like: `return (IsQtApplication && 
getLangOpts().CPlusPlus17) || getLangOpts().CPlusPlus20;` here (also depends on 
the result of my comment on the options of this check)

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);
+}
+
+void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
+  const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression");
+  const auto UnSignedIntCastExpr =
+  intCastExpression(false, "uIntCastExpression");
+
+  // Flag all operators "==", "<=", ">=", "<", ">", "!="
+  // that are used between signed/unsigned
+  const auto CompareOperator =
+  expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="),
+  anyOf(allOf(hasLHS(SignedIntCastExpr),
+  hasRHS(UnSignedIntCastExpr)),
+allOf(hasLHS(UnSignedIntCastExpr),
+  hasRHS(SignedIntCastExpr)
+  .bind("intComparison");
+
+  Finder->addMatcher(CompareOperator, this);
+}
+
+BindableMatcher UseIntegerSignComparisonCheck::intCastExpression(
+bool IsSigned, const std::string &CastBindName) const {
+  auto IntTypeExpr = expr();
+  if (IsSigned) {
+IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(;
+  } else {
+IntTypeExpr =
+expr(hasType(qualType(isInteger(), unless(isSignedInteger();
+  }
+
+  const auto ImplicitCastExpr =
+  implicitCastExpr(hasSourceExpression(IntTypeExpr)).bind(CastBindName);
+
+  const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr));
+  const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr));
+  const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr));
+
+  return traverse(TK_AsIs, expr(anyOf(ImplicitCastExpr, CStyleCastExpr,
+  StaticCastExpr, FunctionalCastExpr)));
+}
+
+std::string
+UseIntegerSignComparisonCheck::parseOpCode(BinaryOperator::Opcode code) const {

5chmidti wrote:

`code` -> `Code`

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);
+}
+
+void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
+  const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression");
+  const auto UnSignedIntCastExpr =
+  intCastExpression(false, "uIntCastExpression");
+
+  // Flag all operators "==", "<=", ">=", "<", ">", "!="
+  // that are used between signed/unsigned
+  const auto CompareOperator =
+  expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="),
+  anyOf(allOf(hasLHS(SignedIntCastExpr),
+  hasRHS(UnSignedIntCastExpr)),
+allOf(hasLHS(UnSignedIntCastExpr),
+  hasRHS(SignedIntCastExpr)
+  .bind("intComparison");
+
+  Finder->addMatcher(CompareOperator, this);
+}
+
+BindableMatcher UseIntegerSignComparisonCheck::intCastExpression(
+bool IsSigned, const std::string &CastBindName) const {
+  auto IntTypeExpr = expr();
+  if (IsSigned) {
+IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(;
+  } else {
+IntTypeExpr =
+expr(hasType(qualType(isInteger(), unless(isSignedInteger();
+  }

5chmidti wrote:

nit: For control structures, LLVM mostly avoids adding braces for single, 
simple statements like here

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti edited 
https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-10-27 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti requested changes to this pull request.

This will be very nice to get in

https://github.com/llvm/llvm-project/pull/113144
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] RFC: [clang-tidy] [analyzer] Move nondeterministic pointer usage check to tidy (PR #110471)

2024-10-27 Thread via cfe-commits

vabridgers wrote:

Thanks @5chmidti ! I do plan to work on improvements, but would like to get 
this baseline checker in for now as a "scope of work" for this PR. I don't mind 
documenting the improvement steps per @whisperity suggestions, and addressing 
your most recent comments. Do you have suggestions on where to document 
improvements? Same as @whisperity ?

I'll plan on a "next iteration" of changes to address your recent comments, 
document improvement opportunities, and see if that documentation build error 
clears up (I cannot see how my patch exposes this?).

Thanks for the comments, and happy this found something interesting. 

https://github.com/llvm/llvm-project/pull/110471
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] RFC: [clang-tidy] [analyzer] Move nondeterministic pointer usage check to tidy (PR #110471)

2024-10-27 Thread via cfe-commits

https://github.com/vabridgers updated 
https://github.com/llvm/llvm-project/pull/110471

>From 4dc4e525ffbf9bb391356008011f5cc6ab20bc1d Mon Sep 17 00:00:00 2001
From: Vince Bridgers 
Date: Thu, 26 Sep 2024 16:24:59 +0200
Subject: [PATCH] [clang-tidy] [analyzer] Move nondeterministic pointer usage
 check to tidy

This change moves the alpha.nondeterministic.PointerSorting and
alpha.nondeterministic.PointerIteration static analyzer checkers to
a single clang-tidy check. Those checkers were implemented as clang-tidy
checks wrapped in the static analyzer framework. The documentation was
updated to describe what the checks can and cannot do, and testing
was completed on a broad set of open source projects.
---
 .../bugprone/BugproneTidyModule.cpp   |   3 +
 .../clang-tidy/bugprone/CMakeLists.txt|   1 +
 ...eterministicPointerIterationOrderCheck.cpp |  79 +
 ...ndeterministicPointerIterationOrderCheck.h |  39 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 ...ndeterministic-pointer-iteration-order.rst |  44 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../system-header-simulator/sim_algorithm |  31 
 .../system-header-simulator/sim_c++config.h   |  11 ++
 .../sim_initializer_list  |  39 +
 .../system-header-simulator/sim_iterator_base |  22 +++
 .../Inputs/system-header-simulator/sim_map|  34 
 .../Inputs/system-header-simulator/sim_set|  44 +
 .../system-header-simulator/sim_stl_pair  |  32 
 .../system-header-simulator/sim_type_traits   |  19 +++
 .../system-header-simulator/sim_unordered_map |  33 
 .../system-header-simulator/sim_unordered_set |  35 
 .../Inputs/system-header-simulator/sim_vector | 150 ++
 ...ndeterministic-pointer-iteration-order.cpp |  84 ++
 clang/docs/ReleaseNotes.rst   |   6 +
 clang/docs/analyzer/checkers.rst  |  31 
 .../clang/StaticAnalyzer/Checkers/Checkers.td |  18 ---
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   2 -
 .../Checkers/PointerIterationChecker.cpp  | 101 
 .../Checkers/PointerSortingChecker.cpp| 115 --
 clang/test/Analysis/ptr-iter.cpp  |  28 
 clang/test/Analysis/ptr-sort.cpp  |  36 -
 27 files changed, 713 insertions(+), 331 deletions(-)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/nondeterministic-pointer-iteration-order.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_algorithm
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_c++config.h
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_initializer_list
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_iterator_base
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_map
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_set
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_stl_pair
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_type_traits
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_unordered_map
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_unordered_set
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/system-header-simulator/sim_vector
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/nondeterministic-pointer-iteration-order.cpp
 delete mode 100644 
clang/lib/StaticAnalyzer/Checkers/PointerIterationChecker.cpp
 delete mode 100644 clang/lib/StaticAnalyzer/Checkers/PointerSortingChecker.cpp
 delete mode 100644 clang/test/Analysis/ptr-iter.cpp
 delete mode 100644 clang/test/Analysis/ptr-sort.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 9120c4b6c0d9ae..33ac65e715ce81 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -49,6 +49,7 @@
 #include "MultipleStatementMacroCheck.h"
 #include "NoEscapeCheck.h"
 #include "NonZeroEnumToBoolConversionCheck.h"
+#include "NondeterministicPointerIterationOrderCheck.h"
 #include "NotNullTerminatedResultCheck.h"
 #include "OptionalValueConversionCheck.h"
 #include "ParentVirtual

[clang] [webkit.UncountedLambdaCapturesChecker] Ignore trivial functions and [[clang::noescape]]. (PR #113845)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1

Author: Ryosuke Niwa (rniwa)


Changes

This PR makes webkit.UncountedLambdaCapturesChecker ignore trivial functions as 
well as the one being passed to an argument with [[clang::noescape]] attribute. 
This dramatically reduces the false positive rate for this checker.

To do this, this PR replaces VisitLambdaExpr in favor of checking lambdas via 
VisitDeclRefExpr and VisitCallExpr. The idea is that if a lambda is defined but 
never called or stored somewhere, then capturing whatever variable in such a 
lambda is harmless.

VisitCallExpr explicitly looks for direct invocation of lambdas and registers 
its DeclRefExpr to be ignored in VisitDeclRefExpr. If a lambda is being passed 
to a function, it checks whether its argument is annotated with 
[[clang::noescape]]. If it's not annotated such, it checks captures for their 
safety.

Because WTF::switchOn could not be annotated with [[clang::noescape]] as 
function type parameters are variadic template function so we hard-code this 
function into the checker.

Finally, this PR also converts the accompanying test to use -verify and adds a 
bunch of tests.

---
Full diff: https://github.com/llvm/llvm-project/pull/113845.diff


4 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h (+4) 
- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp 
(+92-10) 
- (modified) clang/test/Analysis/Checkers/WebKit/mock-types.h (+2) 
- (modified) clang/test/Analysis/Checkers/WebKit/uncounted-lambda-captures.cpp 
(+135-24) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index 4b41ca96e1df1d..814015c311d61e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -63,6 +63,10 @@ std::optional isUncounted(const clang::CXXRecordDecl* 
Class);
 /// class, false if not, std::nullopt if inconclusive.
 std::optional isUncountedPtr(const clang::QualType T);
 
+/// \returns true if \p T is either a raw pointer or reference to an uncounted
+/// or unchecked class, false if not, std::nullopt if inconclusive.
+std::optional isUnsafePtr(const QualType T);
+
 /// \returns true if \p T is a RefPtr, Ref, CheckedPtr, CheckedRef, or its
 /// variant, false if not.
 bool isSafePtrType(const clang::QualType T);
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
index 998bd4ccee07db..02f68ac5e41317 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
@@ -6,6 +6,7 @@
 //
 
//===--===//
 
+#include "ASTUtils.h"
 #include "DiagOutputUtils.h"
 #include "PtrTypesSemantics.h"
 #include "clang/AST/CXXInheritance.h"
@@ -26,6 +27,7 @@ class UncountedLambdaCapturesChecker
   BugType Bug{this, "Lambda capture of uncounted variable",
   "WebKit coding guidelines"};
   mutable BugReporter *BR = nullptr;
+  TrivialFunctionAnalysis TFA;
 
 public:
   void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
@@ -37,6 +39,8 @@ class UncountedLambdaCapturesChecker
 // want to visit those, so we make our own RecursiveASTVisitor.
 struct LocalVisitor : public RecursiveASTVisitor {
   const UncountedLambdaCapturesChecker *Checker;
+  llvm::DenseSet DeclRefExprsToIgnore;
+
   explicit LocalVisitor(const UncountedLambdaCapturesChecker *Checker)
   : Checker(Checker) {
 assert(Checker);
@@ -45,8 +49,61 @@ class UncountedLambdaCapturesChecker
   bool shouldVisitTemplateInstantiations() const { return true; }
   bool shouldVisitImplicitCode() const { return false; }
 
-  bool VisitLambdaExpr(LambdaExpr *L) {
-Checker->visitLambdaExpr(L);
+  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
+if (DeclRefExprsToIgnore.contains(DRE))
+  return true;
+if (auto *VD = dyn_cast_or_null(DRE->getDecl())) {
+  auto *Init = VD->getInit()->IgnoreParenCasts();
+  if (auto *L = dyn_cast_or_null(Init)) {
+Checker->visitLambdaExpr(L);
+return true;
+  }
+}
+return true;
+  }
+
+  // WTF::switchOn(T, F... f) is a variadic template function and couldn't 
be annotated with NOESCAPE.
+  // We hard code it here to workaround that.
+  bool shouldTreatAllArgAsNoEscape(FunctionDecl *Decl) {
+auto *NsDecl = Decl->getParent();
+if (!NsDecl || !isa(NsDecl))
+  return false;
+return safeGetName(NsDecl) == "WTF" && safeGetName(Decl) == "switchOn";
+  }
+
+  bool VisitCallExpr(CallExpr *CE) {
+if (auto

[clang] [webkit.UncountedLambdaCapturesChecker] Ignore trivial functions and [[clang::noescape]]. (PR #113845)

2024-10-27 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa created 
https://github.com/llvm/llvm-project/pull/113845

This PR makes webkit.UncountedLambdaCapturesChecker ignore trivial functions as 
well as the one being passed to an argument with [[clang::noescape]] attribute. 
This dramatically reduces the false positive rate for this checker.

To do this, this PR replaces VisitLambdaExpr in favor of checking lambdas via 
VisitDeclRefExpr and VisitCallExpr. The idea is that if a lambda is defined but 
never called or stored somewhere, then capturing whatever variable in such a 
lambda is harmless.

VisitCallExpr explicitly looks for direct invocation of lambdas and registers 
its DeclRefExpr to be ignored in VisitDeclRefExpr. If a lambda is being passed 
to a function, it checks whether its argument is annotated with 
[[clang::noescape]]. If it's not annotated such, it checks captures for their 
safety.

Because WTF::switchOn could not be annotated with [[clang::noescape]] as 
function type parameters are variadic template function so we hard-code this 
function into the checker.

Finally, this PR also converts the accompanying test to use -verify and adds a 
bunch of tests.

>From 1524ca532c9c1ef015c162360d4e4688296bbc0d Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 27 Oct 2024 16:30:48 -0700
Subject: [PATCH] [webkit.UncountedLambdaCapturesChecker] Ignore trivial
 functions and [[clang::noescape]].

This PR makes webkit.UncountedLambdaCapturesChecker ignore trivial functions as 
well as
the one being passed to an argument with [[clang::noescape]] attribute. This 
dramatically
reduces the false positive rate for this checker.

To do this, this PR replaces VisitLambdaExpr in favor of checking lambdas via 
VisitDeclRefExpr
and VisitCallExpr. The idea is that if a lambda is defined but never called or 
stored somewhere,
then capturing whatever variable in such a lambda is harmless.

VisitCallExpr explicitly looks for direct invocation of lambdas and registers 
its DeclRefExpr
to be ignored in VisitDeclRefExpr. If a lambda is being passed to a function, 
it checks whether
its argument is annotated with [[clang::noescape]]. If it's not annotated such, 
it checks
captures for their safety.

Because WTF::switchOn could not be annotated with [[clang::noescape]] as 
function type parameters
are variadic template function so we hard-code this function into the checker.

Finally, this PR also converts the accompanying test to use -verify and adds a 
bunch of tests.
---
 .../Checkers/WebKit/PtrTypesSemantics.h   |   4 +
 .../WebKit/UncountedLambdaCapturesChecker.cpp | 102 +--
 .../Analysis/Checkers/WebKit/mock-types.h |   2 +
 .../WebKit/uncounted-lambda-captures.cpp  | 159 +++---
 4 files changed, 233 insertions(+), 34 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index 4b41ca96e1df1d..814015c311d61e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -63,6 +63,10 @@ std::optional isUncounted(const clang::CXXRecordDecl* 
Class);
 /// class, false if not, std::nullopt if inconclusive.
 std::optional isUncountedPtr(const clang::QualType T);
 
+/// \returns true if \p T is either a raw pointer or reference to an uncounted
+/// or unchecked class, false if not, std::nullopt if inconclusive.
+std::optional isUnsafePtr(const QualType T);
+
 /// \returns true if \p T is a RefPtr, Ref, CheckedPtr, CheckedRef, or its
 /// variant, false if not.
 bool isSafePtrType(const clang::QualType T);
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
index 998bd4ccee07db..02f68ac5e41317 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
@@ -6,6 +6,7 @@
 //
 
//===--===//
 
+#include "ASTUtils.h"
 #include "DiagOutputUtils.h"
 #include "PtrTypesSemantics.h"
 #include "clang/AST/CXXInheritance.h"
@@ -26,6 +27,7 @@ class UncountedLambdaCapturesChecker
   BugType Bug{this, "Lambda capture of uncounted variable",
   "WebKit coding guidelines"};
   mutable BugReporter *BR = nullptr;
+  TrivialFunctionAnalysis TFA;
 
 public:
   void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
@@ -37,6 +39,8 @@ class UncountedLambdaCapturesChecker
 // want to visit those, so we make our own RecursiveASTVisitor.
 struct LocalVisitor : public RecursiveASTVisitor {
   const UncountedLambdaCapturesChecker *Checker;
+  llvm::DenseSet DeclRefExprsToIgnore;
+
   explicit LocalVisitor(const UncountedLambdaCapturesChecker *Checker)
   : Checker(Checker) {
 assert(Checker);
@@ -45,8 +49,61 @@ 

[clang] [webkit.UncountedLambdaCapturesChecker] Ignore trivial functions and [[clang::noescape]]. (PR #113845)

2024-10-27 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ryosuke Niwa (rniwa)


Changes

This PR makes webkit.UncountedLambdaCapturesChecker ignore trivial functions as 
well as the one being passed to an argument with [[clang::noescape]] attribute. 
This dramatically reduces the false positive rate for this checker.

To do this, this PR replaces VisitLambdaExpr in favor of checking lambdas via 
VisitDeclRefExpr and VisitCallExpr. The idea is that if a lambda is defined but 
never called or stored somewhere, then capturing whatever variable in such a 
lambda is harmless.

VisitCallExpr explicitly looks for direct invocation of lambdas and registers 
its DeclRefExpr to be ignored in VisitDeclRefExpr. If a lambda is being passed 
to a function, it checks whether its argument is annotated with 
[[clang::noescape]]. If it's not annotated such, it checks captures for their 
safety.

Because WTF::switchOn could not be annotated with [[clang::noescape]] as 
function type parameters are variadic template function so we hard-code this 
function into the checker.

Finally, this PR also converts the accompanying test to use -verify and adds a 
bunch of tests.

---
Full diff: https://github.com/llvm/llvm-project/pull/113845.diff


4 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h (+4) 
- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp 
(+92-10) 
- (modified) clang/test/Analysis/Checkers/WebKit/mock-types.h (+2) 
- (modified) clang/test/Analysis/Checkers/WebKit/uncounted-lambda-captures.cpp 
(+135-24) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index 4b41ca96e1df1d..814015c311d61e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -63,6 +63,10 @@ std::optional isUncounted(const clang::CXXRecordDecl* 
Class);
 /// class, false if not, std::nullopt if inconclusive.
 std::optional isUncountedPtr(const clang::QualType T);
 
+/// \returns true if \p T is either a raw pointer or reference to an uncounted
+/// or unchecked class, false if not, std::nullopt if inconclusive.
+std::optional isUnsafePtr(const QualType T);
+
 /// \returns true if \p T is a RefPtr, Ref, CheckedPtr, CheckedRef, or its
 /// variant, false if not.
 bool isSafePtrType(const clang::QualType T);
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
index 998bd4ccee07db..02f68ac5e41317 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
@@ -6,6 +6,7 @@
 //
 
//===--===//
 
+#include "ASTUtils.h"
 #include "DiagOutputUtils.h"
 #include "PtrTypesSemantics.h"
 #include "clang/AST/CXXInheritance.h"
@@ -26,6 +27,7 @@ class UncountedLambdaCapturesChecker
   BugType Bug{this, "Lambda capture of uncounted variable",
   "WebKit coding guidelines"};
   mutable BugReporter *BR = nullptr;
+  TrivialFunctionAnalysis TFA;
 
 public:
   void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
@@ -37,6 +39,8 @@ class UncountedLambdaCapturesChecker
 // want to visit those, so we make our own RecursiveASTVisitor.
 struct LocalVisitor : public RecursiveASTVisitor {
   const UncountedLambdaCapturesChecker *Checker;
+  llvm::DenseSet DeclRefExprsToIgnore;
+
   explicit LocalVisitor(const UncountedLambdaCapturesChecker *Checker)
   : Checker(Checker) {
 assert(Checker);
@@ -45,8 +49,61 @@ class UncountedLambdaCapturesChecker
   bool shouldVisitTemplateInstantiations() const { return true; }
   bool shouldVisitImplicitCode() const { return false; }
 
-  bool VisitLambdaExpr(LambdaExpr *L) {
-Checker->visitLambdaExpr(L);
+  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
+if (DeclRefExprsToIgnore.contains(DRE))
+  return true;
+if (auto *VD = dyn_cast_or_null(DRE->getDecl())) {
+  auto *Init = VD->getInit()->IgnoreParenCasts();
+  if (auto *L = dyn_cast_or_null(Init)) {
+Checker->visitLambdaExpr(L);
+return true;
+  }
+}
+return true;
+  }
+
+  // WTF::switchOn(T, F... f) is a variadic template function and couldn't 
be annotated with NOESCAPE.
+  // We hard code it here to workaround that.
+  bool shouldTreatAllArgAsNoEscape(FunctionDecl *Decl) {
+auto *NsDecl = Decl->getParent();
+if (!NsDecl || !isa(NsDecl))
+  return false;
+return safeGetName(NsDecl) == "WTF" && safeGetName(Decl) == "switchOn";
+  }
+
+  bool VisitCallExpr(CallExpr *CE) {
+if (auto *Callee = CE->get

[clang] [webkit.UncountedLambdaCapturesChecker] Ignore trivial functions and [[clang::noescape]]. (PR #113845)

2024-10-27 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff fb33af08e4c105a05855f8beeb972d493410e72f 
1524ca532c9c1ef015c162360d4e4688296bbc0d --extensions h,cpp -- 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp 
clang/test/Analysis/Checkers/WebKit/mock-types.h 
clang/test/Analysis/Checkers/WebKit/uncounted-lambda-captures.cpp
``





View the diff from clang-format here.


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
index 02f68ac5e4..1d0730e9d5 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp
@@ -62,8 +62,8 @@ public:
 return true;
   }
 
-  // WTF::switchOn(T, F... f) is a variadic template function and couldn't 
be annotated with NOESCAPE.
-  // We hard code it here to workaround that.
+  // WTF::switchOn(T, F... f) is a variadic template function and couldn't
+  // be annotated with NOESCAPE. We hard code it here to workaround that.
   bool shouldTreatAllArgAsNoEscape(FunctionDecl *Decl) {
 auto *NsDecl = Decl->getParent();
 if (!NsDecl || !isa(NsDecl))
@@ -82,7 +82,8 @@ public:
 auto *Init = VD->getInit()->IgnoreParenCasts();
 if (auto *L = dyn_cast_or_null(Init)) {
   DeclRefExprsToIgnore.insert(DRE);
-  Checker->visitLambdaExpr(L, /* ignoreParamVarDecl */ 
true);
+  Checker->visitLambdaExpr(L,
+   /* ignoreParamVarDecl */ true);
 }
   }
 }
@@ -98,7 +99,8 @@ public:
   break;
 auto *Arg = CE->getArg(ArgIndex)->IgnoreParenCasts();
 if (!Param->hasAttr() && !TreatAllArgsAsNoEscape) {
-  if (auto *L = 
dyn_cast_or_null(Arg->IgnoreParenCasts()))
+  if (auto *L =
+  dyn_cast_or_null(Arg->IgnoreParenCasts()))
 Checker->visitLambdaExpr(L);
 }
 ++ArgIndex;
@@ -171,7 +173,8 @@ public:
   Os << "Implicitly captured ";
 }
 
-Os << "raw-pointer 'this' to ref-counted / CheckedPtr capable type is 
unsafe.";
+Os << "raw-pointer 'this' to ref-counted / CheckedPtr capable type is "
+  "unsafe.";
 
 PathDiagnosticLocation BSLoc(Capture.getLocation(), 
BR->getSourceManager());
 auto Report = std::make_unique(Bug, Os.str(), BSLoc);

``




https://github.com/llvm/llvm-project/pull/113845
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] RFC: [clang-tidy] [analyzer] Move nondeterministic pointer usage check to tidy (PR #110471)

2024-10-27 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

> I do plan to work on improvements

Great

> would like to get this baseline checker in for now as a "scope of work" for 
> this PR

Yep, what I meant as well

>  I don't mind documenting the improvement step
> Do you have suggestions on where to document improvements?

As suggested, simply do this in the docs. Because that documentation is 
user-facing, you can be very high-level and don't need to point out everything, 
IMO. E.g.: `This check currently does not check if a nondeterministic iteration 
order is likely to be a mistake, and instead marks all such iterations as 
bugprone.`

https://github.com/llvm/llvm-project/pull/110471
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] fb33af0 - [NVPTX] Remove nvvm.ldg.global.* intrinsics (#112834)

2024-10-27 Thread via cfe-commits

Author: Alex MacLean
Date: 2024-10-27T16:14:13-07:00
New Revision: fb33af08e4c105a05855f8beeb972d493410e72f

URL: 
https://github.com/llvm/llvm-project/commit/fb33af08e4c105a05855f8beeb972d493410e72f
DIFF: 
https://github.com/llvm/llvm-project/commit/fb33af08e4c105a05855f8beeb972d493410e72f.diff

LOG: [NVPTX] Remove nvvm.ldg.global.* intrinsics (#112834)

Remove these intrinsics which can be better represented by load
instructions with `!invariant.load` metadata:

- llvm.nvvm.ldg.global.i
- llvm.nvvm.ldg.global.f
- llvm.nvvm.ldg.global.p

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/builtins-nvptx-native-half-type-native.c
clang/test/CodeGen/builtins-nvptx-native-half-type.c
clang/test/CodeGen/builtins-nvptx.c
llvm/docs/ReleaseNotes.md
llvm/include/llvm/IR/IntrinsicsNVVM.td
llvm/lib/IR/AutoUpgrade.cpp
llvm/lib/Target/NVPTX/NVPTXISelDAGToDAG.cpp
llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
llvm/lib/Target/NVPTX/NVPTXISelLowering.h
llvm/test/Assembler/auto_upgrade_nvvm_intrinsics.ll

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index e2d03eff8ab4a0..911eec48bcb2fd 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -20492,8 +20492,8 @@ static NVPTXMmaInfo getNVPTXMmaInfo(unsigned BuiltinID) 
{
 #undef MMA_VARIANTS_B1_XOR
 }
 
-static Value *MakeLdgLdu(unsigned IntrinsicID, CodeGenFunction &CGF,
- const CallExpr *E) {
+static Value *MakeLdu(unsigned IntrinsicID, CodeGenFunction &CGF,
+  const CallExpr *E) {
   Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
   QualType ArgType = E->getArg(0)->getType();
   clang::CharUnits Align = CGF.CGM.getNaturalPointeeTypeAlignment(ArgType);
@@ -20503,6 +20503,21 @@ static Value *MakeLdgLdu(unsigned IntrinsicID, 
CodeGenFunction &CGF,
   {Ptr, ConstantInt::get(CGF.Builder.getInt32Ty(), Align.getQuantity())});
 }
 
+static Value *MakeLdg(CodeGenFunction &CGF, const CallExpr *E) {
+  Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
+  QualType ArgType = E->getArg(0)->getType();
+  clang::CharUnits AlignV = CGF.CGM.getNaturalPointeeTypeAlignment(ArgType);
+  llvm::Type *ElemTy = CGF.ConvertTypeForMem(ArgType->getPointeeType());
+
+  // Use addrspace(1) for NVPTX ADDRESS_SPACE_GLOBAL
+  auto *ASC = CGF.Builder.CreateAddrSpaceCast(Ptr, CGF.Builder.getPtrTy(1));
+  auto *LD = CGF.Builder.CreateAlignedLoad(ElemTy, ASC, AlignV.getAsAlign());
+  MDNode *MD = MDNode::get(CGF.Builder.getContext(), {});
+  LD->setMetadata(LLVMContext::MD_invariant_load, MD);
+
+  return LD;
+}
+
 static Value *MakeScopedAtomic(unsigned IntrinsicID, CodeGenFunction &CGF,
const CallExpr *E) {
   Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
@@ -20536,9 +20551,11 @@ static Value *MakeHalfType(unsigned IntrinsicID, 
unsigned BuiltinID,
 return nullptr;
   }
 
-  if (IntrinsicID == Intrinsic::nvvm_ldg_global_f ||
-  IntrinsicID == Intrinsic::nvvm_ldu_global_f)
-return MakeLdgLdu(IntrinsicID, CGF, E);
+  if (BuiltinID == NVPTX::BI__nvvm_ldg_h || BuiltinID == 
NVPTX::BI__nvvm_ldg_h2)
+return MakeLdg(CGF, E);
+
+  if (IntrinsicID == Intrinsic::nvvm_ldu_global_f)
+return MakeLdu(IntrinsicID, CGF, E);
 
   SmallVector Args;
   auto *F = CGF.CGM.getIntrinsic(IntrinsicID);
@@ -20675,16 +20692,15 @@ Value *CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned 
BuiltinID,
   case NVPTX::BI__nvvm_ldg_ul2:
   case NVPTX::BI__nvvm_ldg_ull:
   case NVPTX::BI__nvvm_ldg_ull2:
-// PTX Interoperability section 2.2: "For a vector with an even number of
-// elements, its alignment is set to number of elements times the alignment
-// of its member: n*alignof(t)."
-return MakeLdgLdu(Intrinsic::nvvm_ldg_global_i, *this, E);
   case NVPTX::BI__nvvm_ldg_f:
   case NVPTX::BI__nvvm_ldg_f2:
   case NVPTX::BI__nvvm_ldg_f4:
   case NVPTX::BI__nvvm_ldg_d:
   case NVPTX::BI__nvvm_ldg_d2:
-return MakeLdgLdu(Intrinsic::nvvm_ldg_global_f, *this, E);
+// PTX Interoperability section 2.2: "For a vector with an even number of
+// elements, its alignment is set to number of elements times the alignment
+// of its member: n*alignof(t)."
+return MakeLdg(*this, E);
 
   case NVPTX::BI__nvvm_ldu_c:
   case NVPTX::BI__nvvm_ldu_sc:
@@ -20715,13 +20731,13 @@ Value *CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned 
BuiltinID,
   case NVPTX::BI__nvvm_ldu_ul2:
   case NVPTX::BI__nvvm_ldu_ull:
   case NVPTX::BI__nvvm_ldu_ull2:
-return MakeLdgLdu(Intrinsic::nvvm_ldu_global_i, *this, E);
+return MakeLdu(Intrinsic::nvvm_ldu_global_i, *this, E);
   case NVPTX::BI__nvvm_ldu_f:
   case NVPTX::BI__nvvm_ldu_f2:
   case NVPTX::BI__nvvm_ldu_f4:
   case NVPTX::BI__nvvm_ldu_d:
   case NVPTX::BI__nvvm_ldu_d2:
-return MakeLdgLdu(Intrinsic::nvvm_ldu_global_f, *this, E);
+return MakeLdu(Intrin

[clang] [llvm] [NVPTX] Remove nvvm.ldg.global.* intrinsics (PR #112834)

2024-10-27 Thread Alex MacLean via cfe-commits

https://github.com/AlexMaclean closed 
https://github.com/llvm/llvm-project/pull/112834
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -1960,24 +1960,38 @@ class ExplicitSpecifier {
 class CXXDeductionGuideDecl : public FunctionDecl {
   void anchor() override;
 
+public:
+  enum class SourceKind {

antangelo wrote:

Done, renamed to `SourceDeductionGuideKind` to align with the class member and 
added a comment

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -10616,6 +10616,43 @@ bool clang::isBetterOverloadCandidate(
 auto *Guide1 = dyn_cast_or_null(Cand1.Function);
 auto *Guide2 = dyn_cast_or_null(Cand2.Function);
 if (Guide1 && Guide2) {
+  //  -- F1 and F2 are generated from class template argument deduction
+  //  for a class D, and F2 is generated from inheriting constructors
+  //  from a base class of D while F1 is not, ...
+  bool G1Inherited =
+  Guide1->getSourceDeductionGuide() &&
+  Guide1->getSourceKind() ==
+  CXXDeductionGuideDecl::SourceKind::InheritedConstructor;
+  bool G2Inherited =
+  Guide2->getSourceDeductionGuide() &&
+  Guide2->getSourceKind() ==
+  CXXDeductionGuideDecl::SourceKind::InheritedConstructor;
+  if (Guide1->isImplicit() && Guide2->isImplicit() &&
+  G1Inherited != G2Inherited) {
+const FunctionProtoType *FPT1 =
+Guide1->getType()->getAs();
+const FunctionProtoType *FPT2 =
+Guide2->getType()->getAs();
+assert(FPT1 && FPT2);
+
+// ... and for each explicit function argument, the parameters of F1 
and
+// F2 are either both ellipses or have the same type
+if (FPT1->isVariadic() == FPT2->isVariadic() &&
+FPT1->getNumParams() == FPT2->getNumParams()) {
+  const auto &P1 = FPT1->getParamTypes();
+  const auto &P2 = FPT2->getParamTypes();
+  bool ParamsHaveSameType = llvm::all_of(
+  llvm::zip(P1, P2),
+  [&](const std::tuple &pair) {

antangelo wrote:

Done

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -10616,6 +10616,43 @@ bool clang::isBetterOverloadCandidate(
 auto *Guide1 = dyn_cast_or_null(Cand1.Function);
 auto *Guide2 = dyn_cast_or_null(Cand2.Function);
 if (Guide1 && Guide2) {
+  //  -- F1 and F2 are generated from class template argument deduction
+  //  for a class D, and F2 is generated from inheriting constructors
+  //  from a base class of D while F1 is not, ...
+  bool G1Inherited =
+  Guide1->getSourceDeductionGuide() &&
+  Guide1->getSourceKind() ==
+  CXXDeductionGuideDecl::SourceKind::InheritedConstructor;
+  bool G2Inherited =
+  Guide2->getSourceDeductionGuide() &&
+  Guide2->getSourceKind() ==
+  CXXDeductionGuideDecl::SourceKind::InheritedConstructor;
+  if (Guide1->isImplicit() && Guide2->isImplicit() &&
+  G1Inherited != G2Inherited) {
+const FunctionProtoType *FPT1 =
+Guide1->getType()->getAs();
+const FunctionProtoType *FPT2 =
+Guide2->getType()->getAs();
+assert(FPT1 && FPT2);
+
+// ... and for each explicit function argument, the parameters of F1 
and
+// F2 are either both ellipses or have the same type
+if (FPT1->isVariadic() == FPT2->isVariadic() &&
+FPT1->getNumParams() == FPT2->getNumParams()) {
+  const auto &P1 = FPT1->getParamTypes();
+  const auto &P2 = FPT2->getParamTypes();
+  bool ParamsHaveSameType = llvm::all_of(
+  llvm::zip(P1, P2),

antangelo wrote:

I've updated this to use `all_of_zip`

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -11758,6 +11795,40 @@ static void DiagnoseBadDeduction(Sema &S, NamedDecl 
*Found, Decl *Templated,
   return;
 }
 
+// Errors in deduction guides from inherited constructors
+// will present as substitution failures in the mapping

antangelo wrote:

I've updated the comment. `Mapping` here refers to the partial specialization 
that maps the return type of the original deduction guide back to the derived 
class

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -11758,6 +11795,40 @@ static void DiagnoseBadDeduction(Sema &S, NamedDecl 
*Found, Decl *Templated,
   return;
 }
 
+// Errors in deduction guides from inherited constructors
+// will present as substitution failures in the mapping
+// partial specialization, so we show a generic diagnostic
+// in this case.
+if (auto *DG = dyn_cast(Templated);
+DG && DG->getSourceKind() ==
+  CXXDeductionGuideDecl::SourceKind::InheritedConstructor) {
+  CXXDeductionGuideDecl *Source = DG->getSourceDeductionGuide();
+  assert(Source &&
+ "Inherited constructor deduction guides must have a source");
+  QualType DeducedRecordType(
+  cast(DG->getDeducedTemplate())
+  ->getTemplatedDecl()
+  ->getTypeForDecl(),
+  0);
+  QualType InheritedRecordType(
+  cast(Source->getDeducedTemplate())
+  ->getTemplatedDecl()
+  ->getTypeForDecl(),
+  0);
+  S.Diag(Templated->getLocation(),
+ diag::note_ovl_candidate_inherited_constructor_deduction_failure)
+  << DeducedRecordType << InheritedRecordType << TemplateArgString;
+
+  CXXConstructorDecl *Ctor = DG->getCorrespondingConstructor();
+  if (Ctor && Ctor->getBeginLoc().isValid())

antangelo wrote:

I don't recall why I added that initially, I believe there was an example that 
triggered this but it no longer seems to be necessary and I can't think of 
conditions that would trigger it. I have removed that check accordingly.

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -899,7 +902,8 @@ Expr *buildIsDeducibleConstraint(Sema &SemaRef,
   return TypeTraitExpr::Create(
   Context, Context.getLogicalOperationType(), AliasTemplate->getLocation(),
   TypeTrait::BTT_IsDeducible, IsDeducibleTypeTraitArgs,
-  AliasTemplate->getLocation(), /*Value*/ false);
+  AliasTemplate->getLocation(),
+  /*Value*/ false);

antangelo wrote:

Done

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement P2582R1: CTAD from inherited constructors (PR #98788)

2024-10-27 Thread via cfe-commits


@@ -931,12 +935,73 @@ getRHSTemplateDeclAndArgs(Sema &SemaRef, 
TypeAliasTemplateDecl *AliasTemplate) {
   return {Template, AliasRhsTemplateArgs};
 }
 
+struct InheritedConstructorDeductionInfo {
+  // Class template for which we are declaring deduction guides
+  // This is `C` in the standard wording
+  TemplateDecl *DerivedClassTemplate;
+
+  // `template CC` in the standard wording
+  // This is the type of template that is substituted in the deduction guide
+  // return type `CC`
+  TypeSourceInfo *CCType;
+};
+
+// Build the type for a deduction guide generated from an inherited constructor
+// [over.match.class.deduct]p1.10:

antangelo wrote:

Done

https://github.com/llvm/llvm-project/pull/98788
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Tooling/Inclusion] Add binary search related `std::ranges` symbols to the mapping. (PR #113796)

2024-10-27 Thread via cfe-commits

https://github.com/c8ef edited https://github.com/llvm/llvm-project/pull/113796
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][TableGen] Use StringRef in FlattenedSpelling (PR #113809)

2024-10-27 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul updated 
https://github.com/llvm/llvm-project/pull/113809

>From 5fd76fe7a8fe6a009966cf0d7d67a53b68b601a1 Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Sun, 27 Oct 2024 06:51:55 -0700
Subject: [PATCH] [Clang][TableGen] Use StringRef in FlattenedSpelling

Change FlattenedSpelling to use StringRef instead of std::String.
---
 clang/utils/TableGen/ClangAttrEmitter.cpp | 244 ++
 1 file changed, 109 insertions(+), 135 deletions(-)

diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 4890d249c6d8f7..296c47c86b779d 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -49,41 +49,39 @@ using namespace llvm;
 namespace {
 
 class FlattenedSpelling {
-  std::string V, N, NS;
+  StringRef V, N, NS;
   bool K = false;
   const Record &OriginalSpelling;
 
 public:
-  FlattenedSpelling(const std::string &Variety, const std::string &Name,
-const std::string &Namespace, bool KnownToGCC,
-const Record &OriginalSpelling)
+  FlattenedSpelling(StringRef Variety, StringRef Name, StringRef Namespace,
+bool KnownToGCC, const Record &OriginalSpelling)
   : V(Variety), N(Name), NS(Namespace), K(KnownToGCC),
 OriginalSpelling(OriginalSpelling) {}
   explicit FlattenedSpelling(const Record &Spelling)
-  : V(std::string(Spelling.getValueAsString("Variety"))),
-N(std::string(Spelling.getValueAsString("Name"))),
-OriginalSpelling(Spelling) {
+  : V(Spelling.getValueAsString("Variety")),
+N(Spelling.getValueAsString("Name")), OriginalSpelling(Spelling) {
 assert(V != "GCC" && V != "Clang" &&
"Given a GCC spelling, which means this hasn't been flattened!");
 if (V == "CXX11" || V == "C23" || V == "Pragma")
-  NS = std::string(Spelling.getValueAsString("Namespace"));
+  NS = Spelling.getValueAsString("Namespace");
   }
 
-  const std::string &variety() const { return V; }
-  const std::string &name() const { return N; }
-  const std::string &nameSpace() const { return NS; }
+  StringRef variety() const { return V; }
+  StringRef name() const { return N; }
+  StringRef nameSpace() const { return NS; }
   bool knownToGCC() const { return K; }
   const Record &getSpellingRecord() const { return OriginalSpelling; }
 };
 
 struct FlattenedSpellingInfo {
-  FlattenedSpellingInfo(std::string Syntax, std::string Scope,
-std::string TargetTest, uint32_t ArgMask)
+  FlattenedSpellingInfo(StringRef Syntax, StringRef Scope, StringRef 
TargetTest,
+uint32_t ArgMask)
   : Syntax(Syntax), Scope(Scope), TargetTest(TargetTest), ArgMask(ArgMask) 
{
   }
-  std::string Syntax;
-  std::string Scope;
-  std::string TargetTest;
+  StringRef Syntax;
+  StringRef Scope;
+  StringRef TargetTest;
   uint32_t ArgMask;
 };
 using FSIVecTy = std::vector;
@@ -105,17 +103,18 @@ GetFlattenedSpellings(const Record &Attr) {
 StringRef Variety = Spelling->getValueAsString("Variety");
 StringRef Name = Spelling->getValueAsString("Name");
 if (Variety == "GCC") {
-  Ret.emplace_back("GNU", std::string(Name), "", true, *Spelling);
-  Ret.emplace_back("CXX11", std::string(Name), "gnu", true, *Spelling);
+  Ret.emplace_back("GNU", Name, "", true, *Spelling);
+  Ret.emplace_back("CXX11", Name, "gnu", true, *Spelling);
   if (Spelling->getValueAsBit("AllowInC"))
-Ret.emplace_back("C23", std::string(Name), "gnu", true, *Spelling);
+Ret.emplace_back("C23", Name, "gnu", true, *Spelling);
 } else if (Variety == "Clang") {
-  Ret.emplace_back("GNU", std::string(Name), "", false, *Spelling);
-  Ret.emplace_back("CXX11", std::string(Name), "clang", false, *Spelling);
+  Ret.emplace_back("GNU", Name, "", false, *Spelling);
+  Ret.emplace_back("CXX11", Name, "clang", false, *Spelling);
   if (Spelling->getValueAsBit("AllowInC"))
-Ret.emplace_back("C23", std::string(Name), "clang", false, *Spelling);
-} else
+Ret.emplace_back("C23", Name, "clang", false, *Spelling);
+} else {
   Ret.push_back(FlattenedSpelling(*Spelling));
+}
   }
 
   return Ret;
@@ -1554,7 +1553,7 @@ static void writeAvailabilityValue(raw_ostream &OS) {
  << "  OS << \"";
 }
 
-static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
+static void writeDeprecatedAttrValue(raw_ostream &OS, StringRef Variety) {
   OS << "\\\"\" << getMessage() << \"\\\"\";\n";
   // Only GNU deprecated has an optional fixit argument at the second position.
   if (Variety == "GNU")
@@ -1577,9 +1576,12 @@ static void writeGetSpellingFunction(const Record &R, 
raw_ostream &OS) {
 "llvm_unreachable(\"Unknown attribute spelling!\");\n"
 "return \"(No spelling)\";\n";
 
-  for (unsigned I = 0; I < Spellings.size(); ++I)
-OS << "  case " << I << ":\n"
- 

[clang] [Clang][TableGen] Use StringRef in FlattenedSpelling (PR #113809)

2024-10-27 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul updated 
https://github.com/llvm/llvm-project/pull/113809

>From 60da18c88e63612c791ccbb423d752bac311650b Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Sun, 27 Oct 2024 06:51:55 -0700
Subject: [PATCH] [Clang][TableGen] Use StringRef in FlattenedSpelling

Change FlattenedSpelling to use StringRef instead of std::String.
---
 clang/utils/TableGen/ClangAttrEmitter.cpp | 244 ++
 1 file changed, 109 insertions(+), 135 deletions(-)

diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 4890d249c6d8f7..65f9cef9e1695c 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -49,41 +49,39 @@ using namespace llvm;
 namespace {
 
 class FlattenedSpelling {
-  std::string V, N, NS;
+  StringRef V, N, NS;
   bool K = false;
   const Record &OriginalSpelling;
 
 public:
-  FlattenedSpelling(const std::string &Variety, const std::string &Name,
-const std::string &Namespace, bool KnownToGCC,
-const Record &OriginalSpelling)
+  FlattenedSpelling(StringRef Variety, StringRef Name, StringRef Namespace,
+bool KnownToGCC, const Record &OriginalSpelling)
   : V(Variety), N(Name), NS(Namespace), K(KnownToGCC),
 OriginalSpelling(OriginalSpelling) {}
   explicit FlattenedSpelling(const Record &Spelling)
-  : V(std::string(Spelling.getValueAsString("Variety"))),
-N(std::string(Spelling.getValueAsString("Name"))),
-OriginalSpelling(Spelling) {
+  : V(Spelling.getValueAsString("Variety")),
+N(Spelling.getValueAsString("Name")), OriginalSpelling(Spelling) {
 assert(V != "GCC" && V != "Clang" &&
"Given a GCC spelling, which means this hasn't been flattened!");
 if (V == "CXX11" || V == "C23" || V == "Pragma")
-  NS = std::string(Spelling.getValueAsString("Namespace"));
+  NS = Spelling.getValueAsString("Namespace");
   }
 
-  const std::string &variety() const { return V; }
-  const std::string &name() const { return N; }
-  const std::string &nameSpace() const { return NS; }
+  StringRef variety() const { return V; }
+  StringRef name() const { return N; }
+  StringRef nameSpace() const { return NS; }
   bool knownToGCC() const { return K; }
   const Record &getSpellingRecord() const { return OriginalSpelling; }
 };
 
 struct FlattenedSpellingInfo {
-  FlattenedSpellingInfo(std::string Syntax, std::string Scope,
-std::string TargetTest, uint32_t ArgMask)
+  FlattenedSpellingInfo(StringRef Syntax, StringRef Scope, StringRef 
TargetTest,
+uint32_t ArgMask)
   : Syntax(Syntax), Scope(Scope), TargetTest(TargetTest), ArgMask(ArgMask) 
{
   }
-  std::string Syntax;
-  std::string Scope;
-  std::string TargetTest;
+  StringRef Syntax;
+  StringRef Scope;
+  StringRef TargetTest;
   uint32_t ArgMask;
 };
 using FSIVecTy = std::vector;
@@ -105,17 +103,18 @@ GetFlattenedSpellings(const Record &Attr) {
 StringRef Variety = Spelling->getValueAsString("Variety");
 StringRef Name = Spelling->getValueAsString("Name");
 if (Variety == "GCC") {
-  Ret.emplace_back("GNU", std::string(Name), "", true, *Spelling);
-  Ret.emplace_back("CXX11", std::string(Name), "gnu", true, *Spelling);
+  Ret.emplace_back("GNU", Name, "", true, *Spelling);
+  Ret.emplace_back("CXX11", Name, "gnu", true, *Spelling);
   if (Spelling->getValueAsBit("AllowInC"))
-Ret.emplace_back("C23", std::string(Name), "gnu", true, *Spelling);
+Ret.emplace_back("C23", Name, "gnu", true, *Spelling);
 } else if (Variety == "Clang") {
-  Ret.emplace_back("GNU", std::string(Name), "", false, *Spelling);
-  Ret.emplace_back("CXX11", std::string(Name), "clang", false, *Spelling);
+  Ret.emplace_back("GNU", Name, "", false, *Spelling);
+  Ret.emplace_back("CXX11", Name, "clang", false, *Spelling);
   if (Spelling->getValueAsBit("AllowInC"))
-Ret.emplace_back("C23", std::string(Name), "clang", false, *Spelling);
-} else
+Ret.emplace_back("C23", Name, "clang", false, *Spelling);
+} else {
   Ret.push_back(FlattenedSpelling(*Spelling));
+}
   }
 
   return Ret;
@@ -1554,7 +1553,7 @@ static void writeAvailabilityValue(raw_ostream &OS) {
  << "  OS << \"";
 }
 
-static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
+static void writeDeprecatedAttrValue(raw_ostream &OS, StringRef Variety) {
   OS << "\\\"\" << getMessage() << \"\\\"\";\n";
   // Only GNU deprecated has an optional fixit argument at the second position.
   if (Variety == "GNU")
@@ -1577,9 +1576,12 @@ static void writeGetSpellingFunction(const Record &R, 
raw_ostream &OS) {
 "llvm_unreachable(\"Unknown attribute spelling!\");\n"
 "return \"(No spelling)\";\n";
 
-  for (unsigned I = 0; I < Spellings.size(); ++I)
-OS << "  case " << I << ":\n"
- 

[clang] [Clang][TableGen] Use StringRef in FlattenedSpelling (PR #113809)

2024-10-27 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul updated 
https://github.com/llvm/llvm-project/pull/113809

>From 6b128746e5f6bfa13e0ea9a900f0bc8529437717 Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Sun, 27 Oct 2024 06:51:55 -0700
Subject: [PATCH] [Clang][TableGen] Use StringRef in FlattenedSpelling

Change FlattenedSpelling to use StringRef instead of std::String.
---
 clang/utils/TableGen/ClangAttrEmitter.cpp | 245 ++
 1 file changed, 109 insertions(+), 136 deletions(-)

diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 4890d249c6d8f7..cf9c70a93e5db2 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -49,40 +49,38 @@ using namespace llvm;
 namespace {
 
 class FlattenedSpelling {
-  std::string V, N, NS;
+  StringRef V, N, NS;
   bool K = false;
   const Record &OriginalSpelling;
 
 public:
-  FlattenedSpelling(const std::string &Variety, const std::string &Name,
-const std::string &Namespace, bool KnownToGCC,
-const Record &OriginalSpelling)
+  FlattenedSpelling(StringRef Variety, StringRef Name, StringRef Namespace,
+bool KnownToGCC, const Record &OriginalSpelling)
   : V(Variety), N(Name), NS(Namespace), K(KnownToGCC),
 OriginalSpelling(OriginalSpelling) {}
   explicit FlattenedSpelling(const Record &Spelling)
-  : V(std::string(Spelling.getValueAsString("Variety"))),
-N(std::string(Spelling.getValueAsString("Name"))),
-OriginalSpelling(Spelling) {
+  : V(Spelling.getValueAsString("Variety")),
+N(Spelling.getValueAsString("Name")), OriginalSpelling(Spelling) {
 assert(V != "GCC" && V != "Clang" &&
"Given a GCC spelling, which means this hasn't been flattened!");
 if (V == "CXX11" || V == "C23" || V == "Pragma")
-  NS = std::string(Spelling.getValueAsString("Namespace"));
+  NS = Spelling.getValueAsString("Namespace");
   }
 
-  const std::string &variety() const { return V; }
-  const std::string &name() const { return N; }
-  const std::string &nameSpace() const { return NS; }
+  StringRef variety() const { return V; }
+  StringRef name() const { return N; }
+  StringRef nameSpace() const { return NS; }
   bool knownToGCC() const { return K; }
   const Record &getSpellingRecord() const { return OriginalSpelling; }
 };
 
 struct FlattenedSpellingInfo {
-  FlattenedSpellingInfo(std::string Syntax, std::string Scope,
-std::string TargetTest, uint32_t ArgMask)
+  FlattenedSpellingInfo(StringRef Syntax, StringRef Scope,
+const std::string &TargetTest, uint32_t ArgMask)
   : Syntax(Syntax), Scope(Scope), TargetTest(TargetTest), ArgMask(ArgMask) 
{
   }
-  std::string Syntax;
-  std::string Scope;
+  StringRef Syntax;
+  StringRef Scope;
   std::string TargetTest;
   uint32_t ArgMask;
 };
@@ -105,17 +103,18 @@ GetFlattenedSpellings(const Record &Attr) {
 StringRef Variety = Spelling->getValueAsString("Variety");
 StringRef Name = Spelling->getValueAsString("Name");
 if (Variety == "GCC") {
-  Ret.emplace_back("GNU", std::string(Name), "", true, *Spelling);
-  Ret.emplace_back("CXX11", std::string(Name), "gnu", true, *Spelling);
+  Ret.emplace_back("GNU", Name, "", true, *Spelling);
+  Ret.emplace_back("CXX11", Name, "gnu", true, *Spelling);
   if (Spelling->getValueAsBit("AllowInC"))
-Ret.emplace_back("C23", std::string(Name), "gnu", true, *Spelling);
+Ret.emplace_back("C23", Name, "gnu", true, *Spelling);
 } else if (Variety == "Clang") {
-  Ret.emplace_back("GNU", std::string(Name), "", false, *Spelling);
-  Ret.emplace_back("CXX11", std::string(Name), "clang", false, *Spelling);
+  Ret.emplace_back("GNU", Name, "", false, *Spelling);
+  Ret.emplace_back("CXX11", Name, "clang", false, *Spelling);
   if (Spelling->getValueAsBit("AllowInC"))
-Ret.emplace_back("C23", std::string(Name), "clang", false, *Spelling);
-} else
+Ret.emplace_back("C23", Name, "clang", false, *Spelling);
+} else {
   Ret.push_back(FlattenedSpelling(*Spelling));
+}
   }
 
   return Ret;
@@ -1554,7 +1553,7 @@ static void writeAvailabilityValue(raw_ostream &OS) {
  << "  OS << \"";
 }
 
-static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
+static void writeDeprecatedAttrValue(raw_ostream &OS, StringRef Variety) {
   OS << "\\\"\" << getMessage() << \"\\\"\";\n";
   // Only GNU deprecated has an optional fixit argument at the second position.
   if (Variety == "GNU")
@@ -1577,9 +1576,12 @@ static void writeGetSpellingFunction(const Record &R, 
raw_ostream &OS) {
 "llvm_unreachable(\"Unknown attribute spelling!\");\n"
 "return \"(No spelling)\";\n";
 
-  for (unsigned I = 0; I < Spellings.size(); ++I)
-OS << "  case " << I << ":\n"
-  "return \"" << Spellings[I].name() << "

[clang] 5aa1275 - [X86] Support SM4 EVEX version intrinsics/instructions. (#113402)

2024-10-27 Thread via cfe-commits

Author: Freddy Ye
Date: 2024-10-28T10:46:16+08:00
New Revision: 5aa1275d03b679f45f47f29f206292f663afed83

URL: 
https://github.com/llvm/llvm-project/commit/5aa1275d03b679f45f47f29f206292f663afed83
DIFF: 
https://github.com/llvm/llvm-project/commit/5aa1275d03b679f45f47f29f206292f663afed83.diff

LOG: [X86] Support SM4 EVEX version intrinsics/instructions. (#113402)

Ref.: https://cdrdv2.intel.com/v1/dl/getContent/671368

Added: 
clang/lib/Headers/sm4evexintrin.h
clang/test/CodeGen/X86/sm4-evex-builtins.c
llvm/test/CodeGen/X86/sm4-evex-intrinsics.ll
llvm/test/MC/Disassembler/X86/sm4-evex-32.txt
llvm/test/MC/Disassembler/X86/sm4-evex-64.txt
llvm/test/MC/X86/sm4-evex-32-att.s
llvm/test/MC/X86/sm4-evex-32-intel.s
llvm/test/MC/X86/sm4-evex-64-att.s
llvm/test/MC/X86/sm4-evex-64-intel.s

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/BuiltinsX86.def
clang/lib/Headers/CMakeLists.txt
clang/lib/Headers/immintrin.h
llvm/docs/ReleaseNotes.md
llvm/include/llvm/IR/IntrinsicsX86.td
llvm/lib/Target/X86/X86InstrAVX10.td
llvm/test/TableGen/x86-fold-tables.inc

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6a95337815174b..31ee4f7e516fed 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -628,6 +628,10 @@ X86 Support
   * Supported MINMAX intrinsics of ``*_(mask(z)))_minmax(ne)_p[s|d|h|bh]`` and
   ``*_(mask(z)))_minmax_s[s|d|h]``.
 
+- Supported intrinsics for ``SM4 and AVX10.2``.
+  * Supported SM4 intrinsics of ``_mm512_sm4key4_epi32`` and
+  ``_mm512_sm4rnds4_epi32``.
+
 - All intrinsics in adcintrin.h can now be used in constant expressions.
 
 - All intrinsics in adxintrin.h can now be used in constant expressions.

diff  --git a/clang/include/clang/Basic/BuiltinsX86.def 
b/clang/include/clang/Basic/BuiltinsX86.def
index 4c6b22cca421ca..4486eb73a11fa6 100644
--- a/clang/include/clang/Basic/BuiltinsX86.def
+++ b/clang/include/clang/Basic/BuiltinsX86.def
@@ -2179,6 +2179,10 @@ TARGET_BUILTIN(__builtin_ia32_vsm4key4256, 
"V8UiV8UiV8Ui", "nV:256:", "sm4")
 TARGET_BUILTIN(__builtin_ia32_vsm4rnds4128, "V4UiV4UiV4Ui", "nV:128:", "sm4")
 TARGET_BUILTIN(__builtin_ia32_vsm4rnds4256, "V8UiV8UiV8Ui", "nV:256:", "sm4")
 
+// SM4_EVEX
+TARGET_BUILTIN(__builtin_ia32_vsm4key4512, "V16UiV16UiV16Ui", "nV:512:", 
"avx10.2-512,sm4")
+TARGET_BUILTIN(__builtin_ia32_vsm4rnds4512, "V16UiV16UiV16Ui", "nV:512:", 
"avx10.2-512,sm4")
+
 // AVX10 MINMAX
 TARGET_BUILTIN(__builtin_ia32_vminmaxnepbf16128, "V8yV8yV8yIi", "nV:128:", 
"avx10.2-256")
 TARGET_BUILTIN(__builtin_ia32_vminmaxnepbf16256, "V16yV16yV16yIi", "nV:256:", 
"avx10.2-256")

diff  --git a/clang/lib/Headers/CMakeLists.txt 
b/clang/lib/Headers/CMakeLists.txt
index e97953d87a2ff9..0211d1870b30a0 100644
--- a/clang/lib/Headers/CMakeLists.txt
+++ b/clang/lib/Headers/CMakeLists.txt
@@ -243,6 +243,7 @@ set(x86_files
   shaintrin.h
   sm3intrin.h
   sm4intrin.h
+  sm4evexintrin.h
   smmintrin.h
   tbmintrin.h
   tmmintrin.h

diff  --git a/clang/lib/Headers/immintrin.h b/clang/lib/Headers/immintrin.h
index 5f296d0a3324d0..65ad72bc479f49 100644
--- a/clang/lib/Headers/immintrin.h
+++ b/clang/lib/Headers/immintrin.h
@@ -677,6 +677,11 @@ _storebe_i64(void * __P, long long __D) {
 #include 
 #endif
 
+#if !defined(__SCE__) || __has_feature(modules) || 
\
+(defined(__AVX10_2_512__) && defined(__SM4__))
+#include 
+#endif
+
 #if !defined(__SCE__) || __has_feature(modules) || defined(__ENQCMD__)
 #include 
 #endif

diff  --git a/clang/lib/Headers/sm4evexintrin.h 
b/clang/lib/Headers/sm4evexintrin.h
new file mode 100644
index 00..f6ae0037baea03
--- /dev/null
+++ b/clang/lib/Headers/sm4evexintrin.h
@@ -0,0 +1,32 @@
+/*===--- sm4evexintrin.h - SM4 EVEX intrinsics -===
+ *
+ * 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 __IMMINTRIN_H
+#error "Never use  directly; include  instead."
+#endif // __IMMINTRIN_H
+
+#ifndef __SM4EVEXINTRIN_H
+#define __SM4EVEXINTRIN_H
+
+#define __DEFAULT_FN_ATTRS512  
\
+  __attribute__((__always_inline__, __nodebug__,   
\
+ __target__("sm4,avx10.2-512"), __min_vector_width__(512)))
+
+static __inline__ __m512i __DEFAULT_FN_ATTRS512
+_mm512_sm4key4_epi32(__m512i __A, __m512i __B) {
+  return (__m512i)__builtin_ia32_vsm4key4512((__v16su)__A, (__v16su)__B);
+}
+
+static __inline__ __m512i __DEFAULT_FN_ATTRS512
+_mm512_sm4rnds4_epi32(__m512i __A, __m512i __B) {
+  return (__m512i)__builtin_ia32_vsm4rnds4512((__v16su)__A, (__v16su)_

  1   2   >