[clang] Add option -fstdlib-hardening= (PR #78763)

2024-01-19 Thread Akira Hatanaka via cfe-commits

https://github.com/ahatanak created 
https://github.com/llvm/llvm-project/pull/78763

The option allows users to enable libc++ hardening, which was discussed in the 
following RFC:

https://discourse.llvm.org/t/rfc-hardening-in-libc/73925

Users specifiy the hardening mode by passing one of the following values as the 
argument to the option: none, fast, extensive, or debug.

When the option is used, clang defines a macro for each of the hardening modes 
(_LIBCPP_HARDENING_MODE_{NONE,FAST,EXTENSIVE,DEBUG}) and sets macro 
_LIBCPP_HARDENING_MODE_ based on the hardening mode the user chose.

It's an error to use the option if the stdlib used isn't libc++ or clang isn't 
compiling in C++ mode.

>From 0d68286bd8b7206c5045062f65ccaf1c3fb54714 Mon Sep 17 00:00:00 2001
From: Akira Hatanaka 
Date: Thu, 18 Jan 2024 16:20:41 -0800
Subject: [PATCH] Add option -fstdlib-hardening=

The option allows users to enable libc++ hardening, which was discussed
in the following RFC:

https://discourse.llvm.org/t/rfc-hardening-in-libc/73925

Users specifiy the hardening mode by passing one of the following values
as the argument to the option: none, fast, extensive, or debug.

When the option is used, clang defines a macro for each of the hardening
modes (_LIBCPP_HARDENING_MODE_{NONE,FAST,EXTENSIVE,DEBUG}) and sets
macro _LIBCPP_HARDENING_MODE_ based on the hardening mode the user
chose.

It's an error to use the option if the stdlib used isn't libc++ or
clang isn't compiling in C++ mode.
---
 .../clang/Basic/DiagnosticDriverKinds.td  |  2 ++
 clang/include/clang/Basic/LangOptions.def |  1 +
 clang/include/clang/Basic/LangOptions.h   |  8 ++
 clang/include/clang/Driver/Options.td |  8 ++
 clang/lib/Driver/ToolChains/Clang.cpp |  8 ++
 clang/lib/Frontend/InitPreprocessor.cpp   | 27 +++
 clang/test/Driver/libcxx-hardening.cpp| 21 +++
 7 files changed, 75 insertions(+)
 create mode 100644 clang/test/Driver/libcxx-hardening.cpp

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 090b169a0e72408..2369ddc8a80ead3 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -275,6 +275,8 @@ def warn_drv_unknown_argument_clang_cl_with_suggestion : 
Warning<
   InGroup;
 def err_drv_unknown_target_triple : Error<"unknown target triple '%0'">;
 
+def err_drv_stdlib_hardening_unavailable : Error<"libc++ hardening is 
available only when libc++ is used">;
+
 def warn_drv_ycyu_different_arg_clang_cl : Warning<
   "support for '/Yc' and '/Yu' with different filenames not implemented yet; 
flags ignored">,
   InGroup;
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 04ebffbcba69dbf..0db8ff04ad0d52d 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -281,6 +281,7 @@ LANGOPT(OffloadingNewDriver, 1, 0, "use the new driver for 
generating offloading
 LANGOPT(SYCLIsDevice  , 1, 0, "Generate code for SYCL device")
 LANGOPT(SYCLIsHost, 1, 0, "SYCL host compilation")
 ENUM_LANGOPT(SYCLVersion  , SYCLMajorVersion, 2, SYCL_None, "Version of the 
SYCL standard used")
+ENUM_LANGOPT(LibcxxHardeningMode, LibcxxHardeningModeKind, 3, 
LIBCPP_HARDENING_MODE_NOT_SPECIFIED, "libc++ harderning mode")
 
 LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching API for HIP")
 LANGOPT(OffloadUniformBlock, 1, 0, "Assume that kernels are launched with 
uniform block sizes (default true for CUDA/HIP and false otherwise)")
diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 9f986fce2d44188..62e70a5cffafd61 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -174,6 +174,14 @@ class LangOptions : public LangOptionsBase {
 HLSL_202x = 2029,
   };
 
+  enum LibcxxHardeningModeKind {
+LIBCPP_HARDENING_MODE_NOT_SPECIFIED,
+LIBCPP_HARDENING_MODE_NONE,
+LIBCPP_HARDENING_MODE_FAST,
+LIBCPP_HARDENING_MODE_EXTENSIVE,
+LIBCPP_HARDENING_MODE_DEBUG
+  };
+
   /// Clang versions with different platform ABI conformance.
   enum class ClangABI {
 /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d2e6c3ff721c27e..7ce38f88d156441 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -7730,6 +7730,14 @@ def source_date_epoch : Separate<["-"], 
"source-date-epoch">,
 
 } // let Visibility = [CC1Option]
 
+def stdlib_hardening_EQ : Joined<["-"], "fstdlib-hardening=">,
+  Values<"none,fast,extensive,debug">,
+  NormalizedValues<["LIBCPP_HARDENING_MODE_NONE", 
"LIBCPP_HARDENING_MODE_FAST", "LIBCPP_HARDENING_MODE_EXTENSIVE", 
"LIBCPP_HARDENING_MODE_DEBUG"]>,
+  Visibility<[C

[clang] Add option -fstdlib-hardening= (PR #78763)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Akira Hatanaka (ahatanak)


Changes

The option allows users to enable libc++ hardening, which was discussed in the 
following RFC:

https://discourse.llvm.org/t/rfc-hardening-in-libc/73925

Users specifiy the hardening mode by passing one of the following values as the 
argument to the option: none, fast, extensive, or debug.

When the option is used, clang defines a macro for each of the hardening modes 
(_LIBCPP_HARDENING_MODE_{NONE,FAST,EXTENSIVE,DEBUG}) and sets macro 
_LIBCPP_HARDENING_MODE_ based on the hardening mode the user chose.

It's an error to use the option if the stdlib used isn't libc++ or clang isn't 
compiling in C++ mode.

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


7 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+2) 
- (modified) clang/include/clang/Basic/LangOptions.def (+1) 
- (modified) clang/include/clang/Basic/LangOptions.h (+8) 
- (modified) clang/include/clang/Driver/Options.td (+8) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+8) 
- (modified) clang/lib/Frontend/InitPreprocessor.cpp (+27) 
- (added) clang/test/Driver/libcxx-hardening.cpp (+21) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 090b169a0e72408..2369ddc8a80ead3 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -275,6 +275,8 @@ def warn_drv_unknown_argument_clang_cl_with_suggestion : 
Warning<
   InGroup;
 def err_drv_unknown_target_triple : Error<"unknown target triple '%0'">;
 
+def err_drv_stdlib_hardening_unavailable : Error<"libc++ hardening is 
available only when libc++ is used">;
+
 def warn_drv_ycyu_different_arg_clang_cl : Warning<
   "support for '/Yc' and '/Yu' with different filenames not implemented yet; 
flags ignored">,
   InGroup;
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 04ebffbcba69dbf..0db8ff04ad0d52d 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -281,6 +281,7 @@ LANGOPT(OffloadingNewDriver, 1, 0, "use the new driver for 
generating offloading
 LANGOPT(SYCLIsDevice  , 1, 0, "Generate code for SYCL device")
 LANGOPT(SYCLIsHost, 1, 0, "SYCL host compilation")
 ENUM_LANGOPT(SYCLVersion  , SYCLMajorVersion, 2, SYCL_None, "Version of the 
SYCL standard used")
+ENUM_LANGOPT(LibcxxHardeningMode, LibcxxHardeningModeKind, 3, 
LIBCPP_HARDENING_MODE_NOT_SPECIFIED, "libc++ harderning mode")
 
 LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching API for HIP")
 LANGOPT(OffloadUniformBlock, 1, 0, "Assume that kernels are launched with 
uniform block sizes (default true for CUDA/HIP and false otherwise)")
diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 9f986fce2d44188..62e70a5cffafd61 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -174,6 +174,14 @@ class LangOptions : public LangOptionsBase {
 HLSL_202x = 2029,
   };
 
+  enum LibcxxHardeningModeKind {
+LIBCPP_HARDENING_MODE_NOT_SPECIFIED,
+LIBCPP_HARDENING_MODE_NONE,
+LIBCPP_HARDENING_MODE_FAST,
+LIBCPP_HARDENING_MODE_EXTENSIVE,
+LIBCPP_HARDENING_MODE_DEBUG
+  };
+
   /// Clang versions with different platform ABI conformance.
   enum class ClangABI {
 /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d2e6c3ff721c27e..7ce38f88d156441 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -7730,6 +7730,14 @@ def source_date_epoch : Separate<["-"], 
"source-date-epoch">,
 
 } // let Visibility = [CC1Option]
 
+def stdlib_hardening_EQ : Joined<["-"], "fstdlib-hardening=">,
+  Values<"none,fast,extensive,debug">,
+  NormalizedValues<["LIBCPP_HARDENING_MODE_NONE", 
"LIBCPP_HARDENING_MODE_FAST", "LIBCPP_HARDENING_MODE_EXTENSIVE", 
"LIBCPP_HARDENING_MODE_DEBUG"]>,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"libc++ hardening mode">,
+  NormalizedValuesScope<"LangOptions">,
+  MarshallingInfoEnum, 
"LIBCPP_HARDENING_MODE_NOT_SPECIFIED">;
+
 
//===--===//
 // CUDA Options
 
//===--===//
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index fead2e884030e21..560793958455ced 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1256,6 +1256,14 @@ void Clang::AddPreprocessingOptions(Compilation &C, 
const JobAction &JA,
   if (Arg *A = Args.getLastArg(options::OPT_I_))
 D.Diag(diag::err_drv_I_dash_not_supported) <

[clang] [Clang][Sema] fix outline member function template with default align crash (PR #78400)

2024-01-19 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/78400

>From c3856543fd56ec33bab6bcdcd3d833c0e19f58f9 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 17 Jan 2024 14:16:34 +0800
Subject: [PATCH] fix

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp | 12 ++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index fc80515b45e35b4..262fe71545a2a61 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -3064,10 +3064,18 @@ bool Sema::SubstDefaultArgument(
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
 }
+auto NewTemplateArgs = TemplateArgs;
+if (FD->isOutOfLine()) {
+  auto *CurrentTemplateArgumentList = TemplateArgumentList::CreateCopy(
+  getASTContext(), TemplateArgs.getInnermost());
+  NewTemplateArgs = getTemplateInstantiationArgs(
+  FD, FD->getDeclContext(), true, CurrentTemplateArgumentList, true,
+  nullptr, false, false);
+}
 
 runWithSufficientStackSpace(Loc, [&] {
-  Result = SubstInitializer(PatternExpr, TemplateArgs,
-/*DirectInit*/false);
+  Result = SubstInitializer(PatternExpr, NewTemplateArgs,
+/*DirectInit*/ false);
 });
   }
   if (Result.isInvalid())

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


[clang] [clang-repl] Add a interpreter-specific overload of operator new for C++ (PR #76218)

2024-01-19 Thread Vassil Vassilev via cfe-commits

vgvassilev wrote:

@vitalybuka, thank you!

I am trying to add a fix but I get `unsupported option '-fsanitize=hwaddress' 
for target 'x86_64-apple-darwin21.6.0'`. If you have a compatible platform, do 
you mind testing:

```diff
diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp 
b/clang/unittests/Interpreter/InterpreterTest.cpp
index d6eb0684ba49..406a4871dff5 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -34,12 +34,6 @@ using namespace clang;
 #define CLANG_INTERPRETER_NO_SUPPORT_EXEC
 #endif
 
-#if LLVM_ADDRESS_SANITIZER_BUILD || LLVM_HWADDRESS_SANITIZER_BUILD
-#include 
-#else
-extern "C" void __lsan_ignore_object(const void *p) {}
-#endif
-
 int Global = 42;
 // JIT reports symbol not found on Windows without the visibility attribute.
 REPL_EXTERNAL_VISIBILITY int getGlobal() { return Global; }
@@ -317,8 +311,9 @@ TEST(IncrementalProcessing, InstantiateTemplate) {
   auto fn =
   cantFail(Interp->getSymbolAddress(MangledName)).toPtr();
   EXPECT_EQ(42, fn(NewA.getPtr()));
-  // FIXME: release the memory.
-  __lsan_ignore_object(NewA.getPtr());
+  // FIXME: Consider providing an option in clang::Value to take ownership of
+  // the memory created from the interpreter.
+  free(NewA.getPtr());
 }
 
 #ifdef CLANG_INTERPRETER_NO_SUPPORT_EXEC
```

I think that's going to work.

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


[clang] Reland "[clang] Fix CTAD for aggregates for nested template classes" (PR #78670)

2024-01-19 Thread via cfe-commits

cor3ntin wrote:

@antangelo do you need me to merge this for you?

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


[clang] [clang-format] Add SkipMacroDefinitionBody option (PR #78682)

2024-01-19 Thread Björn Schäpers via cfe-commits

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


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


[clang] [libcxx] CI Test - Please ignore (PR #78712)

2024-01-19 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 updated 
https://github.com/llvm/llvm-project/pull/78712

>From 1c17da188035ec39c23c62f9f467cfbee05f4f63 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Fri, 19 Jan 2024 14:40:38 +0100
Subject: [PATCH] CI Test - Please ignore

---
 clang/utils/ci/buildkite-pipeline.yml  |  77 +
 libcxx/utils/ci/buildkite-pipeline.yml | 209 +
 2 files changed, 9 insertions(+), 277 deletions(-)

diff --git a/clang/utils/ci/buildkite-pipeline.yml 
b/clang/utils/ci/buildkite-pipeline.yml
index 7a679176038c693..ec037fc8d14316c 100644
--- a/clang/utils/ci/buildkite-pipeline.yml
+++ b/clang/utils/ci/buildkite-pipeline.yml
@@ -17,87 +17,12 @@ env:
 # LLVM RELEASE bump version
 LLVM_HEAD_VERSION: "17"
 steps:
-  - label: "Format"
-commands:
-  - "clang/utils/ci/run-buildbot check-format"
-agents:
-  queue: "linux"
-retry:
-  automatic:
-- exit_status: -1  # Agent was lost
-  limit: 2
-timeout_in_minutes: 120
-
-  - label: "Building and testing clang (Linux)"
-commands:
-  - "clang/utils/ci/run-buildbot build-clang"
-agents:
-  queue: "linux"
-retry:
-  automatic:
-- exit_status: -1  # Agent was lost
-  limit: 2
-timeout_in_minutes: 120
-
   - label: "Building and testing clang (Windows)"
 commands:
   - "C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat -arch=amd64 
-host_arch=amd64"
   - "bash clang/utils/ci/run-buildbot build-clang-windows"
 agents:
-  queue: "windows"
-retry:
-  automatic:
-- exit_status: -1  # Agent was lost
-  limit: 2
-timeout_in_minutes: 120
-
-  - wait
-
-  - label: "Running libc++ test suite in C++03"
-commands:
-  - "clang/utils/ci/run-buildbot generic-cxx03"
-artifact_paths:
-  - "**/test-results.xml"
-  - "**/crash_diagnostics/*"
-env:
-LLVM_SYMBOLIZER_PATH: "/usr/bin/llvm-symbolizer-${LLVM_HEAD_VERSION}" 
# TODO: Should we build that from scratch?
-CLANG_CRASH_DIAGNOSTICS_DIR: "crash_diagnostics"
-agents:
-  queue: "linux"
-retry:
-  automatic:
-- exit_status: -1  # Agent was lost
-  limit: 2
-timeout_in_minutes: 120
-
-  - label: "Running libc++ test suite in C++26"
-commands:
-  - "clang/utils/ci/run-buildbot generic-cxx26"
-artifact_paths:
-  - "**/test-results.xml"
-  - "**/crash_diagnostics/*"
-env:
-LLVM_SYMBOLIZER_PATH: "/usr/bin/llvm-symbolizer-${LLVM_HEAD_VERSION}" 
# TODO: Should we build that from scratch?
-CLANG_CRASH_DIAGNOSTICS_DIR: "crash_diagnostics"
-agents:
-  queue: "linux"
-retry:
-  automatic:
-- exit_status: -1  # Agent was lost
-  limit: 2
-timeout_in_minutes: 120
-
-  - label: "Running libc++ test suite with Clang Modules"
-commands:
-  - "clang/utils/ci/run-buildbot generic-modules"
-artifact_paths:
-  - "**/test-results.xml"
-  - "**/crash_diagnostics/*"
-env:
-LLVM_SYMBOLIZER_PATH: "/usr/bin/llvm-symbolizer-${LLVM_HEAD_VERSION}" 
# TODO: Should we build that from scratch?
-CLANG_CRASH_DIAGNOSTICS_DIR: "crash_diagnostics"
-agents:
-  queue: "linux"
+  queue: "windows-test"
 retry:
   automatic:
 - exit_status: -1  # Agent was lost
diff --git a/libcxx/utils/ci/buildkite-pipeline.yml 
b/libcxx/utils/ci/buildkite-pipeline.yml
index a48f8524ef63c44..b0d1d7414e83879 100644
--- a/libcxx/utils/ci/buildkite-pipeline.yml
+++ b/libcxx/utils/ci/buildkite-pipeline.yml
@@ -63,240 +63,47 @@ steps:
   - label: Clang-cl (DLL)
 command: bash libcxx/utils/ci/run-buildbot clang-cl-dll
 agents:
-  queue: windows
+  queue: windows-test
 <<: *common
 
   - label: Clang-cl (Static)
 command: bash libcxx/utils/ci/run-buildbot clang-cl-static
 agents:
-  queue: windows
+  queue: windows-test
 <<: *common
 
   - label: Clang-cl (no vcruntime exceptions)
 command: bash libcxx/utils/ci/run-buildbot clang-cl-no-vcruntime
 <<: *common
 agents:
-  queue: windows
+  queue: windows-test
 
   - label: Clang-cl (Debug mode)
 command: bash libcxx/utils/ci/run-buildbot clang-cl-debug
 agents:
-  queue: windows
+  queue: windows-test
 <<: *common
 
   - label: Clang-cl (Static CRT)
 command: bash libcxx/utils/ci/run-buildbot clang-cl-static-crt
 agents:
-  queue: windows
+  queue: windows-test
 <<: *common
 
   - label: MinGW (DLL, x86_64)
 command: bash libcxx/utils/ci/run-buildbot mingw-dll
 agents:
-  queue: windows
+  queue: windows-test
 <<: *common
 
   - label: MinGW (Static, x86_64)
 command: bash libcxx/utils/ci/run-buildbot mingw-static
 agents:
-  queue: windows
+  queue: windows-test
 <<: *common
 
   - label: MinGW (DLL, i686)
 command: bash libcxx/utils/ci/run-buildbot mingw-dll-i686
 agents:
-  queue: windows
+  queue: windows

[clang] [llvm] [mlir] [AMDGPU] Add GFX12 WMMA and SWMMAC instructions (PR #77795)

2024-01-19 Thread Mirko Brkušanin via cfe-commits

mbrkusanin wrote:

Rebased.

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits

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

I think splitting the two features would be better.

Also please add a note to the changelog.

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -2459,6 +2459,52 @@ struct FormatStyle {
   /// \version 12
   EmptyLineBeforeAccessModifierStyle EmptyLineBeforeAccessModifier;
 
+  /// \brief Number of lines after includes.
+  /// If set, determines the number of lines to insert after includes.
+  /// Limited by MaxEmptyLinesToKeep.
+  /// Example:
+  /// EmptyLinesAfterIncludes = 1
+  /// \code
+  ///#include 
+  ///#include 
+  ///
+  ///class Test {};
+  ///
+  /// \endcode
+  /// vs EmptyLinesAfterIncludes = 2
+  /// \code
+  ///#include 
+  ///#include 
+  ///
+  ///
+  ///class Test {};
+  /// \endcode
+  /// \version 1

HazardyKnusperkeks wrote:

```suggestion
  /// \version 18
```
You're a bit late for LLVM 1.0 ;)

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -2459,6 +2459,52 @@ struct FormatStyle {
   /// \version 12
   EmptyLineBeforeAccessModifierStyle EmptyLineBeforeAccessModifier;
 
+  /// \brief Number of lines after includes.
+  /// If set, determines the number of lines to insert after includes.
+  /// Limited by MaxEmptyLinesToKeep.
+  /// Example:
+  /// EmptyLinesAfterIncludes = 1
+  /// \code
+  ///#include 
+  ///#include 
+  ///
+  ///class Test {};
+  ///
+  /// \endcode
+  /// vs EmptyLinesAfterIncludes = 2
+  /// \code
+  ///#include 
+  ///#include 
+  ///
+  ///
+  ///class Test {};
+  /// \endcode
+  /// \version 1
+  std::optional EmptyLinesAfterIncludes;
+
+  /// \brief Number of empty lines after top level comment.
+  /// If set, determines the number of empty lines to insert/keep after the top
+  /// level comment. Limited by MaxEmptyLinesToKeep.
+  /// Example:
+  /// EmptyLinesAfterTopLevelComment = 1
+  /// \code

HazardyKnusperkeks wrote:

I prefer both examples in the same code block side by side. It is more concise.

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -0,0 +1,70 @@
+//===--- TopLevelCommentSeparator.cpp ---*- 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
+//
+//===--===//
+///
+/// \file
+/// This file implements TopLevelCommentSeparator, a TokenAnalyzer that inserts
+/// new lines or removes empty lines after the top level comment (i.e. comment
+/// block at the top of the source file), usually license text or 
documentation.
+///
+//===--===//
+
+#include "TopLevelCommentSeparator.h"
+#define DEBUG_TYPE "top-level-comment-separator"
+
+namespace clang {
+namespace format {
+std::pair TopLevelCommentSeparator::analyze(
+TokenAnnotator &Annotator, SmallVectorImpl 
&AnnotatedLines,
+FormatTokenLexer &Tokens) {
+  assert(Style.EmptyLinesAfterTopLevelComment.has_value());
+  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+  tooling::Replacements Result;
+  separateTopLevelComment(AnnotatedLines, Result, Tokens);
+  return {Result, 0};
+}
+
+void TopLevelCommentSeparator::separateTopLevelComment(
+SmallVectorImpl &Lines, tooling::Replacements &Result,
+FormatTokenLexer &Tokens) {
+  unsigned NewlineCount = std::min(Style.MaxEmptyLinesToKeep,
+   *Style.EmptyLinesAfterTopLevelComment) +
+  1;
+  WhitespaceManager Whitespaces(
+  Env.getSourceManager(), Style,
+  Style.LineEnding > FormatStyle::LE_CRLF
+  ? WhitespaceManager::inputUsesCRLF(
+Env.getSourceManager().getBufferData(Env.getFileID()),
+Style.LineEnding == FormatStyle::LE_DeriveCRLF)
+  : Style.LineEnding == FormatStyle::LE_CRLF);
+
+  bool InTopLevelComment = false;
+  for (unsigned I = 0; I < Lines.size(); ++I) {
+const auto &CurrentLine = Lines[I];
+if (CurrentLine->isComment()) {
+  InTopLevelComment = true;
+} else if (InTopLevelComment) {
+  // Do not handle EOF newlines.
+  if (!CurrentLine->First->is(tok::eof) && CurrentLine->Affected) {
+Whitespaces.replaceWhitespace(*CurrentLine->First, NewlineCount,
+  CurrentLine->First->OriginalColumn,
+  CurrentLine->First->OriginalColumn);
+  }
+  break;
+}

HazardyKnusperkeks wrote:

```c++
#include 

// My comment
int foo();
```
Is `My comment` now the "Top level" comment and new lines will be set 
accordingly? That is not what you intent to do, or am I mistaken?

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -1035,6 +1039,8 @@ template <> struct MappingTraits {
 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
 IO.mapOptional("NamespaceMacros", Style.NamespaceMacros);
+IO.mapOptional("EmptyLinesAfterTopLevelComment",

HazardyKnusperkeks wrote:

Remove

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -2459,6 +2459,52 @@ struct FormatStyle {
   /// \version 12
   EmptyLineBeforeAccessModifierStyle EmptyLineBeforeAccessModifier;
 
+  /// \brief Number of lines after includes.
+  /// If set, determines the number of lines to insert after includes.
+  /// Limited by MaxEmptyLinesToKeep.
+  /// Example:
+  /// EmptyLinesAfterIncludes = 1
+  /// \code
+  ///#include 
+  ///#include 
+  ///
+  ///class Test {};
+  ///
+  /// \endcode
+  /// vs EmptyLinesAfterIncludes = 2
+  /// \code
+  ///#include 
+  ///#include 
+  ///
+  ///
+  ///class Test {};
+  /// \endcode
+  /// \version 1
+  std::optional EmptyLinesAfterIncludes;
+
+  /// \brief Number of empty lines after top level comment.
+  /// If set, determines the number of empty lines to insert/keep after the top
+  /// level comment. Limited by MaxEmptyLinesToKeep.
+  /// Example:
+  /// EmptyLinesAfterTopLevelComment = 1
+  /// \code
+  ////* LICENSE TEXT */
+  ///
+  ///#include 
+  ///class Test {};
+  ///
+  /// \endcode
+  /// vs EmptyLinesAfterTopLevelComment = 2
+  /// \code
+  ////* License Text */
+  ///
+  ///
+  ///#include 
+  ///class Test {};
+  /// \endcode
+  /// \version 1
+  std::optional EmptyLinesAfterTopLevelComment;

HazardyKnusperkeks wrote:

The name has to be improved.
```c++
// Top level comment in your definition

#include 

// But this is also top level, or not?
```

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -26846,6 +26846,26 @@ TEST_F(FormatTest, BreakAdjacentStringLiterals) {
   Style.BreakAdjacentStringLiterals = false;
   verifyFormat(Code, Style);
 }
+
+TEST_F(FormatTest, EmptyLinesAfterInclude) {
+  auto Style = getLLVMStyle();
+  Style.EmptyLinesAfterIncludes = 2;
+  Style.MaxEmptyLinesToKeep = 2;
+  verifyFormat("#include \n\n\n"
+   "class Test {};",
+   Style);
+
+  Style.EmptyLinesAfterIncludes = 1;
+  verifyFormat("#include \n\n"
+   "class Test {};",
+   Style);
+
+  Style.EmptyLinesAfterIncludes = 2;
+  Style.MaxEmptyLinesToKeep = 1;
+  verifyFormat("#include \n\n"
+   "class Test {};",
+   Style);
+}

HazardyKnusperkeks wrote:

Please add tests with multiple includes and in conjunction with include 
sorting/grouping.

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -0,0 +1,70 @@
+//===--- TopLevelCommentSeparator.cpp ---*- 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
+//
+//===--===//
+///
+/// \file
+/// This file implements TopLevelCommentSeparator, a TokenAnalyzer that inserts
+/// new lines or removes empty lines after the top level comment (i.e. comment
+/// block at the top of the source file), usually license text or 
documentation.
+///
+//===--===//
+
+#include "TopLevelCommentSeparator.h"
+#define DEBUG_TYPE "top-level-comment-separator"
+
+namespace clang {
+namespace format {
+std::pair TopLevelCommentSeparator::analyze(
+TokenAnnotator &Annotator, SmallVectorImpl 
&AnnotatedLines,
+FormatTokenLexer &Tokens) {
+  assert(Style.EmptyLinesAfterTopLevelComment.has_value());
+  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
+  tooling::Replacements Result;
+  separateTopLevelComment(AnnotatedLines, Result, Tokens);
+  return {Result, 0};
+}
+
+void TopLevelCommentSeparator::separateTopLevelComment(
+SmallVectorImpl &Lines, tooling::Replacements &Result,
+FormatTokenLexer &Tokens) {
+  unsigned NewlineCount = std::min(Style.MaxEmptyLinesToKeep,
+   *Style.EmptyLinesAfterTopLevelComment) +
+  1;
+  WhitespaceManager Whitespaces(
+  Env.getSourceManager(), Style,
+  Style.LineEnding > FormatStyle::LE_CRLF
+  ? WhitespaceManager::inputUsesCRLF(
+Env.getSourceManager().getBufferData(Env.getFileID()),
+Style.LineEnding == FormatStyle::LE_DeriveCRLF)
+  : Style.LineEnding == FormatStyle::LE_CRLF);
+
+  bool InTopLevelComment = false;
+  for (unsigned I = 0; I < Lines.size(); ++I) {
+const auto &CurrentLine = Lines[I];
+if (CurrentLine->isComment()) {
+  InTopLevelComment = true;
+} else if (InTopLevelComment) {
+  // Do not handle EOF newlines.
+  if (!CurrentLine->First->is(tok::eof) && CurrentLine->Affected) {
+Whitespaces.replaceWhitespace(*CurrentLine->First, NewlineCount,
+  CurrentLine->First->OriginalColumn,
+  CurrentLine->First->OriginalColumn);
+  }
+  break;
+}

HazardyKnusperkeks wrote:

Another one
```c++
int foo() {
  // Comment
  return 5;
}
```

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -0,0 +1,112 @@
+//===- unittest/Format/TopLevelCommentSeparatorTest.cpp - Formatting unit tests
+//-===//
+//
+// 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 "FormatTestBase.h"
+
+#define DEBUG_TYPE "format-test-comments"
+
+namespace clang {
+namespace format {
+namespace test {
+namespace {
+
+class TopLevelCommentSeparatorTest : public FormatTestBase {};
+
+TEST_F(TopLevelCommentSeparatorTest, CheckEmptyLines) {
+  FormatStyle Style = getDefaultStyle();
+  Style.EmptyLinesAfterTopLevelComment = 2;
+  Style.MaxEmptyLinesToKeep = 2;
+  verifyFormat("// start license\n"
+   "// license text\n"
+   "// more license text\n"
+   "// end license\n\n\n"
+   "class Test {};",
+   Style);
+
+  verifyFormat("// start license\n"
+   "// license text\n"
+   "// more license text\n"
+   "// end license\n\n\n"
+   "static int test = 10;",
+   Style);
+
+  verifyFormat("// start license\n"
+   "// license text\n"
+   "// more license text\n"
+   "// end license\n\n\n"
+   "#include ",
+   Style);
+
+  verifyFormat("// start license\n"
+   "// license text\n"
+   "// more license text\n"
+   "// end license",
+   Style);
+
+  verifyFormat("/* top level comment */\n\n\n"
+   "#include \n"
+   "class Test {\n"
+   "public:\n"
+   "  void test() {}\n"
+   "};\n"
+   "int main() {\n"
+   "  Test test;\n"
+   "  test.test();\n"
+   "  return 0;\n"
+   "}",
+   Style);
+
+  Style.EmptyLinesAfterTopLevelComment = 1;
+  verifyFormat("// start license\n"
+   "// license text\n"
+   "// more license text\n"
+   "// end license\n\n"
+   "class Test {};",
+   Style);
+
+  verifyFormat("// start license\n"
+   "// license text\n"
+   "// more license text\n"
+   "// end license\n\n"
+   "#include ",
+   Style);
+
+  verifyFormat("/* top level comment */\n\n"
+   "#include \n"
+   "class Test {};",
+   Style);
+}
+
+TEST_F(TopLevelCommentSeparatorTest, LimitedByMaxEmptyLinesToKeep) {
+  FormatStyle Style = getDefaultStyle();
+  Style.EmptyLinesAfterTopLevelComment = 2;
+  Style.MaxEmptyLinesToKeep = 1;
+  verifyFormat("// start license\n"
+   "// license text\n"
+   "// more license text\n"
+   "// end license\n\n"
+   "class Test {};",
+   Style);
+
+  verifyFormat("// start license\n"
+   "// license text\n"
+   "// more license text\n"
+   "// end license\n\n"
+   "#include ",
+   Style);
+
+  verifyFormat("/* top level comment */\n\n"
+   "#include \n"
+   "class Test {};",
+   Style);
+}

HazardyKnusperkeks wrote:

Way more tests.

With declarations, statements, and what ever is possible before the first 
comment.

Also `#ifndef` include guards and `#pragma once'.

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -4827,6 +4873,8 @@ struct FormatStyle {
DerivePointerAlignment == R.DerivePointerAlignment &&
DisableFormat == R.DisableFormat &&
EmptyLineAfterAccessModifier == R.EmptyLineAfterAccessModifier &&
+   EmptyLinesAfterIncludes == R.EmptyLinesAfterIncludes &&
+   EmptyLinesAfterTopLevelComment == R.EmptyLinesAfterTopLevelComment 
&&
EmptyLineBeforeAccessModifier == R.EmptyLineBeforeAccessModifier &&

HazardyKnusperkeks wrote:

```suggestion
   EmptyLineBeforeAccessModifier == R.EmptyLineBeforeAccessModifier &&
   EmptyLinesAfterIncludes == R.EmptyLinesAfterIncludes &&
   EmptyLinesAfterTopLevelComment == R.EmptyLinesAfterTopLevelComment &&
```

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -26846,6 +26846,26 @@ TEST_F(FormatTest, BreakAdjacentStringLiterals) {
   Style.BreakAdjacentStringLiterals = false;
   verifyFormat(Code, Style);
 }
+
+TEST_F(FormatTest, EmptyLinesAfterInclude) {
+  auto Style = getLLVMStyle();
+  Style.EmptyLinesAfterIncludes = 2;
+  Style.MaxEmptyLinesToKeep = 2;
+  verifyFormat("#include \n\n\n"
+   "class Test {};",

HazardyKnusperkeks wrote:

```suggestion
  verifyFormat("#include \n"
  "\n"
  "\n"
   "class Test {};",
```
So one does see the new lines directly.

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


[clang] [openmp] [OpenMP][USM] Introduces -fopenmp-force-usm flag (PR #76571)

2024-01-19 Thread Jan Patrick Lehr via cfe-commits

jplehr wrote:

> Automatic zero-copy doesn't work on some of the bbot's. I will have to land 
> this once the lit test harness extension in #77851 re-lands.

Having your work landed would be very helpful indeed.

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


[clang] [clang][dataflow] Make cap on block visits configurable by caller. (PR #77481)

2024-01-19 Thread Yitzhak Mandelbaum via cfe-commits


@@ -138,13 +138,20 @@ struct TypeErasedDataflowAnalysisState {
 /// dataflow analysis cannot be performed successfully. Otherwise, calls
 /// `PostVisitCFG` on each CFG element with the final analysis results at that
 /// program point.
+///
+/// `MaxBlockVisits` caps the number of block visits during analysis. It 
doesn't
+/// distinguish between repeat visits to the same block and visits to distinct
+/// blocks. This parameter is a backstop to prevent infintite loops, in the 
case
+/// of bugs in the lattice and/or transfer functions that prevent the analysis
+/// from converging.

ymand wrote:

See the FIXME -- I'm planning to followup (quickly) with a patch that removes 
that restriction, once callers have a chance to set their own limits. So, i 
don't think its worth documenting a feature that we're about to remove.

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


[clang] [clang][dataflow] Make cap on block visits configurable by caller. (PR #77481)

2024-01-19 Thread Yitzhak Mandelbaum via cfe-commits


@@ -186,6 +186,14 @@ template  struct DataflowAnalysisState {
 /// the dataflow analysis cannot be performed successfully. Otherwise, calls
 /// `PostVisitCFG` on each CFG element with the final analysis results at that
 /// program point.
+///
+/// `MaxBlockVisits` caps the number of block visits during analysis. It 
doesn't
+/// distinguish between repeat visits to the same block and visits to distinct
+/// blocks. This parameter is a backstop to prevent infintite loops, in the 
case
+/// of bugs in the lattice and/or transfer functions that prevent the analysis
+/// from converging. The default value is essentially arbitrary -- large enough
+/// to accomodate what seems like any reasonable CFG, but still small enough to
+/// limit the cost of hitting the limit.

ymand wrote:

Done.

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


[clang] [clang][dataflow] Make cap on block visits configurable by caller. (PR #77481)

2024-01-19 Thread Yitzhak Mandelbaum via cfe-commits


@@ -138,13 +138,20 @@ struct TypeErasedDataflowAnalysisState {
 /// dataflow analysis cannot be performed successfully. Otherwise, calls
 /// `PostVisitCFG` on each CFG element with the final analysis results at that
 /// program point.
+///
+/// `MaxBlockVisits` caps the number of block visits during analysis. It 
doesn't
+/// distinguish between repeat visits to the same block and visits to distinct
+/// blocks. This parameter is a backstop to prevent infintite loops, in the 
case
+/// of bugs in the lattice and/or transfer functions that prevent the analysis
+/// from converging.

ymand wrote:

done

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


[clang] [clang][dataflow] Make cap on block visits configurable by caller. (PR #77481)

2024-01-19 Thread Yitzhak Mandelbaum via cfe-commits


@@ -261,14 +270,23 @@ auto createAnalysis(ASTContext &ASTCtx, Environment &Env)
 ///   iterations.
 /// - This limit is still low enough to keep runtimes acceptable (on typical
 ///   machines) in cases where we hit the limit.
+///
+/// `MaxBlockVisits` caps the number of block visits during analysis. It 
doesn't
+/// distinguish between repeat visits to the same block and visits to distinct
+/// blocks. This parameter is a backstop to prevent infintite loops, in the 
case
+/// of bugs in the lattice and/or transfer functions that prevent the analysis
+/// from converging. The default value is essentially arbitrary -- large enough
+/// to accomodate what seems like any reasonable CFG, but still small enough to
+/// limit the cost of hitting the limit.

ymand wrote:

done

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


[clang] [clang-format] Support of TableGen identifiers beginning with a number. (PR #78571)

2024-01-19 Thread Björn Schäpers via cfe-commits

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


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


[clang] [clang-format]: Fix formatting of if statements with BlockIndent (PR #77699)

2024-01-19 Thread Björn Schäpers via cfe-commits

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


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


[clang] [clang][dataflow] Make cap on block visits configurable by caller. (PR #77481)

2024-01-19 Thread Yitzhak Mandelbaum via cfe-commits

https://github.com/ymand updated https://github.com/llvm/llvm-project/pull/77481

>From 02f3e6ad46db8df8256ec15f3388399f24eaafad Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Thu, 4 Jan 2024 15:36:40 +
Subject: [PATCH 1/3] [clang][dataflow] Make cap on block visits configurable
 by caller.

Previously, we hard-coded the cap on block visits inside the framework. This
patch enables the caller to specify the cap in the APIs for running an analysis.
---
 .../Analysis/FlowSensitive/DataflowAnalysis.h | 27 +++---
 .../TypeErasedDataflowAnalysis.h  |  9 +-
 .../TypeErasedDataflowAnalysis.cpp| 28 ---
 3 files changed, 42 insertions(+), 22 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
index 1dffbe8a09c360..6426fc1a3aff14 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -186,6 +186,14 @@ template  struct DataflowAnalysisState {
 /// the dataflow analysis cannot be performed successfully. Otherwise, calls
 /// `PostVisitCFG` on each CFG element with the final analysis results at that
 /// program point.
+///
+/// `MaxBlockVisits` caps the number of block visits during analysis. It 
doesn't
+/// distinguish between repeat visits to the same block and visits to distinct
+/// blocks. This parameter is a backstop to prevent infintite loops, in the 
case
+/// of bugs in the lattice and/or transfer functions that prevent the analysis
+/// from converging. The default value is essentially arbitrary -- large enough
+/// to accomodate what seems like any reasonable CFG, but still small enough to
+/// limit the cost of hitting the limit.
 template 
 llvm::Expected>>>
@@ -194,7 +202,8 @@ runDataflowAnalysis(
 const Environment &InitEnv,
 std::function &)>
-PostVisitCFG = nullptr) {
+PostVisitCFG = nullptr,
+std::int32_t MaxBlockVisits = 20'000) {
   std::function
   PostVisitCFGClosure = nullptr;
@@ -212,7 +221,7 @@ runDataflowAnalysis(
   }
 
   auto TypeErasedBlockStates = runTypeErasedDataflowAnalysis(
-  CFCtx, Analysis, InitEnv, PostVisitCFGClosure);
+  CFCtx, Analysis, InitEnv, PostVisitCFGClosure, MaxBlockVisits);
   if (!TypeErasedBlockStates)
 return TypeErasedBlockStates.takeError();
 
@@ -261,6 +270,14 @@ auto createAnalysis(ASTContext &ASTCtx, Environment &Env)
 ///   iterations.
 /// - This limit is still low enough to keep runtimes acceptable (on typical
 ///   machines) in cases where we hit the limit.
+///
+/// `MaxBlockVisits` caps the number of block visits during analysis. It 
doesn't
+/// distinguish between repeat visits to the same block and visits to distinct
+/// blocks. This parameter is a backstop to prevent infintite loops, in the 
case
+/// of bugs in the lattice and/or transfer functions that prevent the analysis
+/// from converging. The default value is essentially arbitrary -- large enough
+/// to accomodate what seems like any reasonable CFG, but still small enough to
+/// limit the cost of hitting the limit.
 template 
 llvm::Expected> diagnoseFunction(
 const FunctionDecl &FuncDecl, ASTContext &ASTCtx,
@@ -268,7 +285,8 @@ llvm::Expected> 
diagnoseFunction(
 const CFGElement &, ASTContext &,
 const TransferStateForDiagnostics &)>
 Diagnoser,
-std::int64_t MaxSATIterations = 1'000'000'000) {
+std::int64_t MaxSATIterations = 1'000'000'000,
+std::int32_t MaxBlockVisits = 20'000) {
   llvm::Expected Context =
   ControlFlowContext::build(FuncDecl);
   if (!Context)
@@ -293,7 +311,8 @@ llvm::Expected> 
diagnoseFunction(
 State.Lattice.Value),
 State.Env));
 llvm::move(EltDiagnostics, std::back_inserter(Diagnostics));
-  })
+  },
+  MaxBlockVisits)
   .takeError())
 return std::move(Err);
 
diff --git 
a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
index 67c323dbf45e1b..edc582ac938fa2 100644
--- a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
@@ -138,13 +138,20 @@ struct TypeErasedDataflowAnalysisState {
 /// dataflow analysis cannot be performed successfully. Otherwise, calls
 /// `PostVisitCFG` on each CFG element with the final analysis results at that
 /// program point.
+///
+/// `MaxBlockVisits` caps the number of block visits during analysis. It 
doesn't
+/// distinguish between repeat visits to the same block and visits to distinct
+/// blocks. This parameter is a backstop to prevent infintite loops, in the 
case
+/// of bugs in the lattice and/or transfer functions that prevent the analysis
+/// from converging.
 

[clang] [clang][dataflow] Make cap on block visits configurable by caller. (PR #77481)

2024-01-19 Thread Yitzhak Mandelbaum via cfe-commits


@@ -186,6 +186,14 @@ template  struct DataflowAnalysisState {
 /// the dataflow analysis cannot be performed successfully. Otherwise, calls
 /// `PostVisitCFG` on each CFG element with the final analysis results at that
 /// program point.
+///
+/// `MaxBlockVisits` caps the number of block visits during analysis. It 
doesn't
+/// distinguish between repeat visits to the same block and visits to distinct
+/// blocks. This parameter is a backstop to prevent infintite loops, in the 
case
+/// of bugs in the lattice and/or transfer functions that prevent the analysis
+/// from converging. The default value is essentially arbitrary -- large enough
+/// to accomodate what seems like any reasonable CFG, but still small enough to
+/// limit the cost of hitting the limit.

ymand wrote:

done

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-19 Thread Björn Schäpers via cfe-commits

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


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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -3392,6 +3392,24 @@ the configuration (without a prefix: ``Auto``).
 Priority:1
 SortPriority:0
 
+.. _MainIncludeChar:

HazardyKnusperkeks wrote:

Did you add this by hand? I'm wondering why it has a different order than in 
the header.

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-19 Thread Björn Schäpers via cfe-commits

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -151,6 +151,21 @@ struct IncludeStyle {
   /// before any other include.
   /// \version 10
   std::string IncludeIsMainSourceRegex;
+
+  /// Character to consider in the include directives for the main header.
+  enum MainIncludeCharDiscriminator {
+/// Main include uses quotes: ``#include "foo.hpp"``
+MICD_Quote,
+/// Main include uses brackets: ``#include ``
+MICD_Bracket,
+/// Main include uses either quotes or brackets.

HazardyKnusperkeks wrote:

```suggestion
/// Main include uses angle brackets: ``#include ``
MICD_AngleBracket,
/// Main include uses either quotes or angle brackets.
```

Brackets are `[` and `]`.

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -151,6 +151,21 @@ struct IncludeStyle {
   /// before any other include.
   /// \version 10
   std::string IncludeIsMainSourceRegex;
+
+  /// Character to consider in the include directives for the main header.
+  enum MainIncludeCharDiscriminator {

HazardyKnusperkeks wrote:

```suggestion
  enum MainIncludeCharDiscriminator : int8_t {
```
Is now common in clang format.

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -0,0 +1,27 @@
+// Test the combination of regrouped include directives, via regexes and

HazardyKnusperkeks wrote:

Our tests reside in `clang/unittests/Format/SortIncludesTest.cpp`.

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -151,6 +151,21 @@ struct IncludeStyle {
   /// before any other include.
   /// \version 10
   std::string IncludeIsMainSourceRegex;
+
+  /// Character to consider in the include directives for the main header.

HazardyKnusperkeks wrote:

It should also be added to `FormatStyle::operator==` in `Format.h`.

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


[clang] [libcxx] [SemaCXX] Implement CWG2137 (list-initialization from objects of the same type) (PR #77768)

2024-01-19 Thread via cfe-commits

cor3ntin wrote:

Let me merge that lest I forget. Our windows bots have a lot of issues

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


[clang] 9247013 - [SemaCXX] Implement CWG2137 (list-initialization from objects of the same type) (#77768)

2024-01-19 Thread via cfe-commits

Author: Mital Ashok
Date: 2024-01-19T21:10:51+01:00
New Revision: 924701311aa79180e86ad8ce43d253f27d25ec7d

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

LOG: [SemaCXX] Implement CWG2137 (list-initialization from objects of the same 
type) (#77768)

Closes #77638, #24186

Rebased from , see there for more
information.

Implements wording change in [CWG2137](https://wg21.link/CWG2137) in the
first commit.

This also implements an approach to [CWG2311](https://wg21.link/CWG2311)
in the second commit, because too much code that relies on `T{ T_prvalue}` 
being an elision would break. Because that issue is still open and
the CWG issue doesn't provide wording to fix the issue, there may be
different behaviours on other compilers.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaInit.cpp
clang/lib/Sema/SemaOverload.cpp
clang/test/CXX/drs/dr14xx.cpp
clang/test/CXX/drs/dr21xx.cpp
clang/test/CXX/drs/dr23xx.cpp
clang/www/cxx_dr_status.html

libcxx/test/std/utilities/utility/pairs/pairs.pair/ctor.pair_U_V_move.pass.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 392f694065a242..585e1535b15852 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -229,6 +229,11 @@ C++2c Feature Support
 
 Resolutions to C++ Defect Reports
 ^
+- Implemented `CWG2137 `_ which allows
+  list-initialization from objects of the same type.
+- Implemented `CWG2311 `_: given a prvalue ``e`` of 
object type
+  ``T``, ``T{e}`` will try to resolve an initializer list constructor and will 
use it if successful (CWG2137).
+  Otherwise, if there is no initializer list constructor, the copy will be 
elided as if it was ``T(e)``.
 
 - Implemented `CWG2598 `_ and `CWG2096 
`_,
   making unions (that have either no members or at least one literal member) 
literal types.

diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 18440a69e3a3d9..3170f41e8033f2 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -4200,7 +4200,7 @@ static OverloadingResult ResolveConstructorOverload(
 /// \param IsListInit Is this list-initialization?
 /// \param IsInitListCopy Is this non-list-initialization resulting from a
 ///   list-initialization from {x} where x is the same
-///   type as the entity?
+///   aggregate type as the entity?
 static void TryConstructorInitialization(Sema &S,
  const InitializedEntity &Entity,
  const InitializationKind &Kind,
@@ -4230,6 +4230,14 @@ static void TryConstructorInitialization(Sema &S,
 Entity.getKind() !=
 InitializedEntity::EK_LambdaToBlockConversionBlockElement);
 
+  bool CopyElisionPossible = false;
+  auto ElideConstructor = [&] {
+// Convert qualifications if necessary.
+Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
+if (ILE)
+  Sequence.RewrapReferenceInitList(DestType, ILE);
+  };
+
   // C++17 [dcl.init]p17:
   // - If the initializer expression is a prvalue and the cv-unqualified
   //   version of the source type is the same class as the class of the
@@ -4242,11 +4250,17 @@ static void TryConstructorInitialization(Sema &S,
   if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
   UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
   S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) 
{
-// Convert qualifications if necessary.
-Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
-if (ILE)
-  Sequence.RewrapReferenceInitList(DestType, ILE);
-return;
+if (ILE && !DestType->isAggregateType()) {
+  // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
+  // Make this an elision if this won't call an initializer-list
+  // constructor. (Always on an aggregate type or check constructors 
first.)
+  assert(!IsInitListCopy &&
+ "IsInitListCopy only possible with aggregate types");
+  CopyElisionPossible = true;
+} else {
+  ElideConstructor();
+  return;
+}
   }
 
   const RecordType *DestRecordType = DestType->getAs();
@@ -4291,6 +4305,12 @@ static void TryConstructorInitialization(Sema &S,
   S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
   CopyInitialization, AllowExplicit,
   /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
+
+if (CopyEl

[clang] [libcxx] [SemaCXX] Implement CWG2137 (list-initialization from objects of the same type) (PR #77768)

2024-01-19 Thread via cfe-commits

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


[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)

2024-01-19 Thread Björn Schäpers via cfe-commits


@@ -3132,20 +3133,24 @@ static void sortCppIncludes(const FormatStyle &Style,
 }
 result += Includes[Index].Text;
 if (Cursor && CursorIndex == Index)
-  *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
+  NewCursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
 CurrentCategory = Includes[Index].Category;
   }
 
-  if (Cursor && *Cursor >= IncludesEndOffset)
-*Cursor += result.size() - IncludesBlockSize;
-
   // If the #includes are out of order, we generate a single replacement fixing
   // the entire range of blocks. Otherwise, no replacement is generated.
   if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr(
  IncludesBeginOffset, IncludesBlockSize {
 return;
   }
 
+  if (Cursor) {
+if (UINT_MAX != NewCursor)

HazardyKnusperkeks wrote:

```suggestion
if (NewCursor != UINT_MAX)
```
Still that. :)

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


[clang] 8959206 - Remove an unused API; NFC

2024-01-19 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2024-01-19T15:15:24-05:00
New Revision: 89592061a4d53a5b78ca033fb13ba9f9f27ab1b7

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

LOG: Remove an unused API; NFC

Not only is this unused, it's really confusing having
getAPValueResult() and getResultAsAPValue() as sibling APIs

Added: 


Modified: 
clang/include/clang/AST/Expr.h

Removed: 




diff  --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 9de3e356094670b..9820bd11da8609d 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -1136,7 +1136,6 @@ class ConstantExpr final
 return ConstantExprBits.APValueKind != APValue::None;
   }
   APValue getAPValueResult() const;
-  APValue &getResultAsAPValue() const { return APValueResult(); }
   llvm::APSInt getResultAsAPSInt() const;
   // Iterators
   child_range children() { return child_range(&SubExpr, &SubExpr+1); }



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


[clang] [clang-tools-extra] [clang][NFC] Refactor `CXXNewExpr::InitializationStyle` (re-land) (PR #71417)

2024-01-19 Thread via cfe-commits

tomasz-kaminski-sonarsource wrote:

> I had an offline discussion with @Endilll during my morning office hours 
> today, and our current plan is:
> 
> 1. Remove `Implicit` from the enumeration, rename `Call` and `List` to 
> `ParenList` and `BraceList`, respectively
> 2. Add a new bit to the bit-field for `CXXNewExpr` to track "has an 
> initializer" instead of encoding it as in-band information in the 
> initialization style.
> 3. Use that new bit internally in `CXXNewExpr`, update serialization and 
> whatnot accordingly.
> 
> This should bring us back to the enumeration mapping directly to syntax but 
> removes the strange in-band nature of how the original enumeration was being 
> used.

Thank you! I really like how this direction, that both keeps the benefit of 
simplified implementation and makes the enumeration values cleaner. Of course 
this resolves, all concerns that we have with this change.

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


[clang] [llvm] [AMDGPU]: Add and codegen sched_group_barrier_inst (PR #78775)

2024-01-19 Thread Jeffrey Byrnes via cfe-commits

https://github.com/jrbyrnes created 
https://github.com/llvm/llvm-project/pull/78775

As stated, this simply adds and codegens the builtin/intrinsic. A subsequent 
patch will interface it with IGroupLP.

The idea is to give the users more expression by allowing them to create 
schedgroups which have an inclusion mechanism that compares the char * argument 
of the builtin to the name of the instruction -- with the argument being 
handled as a prefix (again, this will be implemented in subsequent patch).

There are some peculiarities with handling the char *, so I've created this as 
a separate review. In particular, I wasn't quite sure the best way to provide 
the metadata to the MIR passes -- open to ideas.

>From 6687ddf4ff756bf15c8e7204e23491322c5b6d8c Mon Sep 17 00:00:00 2001
From: Jeffrey Byrnes 
Date: Fri, 19 Jan 2024 11:59:57 -0800
Subject: [PATCH] [AMDGPU]: Add and codegen sched_group_barrier_inst

Change-Id: I920b3787a9a2c9f65b02d3d897bfe89573a97e27
---
 clang/include/clang/Basic/BuiltinsAMDGPU.def  |  1 +
 clang/lib/CodeGen/CGBuiltin.cpp   | 16 +
 clang/test/CodeGenOpenCL/builtins-amdgcn.cl   | 13 +++
 llvm/include/llvm/IR/IntrinsicsAMDGPU.td  | 11 ++
 llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp |  1 +
 llvm/lib/Target/AMDGPU/AMDGPUISelLowering.h   |  2 ++
 llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp  | 15 
 .../lib/Target/AMDGPU/AMDGPUMachineFunction.h | 25 ++
 llvm/lib/Target/AMDGPU/SIISelLowering.cpp | 18 ++
 llvm/lib/Target/AMDGPU/SIInstructions.td  | 18 ++
 .../llvm.amdgcn.sched.group.barrier.inst.ll   | 34 +++
 11 files changed, 154 insertions(+)
 create mode 100644 
llvm/test/CodeGen/AMDGPU/llvm.amdgcn.sched.group.barrier.inst.ll

diff --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def 
b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index e562ef04a30194..bd540bebd37319 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -64,6 +64,7 @@ BUILTIN(__builtin_amdgcn_s_barrier, "v", "n")
 BUILTIN(__builtin_amdgcn_wave_barrier, "v", "n")
 BUILTIN(__builtin_amdgcn_sched_barrier, "vIi", "n")
 BUILTIN(__builtin_amdgcn_sched_group_barrier, "vIiIiIi", "n")
+BUILTIN(__builtin_amdgcn_sched_group_barrier_inst, "vcC*IiIi", "n")
 BUILTIN(__builtin_amdgcn_iglp_opt, "vIi", "n")
 BUILTIN(__builtin_amdgcn_s_dcache_inv, "v", "n")
 BUILTIN(__builtin_amdgcn_buffer_wbinvl1, "v", "n")
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 1ed35befe1361f..efcb0e80a4eb5c 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -18149,6 +18149,22 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
 CGM.getIntrinsic(Intrinsic::amdgcn_s_sendmsg_rtn, {ResultType});
 return Builder.CreateCall(F, {Arg});
   }
+  case AMDGPU::BI__builtin_amdgcn_sched_group_barrier_inst: {
+StringRef InstrStr;
+llvm::getConstantStringInfo(EmitScalarExpr(E->getArg(0)), InstrStr);
+
+llvm::MDBuilder MDHelper(getLLVMContext());
+
+MDNode *InfoTuple =
+MDTuple::get(getLLVMContext(), {MDHelper.createString(InstrStr)});
+auto MDV = MetadataAsValue::get(getLLVMContext(), InfoTuple);
+
+Function *F =
+CGM.getIntrinsic(Intrinsic::amdgcn_sched_group_barrier_inst, {});
+llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
+llvm::Value *Src2 = EmitScalarExpr(E->getArg(2));
+return Builder.CreateCall(F, {MDV, Src1, Src2});
+  }
   default:
 return nullptr;
   }
diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
index 0bc9a54682d3e3..d43a47746cf0df 100644
--- a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
@@ -436,6 +436,19 @@ void test_sched_group_barrier()
   __builtin_amdgcn_sched_group_barrier(15, 1, -1);
 }
 
+// CHECK-LABEL: @test_sched_group_barrier_inst
+// CHECK: call void @llvm.amdgcn.sched.group.barrier.inst(metadata !16, i32 1, 
i32 2)
+// CHECK: call void @llvm.amdgcn.sched.group.barrier.inst(metadata !17, i32 3, 
i32 1)
+// CHECK: call void @llvm.amdgcn.sched.group.barrier.inst(metadata !16, i32 
1000, i32 -1)
+// CHECK: call void @llvm.amdgcn.sched.group.barrier.inst(metadata !18, i32 1, 
i32 1)
+void test_sched_group_barrier_inst()
+{
+  __builtin_amdgcn_sched_group_barrier_inst("ds_r",1,2);
+  __builtin_amdgcn_sched_group_barrier_inst("v_cvt",3,1);
+  __builtin_amdgcn_sched_group_barrier_inst("ds_r",1000,-1);
+  __builtin_amdgcn_sched_group_barrier_inst("1",1,1);
+}
+
 // CHECK-LABEL: @test_iglp_opt
 // CHECK: call void @llvm.amdgcn.iglp.opt(i32 0)
 // CHECK: call void @llvm.amdgcn.iglp.opt(i32 1)
diff --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td 
b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
index e5596258847f9f..fd8b4581d97c8c 100644
--- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -302,6 +302,

[clang] [llvm] [AMDGPU]: Add and codegen sched_group_barrier_inst (PR #78775)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-amdgpu

Author: Jeffrey Byrnes (jrbyrnes)


Changes

As stated, this simply adds and codegens the builtin/intrinsic. A subsequent 
patch will interface it with IGroupLP.

The idea is to give the users more expression by allowing them to create 
schedgroups which have an inclusion mechanism that compares the char * argument 
of the builtin to the name of the instruction -- with the argument being 
handled as a prefix (again, this will be implemented in subsequent patch).

There are some peculiarities with handling the char *, so I've created this as 
a separate review. In particular, I wasn't quite sure the best way to provide 
the metadata to the MIR passes -- open to ideas.

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


11 Files Affected:

- (modified) clang/include/clang/Basic/BuiltinsAMDGPU.def (+1) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+16) 
- (modified) clang/test/CodeGenOpenCL/builtins-amdgcn.cl (+13) 
- (modified) llvm/include/llvm/IR/IntrinsicsAMDGPU.td (+11) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp (+1) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUISelLowering.h (+2) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp (+15) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUMachineFunction.h (+25) 
- (modified) llvm/lib/Target/AMDGPU/SIISelLowering.cpp (+18) 
- (modified) llvm/lib/Target/AMDGPU/SIInstructions.td (+18) 
- (added) llvm/test/CodeGen/AMDGPU/llvm.amdgcn.sched.group.barrier.inst.ll 
(+34) 


``diff
diff --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def 
b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index e562ef04a30194e..bd540bebd37319b 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -64,6 +64,7 @@ BUILTIN(__builtin_amdgcn_s_barrier, "v", "n")
 BUILTIN(__builtin_amdgcn_wave_barrier, "v", "n")
 BUILTIN(__builtin_amdgcn_sched_barrier, "vIi", "n")
 BUILTIN(__builtin_amdgcn_sched_group_barrier, "vIiIiIi", "n")
+BUILTIN(__builtin_amdgcn_sched_group_barrier_inst, "vcC*IiIi", "n")
 BUILTIN(__builtin_amdgcn_iglp_opt, "vIi", "n")
 BUILTIN(__builtin_amdgcn_s_dcache_inv, "v", "n")
 BUILTIN(__builtin_amdgcn_buffer_wbinvl1, "v", "n")
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 1ed35befe1361f4..efcb0e80a4eb5c7 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -18149,6 +18149,22 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
 CGM.getIntrinsic(Intrinsic::amdgcn_s_sendmsg_rtn, {ResultType});
 return Builder.CreateCall(F, {Arg});
   }
+  case AMDGPU::BI__builtin_amdgcn_sched_group_barrier_inst: {
+StringRef InstrStr;
+llvm::getConstantStringInfo(EmitScalarExpr(E->getArg(0)), InstrStr);
+
+llvm::MDBuilder MDHelper(getLLVMContext());
+
+MDNode *InfoTuple =
+MDTuple::get(getLLVMContext(), {MDHelper.createString(InstrStr)});
+auto MDV = MetadataAsValue::get(getLLVMContext(), InfoTuple);
+
+Function *F =
+CGM.getIntrinsic(Intrinsic::amdgcn_sched_group_barrier_inst, {});
+llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
+llvm::Value *Src2 = EmitScalarExpr(E->getArg(2));
+return Builder.CreateCall(F, {MDV, Src1, Src2});
+  }
   default:
 return nullptr;
   }
diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
index 0bc9a54682d3e31..d43a47746cf0df9 100644
--- a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
@@ -436,6 +436,19 @@ void test_sched_group_barrier()
   __builtin_amdgcn_sched_group_barrier(15, 1, -1);
 }
 
+// CHECK-LABEL: @test_sched_group_barrier_inst
+// CHECK: call void @llvm.amdgcn.sched.group.barrier.inst(metadata !16, i32 1, 
i32 2)
+// CHECK: call void @llvm.amdgcn.sched.group.barrier.inst(metadata !17, i32 3, 
i32 1)
+// CHECK: call void @llvm.amdgcn.sched.group.barrier.inst(metadata !16, i32 
1000, i32 -1)
+// CHECK: call void @llvm.amdgcn.sched.group.barrier.inst(metadata !18, i32 1, 
i32 1)
+void test_sched_group_barrier_inst()
+{
+  __builtin_amdgcn_sched_group_barrier_inst("ds_r",1,2);
+  __builtin_amdgcn_sched_group_barrier_inst("v_cvt",3,1);
+  __builtin_amdgcn_sched_group_barrier_inst("ds_r",1000,-1);
+  __builtin_amdgcn_sched_group_barrier_inst("1",1,1);
+}
+
 // CHECK-LABEL: @test_iglp_opt
 // CHECK: call void @llvm.amdgcn.iglp.opt(i32 0)
 // CHECK: call void @llvm.amdgcn.iglp.opt(i32 1)
diff --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td 
b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
index e5596258847f9f1..fd8b4581d97c8c2 100644
--- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -302,6 +302,17 @@ def int_amdgcn_sched_group_barrier : 
ClangBuiltin<"__builtin_amdgcn_sched_group_
   [ImmArg>, ImmArg>, ImmArg>, IntrNoMem, 
IntrHasSideEffects,
IntrConvergent, IntrWillReturn, IntrNoCallback, IntrNoFree]>

[clang] [llvm] [clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-19 Thread Bhuminjay Soni via cfe-commits

11happy wrote:

@5chmidti I have added all the requested changes.
Thank you

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-19 Thread via cfe-commits


@@ -3392,6 +3392,24 @@ the configuration (without a prefix: ``Auto``).
 Priority:1
 SortPriority:0
 
+.. _MainIncludeChar:

j-jorge wrote:

Yes, is it supposed to be automatically generated?

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-19 Thread via cfe-commits


@@ -0,0 +1,27 @@
+// Test the combination of regrouped include directives, via regexes and

j-jorge wrote:

Ok I will move them there, thanks :) Should I remove these lit tests or are 
they complementary?

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


[clang] [llvm] [RISCV] Relax march string order constraint (PR #78120)

2024-01-19 Thread Fangrui Song via cfe-commits


@@ -156,9 +156,8 @@
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32L %s
 // RV32L: error: invalid arch name 'rv32l'
 
-// RUN: not %clang --target=riscv32-unknown-elf -march=rv32imadf -### %s \
-// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32IMADF %s
-// RV32IMADF: error: invalid arch name 'rv32imadf'
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32imadf -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck %s

MaskRay wrote:

The convention is to indent continuation lines by 2 spaces. Some tests do not 
follow the convention. You can make them follow the convention as you are 
modifying lines.

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


[clang] Add option -fstdlib-hardening= (PR #78763)

2024-01-19 Thread Louis Dionne via cfe-commits

https://github.com/ldionne commented:

This is nice!

Tagging a few people who might have opinions on the naming: @nico @kubamracek 
@AaronBallman

Also, @jwakely it would be nice if this worked with libstdc++ as well in the 
future -- it would probably turn on checks like `__GLIBCXX_ASSERT__`. Do you 
have thoughts on this? And if we want to do this, then `gcc` would also need to 
gain an option that works similarly.

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


[clang] Add option -fstdlib-hardening= (PR #78763)

2024-01-19 Thread Louis Dionne via cfe-commits

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


[clang] Add option -fstdlib-hardening= (PR #78763)

2024-01-19 Thread Louis Dionne via cfe-commits


@@ -281,6 +281,7 @@ LANGOPT(OffloadingNewDriver, 1, 0, "use the new driver for 
generating offloading
 LANGOPT(SYCLIsDevice  , 1, 0, "Generate code for SYCL device")
 LANGOPT(SYCLIsHost, 1, 0, "SYCL host compilation")
 ENUM_LANGOPT(SYCLVersion  , SYCLMajorVersion, 2, SYCL_None, "Version of the 
SYCL standard used")
+ENUM_LANGOPT(LibcxxHardeningMode, LibcxxHardeningModeKind, 3, 
LIBCPP_HARDENING_MODE_NOT_SPECIFIED, "libc++ harderning mode")

ldionne wrote:

This should be `StdlibHardeningMode` to reflect the option name -- in the 
future we could potentially expand to libstdc++ as well. I think this applies 
to a couple of other names throughout the review, too.

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


[clang] Add option -fstdlib-hardening= (PR #78763)

2024-01-19 Thread Louis Dionne via cfe-commits


@@ -275,6 +275,8 @@ def warn_drv_unknown_argument_clang_cl_with_suggestion : 
Warning<
   InGroup;
 def err_drv_unknown_target_triple : Error<"unknown target triple '%0'">;
 
+def err_drv_stdlib_hardening_unavailable : Error<"libc++ hardening is 
available only when libc++ is used">;

ldionne wrote:

```suggestion
def err_drv_stdlib_hardening_unavailable : Error<"standard library hardening is 
available only when libc++ is used">;
```

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


[clang] Add option -fstdlib-hardening= (PR #78763)

2024-01-19 Thread Louis Dionne via cfe-commits


@@ -851,6 +851,33 @@ static void InitializePredefinedMacros(const TargetInfo 
&TI,
   Twine(getClangFullCPPVersion()) + "\"");
 
   // Initialize language-specific preprocessor defines.
+  if (LangOpts.getLibcxxHardeningMode()) {
+const char *LibcxxHardeningStr;
+
+Builder.defineMacro("_LIBCPP_HARDENING_MODE_NONE", "0");

ldionne wrote:

It would be great to avoid coupling these values between Clang and libc++. 
Can't you just define e.g. `_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST` 
without actually defining what `_LIBCPP_HARDENING_MODE_FAST` expands to?

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


[llvm] [clang] [RISCV] Relax march string order constraint (PR #78120)

2024-01-19 Thread Fangrui Song via cfe-commits


@@ -785,153 +878,61 @@ RISCVISAInfo::parseArchString(StringRef Arch, bool 
EnableExperimentalExtension,
   Minor = Version->Minor;
 }
 
-ISAInfo->addExtension(StringRef(&Baseline, 1), {Major, Minor});
+// Postpone AddExtension until end of this function
+SeenExts.push_back(StringRef(&Baseline, 1).str());
+ExtsVersion.push_back({Major, Minor});
   }
 
   // Consume the base ISA version number and any '_' between rvxxx and the
   // first extension
   Exts = Exts.drop_front(ConsumeLength);
   Exts.consume_front("_");
 
-  auto StdExtsItr = StdExts.begin();
-  auto StdExtsEnd = StdExts.end();
-  auto GoToNextExt = [](StringRef::iterator &I, unsigned ConsumeLength,
-StringRef::iterator E) {
-I += 1 + ConsumeLength;
-if (I != E && *I == '_')
-  ++I;
-  };
-  for (auto I = Exts.begin(), E = Exts.end(); I != E;) {
-char C = *I;
-
-// Check ISA extensions are specified in the canonical order.
-while (StdExtsItr != StdExtsEnd && *StdExtsItr != C)
-  ++StdExtsItr;
-
-if (StdExtsItr == StdExtsEnd) {
-  // Either c contains a valid extension but it was not given in
-  // canonical order or it is an invalid extension.
-  if (StdExts.contains(C)) {
-return createStringError(
-errc::invalid_argument,
-"standard user-level extension not given in canonical order '%c'",
-C);
-  }
-
-  return createStringError(errc::invalid_argument,
-   "invalid standard user-level extension '%c'", 
C);
-}
-
-// Move to next char to prevent repeated letter.
-++StdExtsItr;
-
-StringRef Next;
-unsigned Major, Minor, ConsumeLength;
-if (std::next(I) != E)
-  Next = StringRef(std::next(I), E - std::next(I));
-if (auto E = getExtensionVersion(StringRef(&C, 1), Next, Major, Minor,
- ConsumeLength, 
EnableExperimentalExtension,
- ExperimentalExtensionVersionCheck)) {
-  if (IgnoreUnknown) {
-consumeError(std::move(E));
-GoToNextExt(I, ConsumeLength, Exts.end());
-continue;
-  }
-  return std::move(E);
-}
-
-// The order is OK, then push it into features.
-// Currently LLVM supports only "mafdcvh".
-if (!isSupportedExtension(StringRef(&C, 1))) {
-  if (IgnoreUnknown) {
-GoToNextExt(I, ConsumeLength, Exts.end());
-continue;
-  }
-  return createStringError(errc::invalid_argument,
-   "unsupported standard user-level extension 
'%c'",
-   C);
-}
-ISAInfo->addExtension(StringRef(&C, 1), {Major, Minor});
-
-// Consume full extension name and version, including any optional '_'
-// between this extension and the next
-GoToNextExt(I, ConsumeLength, Exts.end());
-  }
-
-  // Handle other types of extensions other than the standard
-  // general purpose and standard user-level extensions.
-  // Parse the ISA string containing non-standard user-level
-  // extensions, standard supervisor-level extensions and
-  // non-standard supervisor-level extensions.
-  // These extensions start with 'z', 's', 'x' prefixes, might have a version

MaskRay wrote:

This comment appears to be removed. Consider retaining it.

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


[llvm] [clang] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-19 Thread Jonas Paulsson via cfe-commits

https://github.com/JonPsson1 updated 
https://github.com/llvm/llvm-project/pull/73511

>From 5c1c5d401775089bc600b85227f5e7bd974d4bd0 Mon Sep 17 00:00:00 2001
From: Jonas Paulsson 
Date: Thu, 23 Nov 2023 17:22:32 +0100
Subject: [PATCH 1/2] Initial Also handle weak symbols Fix test for -emit-llvm
 clang-format

---
 clang/include/clang/AST/ASTContext.h  |   4 +-
 clang/include/clang/Basic/TargetInfo.h|   6 +-
 clang/include/clang/Driver/Options.td |   4 +
 clang/lib/AST/ASTContext.cpp  |  12 +-
 clang/lib/Basic/Targets/AArch64.cpp   |   5 +-
 clang/lib/Basic/Targets/AArch64.h |   3 +-
 clang/lib/Basic/Targets/CSKY.cpp  |   3 +-
 clang/lib/Basic/Targets/CSKY.h|   2 +-
 clang/lib/Basic/Targets/NVPTX.cpp |   3 +-
 clang/lib/Basic/Targets/SPIR.h|   3 +-
 clang/lib/Basic/Targets/SystemZ.cpp   |  11 ++
 clang/lib/Basic/Targets/SystemZ.h |   9 +-
 clang/lib/CodeGen/CodeGenModule.cpp   |   7 +-
 clang/lib/Driver/ToolChains/Arch/SystemZ.cpp  |   8 ++
 clang/lib/Sema/SemaOpenMP.cpp |   2 +-
 .../test/CodeGen/SystemZ/unaligned-symbols.c  | 113 ++
 llvm/lib/Target/SystemZ/SystemZFeatures.td|   5 +
 17 files changed, 179 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/CodeGen/SystemZ/unaligned-symbols.c

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 3e46a5da3fc043..2c42602bef5a6f 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2406,11 +2406,11 @@ class ASTContext : public RefCountedBase {
 
   /// Return the alignment in bits that should be given to a
   /// global variable with type \p T.
-  unsigned getAlignOfGlobalVar(QualType T) const;
+  unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const;
 
   /// Return the alignment in characters that should be given to a
   /// global variable with type \p T.
-  CharUnits getAlignOfGlobalVarInChars(QualType T) const;
+  CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const;
 
   /// Return a conservative estimate of the alignment of the specified
   /// decl \p D.
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 3eb23ebdacf0ed..7ac6bf24124cdd 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -50,6 +50,7 @@ class DiagnosticsEngine;
 class LangOptions;
 class CodeGenOptions;
 class MacroBuilder;
+class VarDecl;
 
 /// Contains information gathered from parsing the contents of TargetAttr.
 struct ParsedTargetAttr {
@@ -704,8 +705,9 @@ class TargetInfo : public TransferrableTargetInfo,
   }
 
   /// getMinGlobalAlign - Return the minimum alignment of a global variable,
-  /// unless its alignment is explicitly reduced via attributes.
-  virtual unsigned getMinGlobalAlign (uint64_t) const {
+  /// unless its alignment is explicitly reduced via attributes. If \param VD
+  /// is non-null, it may be used to examine the specific variable's 
attributes.
+  virtual unsigned getMinGlobalAlign(uint64_t Size, const VarDecl *VD) const {
 return MinGlobalAlign;
   }
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d2e6c3ff721c27..29f2b5c8b00512 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4601,6 +4601,10 @@ def munaligned_access : Flag<["-"], 
"munaligned-access">, Group,
   HelpText<"Allow memory accesses to be unaligned 
(AArch32/AArch64/LoongArch/RISC-V only)">;
 def mno_unaligned_access : Flag<["-"], "mno-unaligned-access">, Group,
   HelpText<"Force all memory accesses to be aligned 
(AArch32/AArch64/LoongArch/RISC-V only)">;
+def munaligned_symbols : Flag<["-"], "munaligned-symbols">, Group,
+  HelpText<"Expect external char-aligned symbols to be without ABI alignment 
(SystemZ only)">;
+def mno_unaligned_symbols : Flag<["-"], "mno-unaligned-symbols">, 
Group,
+  HelpText<"Expect external char-aligned symbols to be without ABI alignment 
(SystemZ only)">;
 } // let Flags = [TargetSpecific]
 def mstrict_align : Flag<["-"], "mstrict-align">, Alias,
   Flags<[HelpHidden]>, Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 0fc0831b221aab..a6314c83f06ca7 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -1688,7 +1688,8 @@ CharUnits ASTContext::getDeclAlign(const Decl *D, bool 
ForAlignof) const {
   if (VD->hasGlobalStorage() && !ForAlignof) {
 uint64_t TypeSize =
 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
-Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
+Align =
+std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize, VD));
   }
 
 // Fields can be subject to extr

[clang] [llvm] [RISCV] Relax march string order constraint (PR #78120)

2024-01-19 Thread Fangrui Song via cfe-commits

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

GCC patch has just landed: 
https://gcc.gnu.org/pipermail/gcc-patches/2024-January/643411.html

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


[clang] Add a "don't override" mapping for -fvisibility-from-dllstorageclass (PR #74629)

2024-01-19 Thread via cfe-commits

https://github.com/bd1976bris updated 
https://github.com/llvm/llvm-project/pull/74629

>From 5bae541608ffacfee767da592afe65003ccdad79 Mon Sep 17 00:00:00 2001
From: Ben Dunbobbin 
Date: Wed, 6 Dec 2023 15:47:52 +
Subject: [PATCH 1/3] Add a "don't override" mapping for
 -fvisibility-from-dllstorageclass

`-fvisibility-from-dllstorageclass` allows for overriding the visibility
of globals from their DLL storage class. The visibility to apply can be
customised for the different classes of globals via a set of dependent
options that specify the mapping values:
- `-fvisibility-dllexport=`
- `-fvisibility-nodllstorageclass=`
- `-fvisibility-externs-dllimport=`
- `-fvisibility-externs-nodllstorageclass=`
Currently, one of the existing LLVM visibilities, `hidden`, `protected`,
`default`, can be used as a mapping value. This change adds a new
mapping value: `keep`, which specifies that the visibility should not
be overridden for that class of globals. The behaviour of
`-fvisibility-from-dllstorageclass` is otherwise unchanged and existing
uses of this set of options will be unaffected.

The background to this change is that currently the PS4 and PS5
compilers effectively ignore visibility - dllimport/export is the
supported method for export control in C/C++ source code. Now, we would
like to support visibility attributes and options in our frontend, in
addition to dllimport/export. To support this, we will override the
visibility of globals with explicit dllimport/export attributes but use
the `keep` setting for globals which do not have an explicit
dllimport/export.

There are also some minor improvements to the existing options:
- Make the LANGOPS `BENIGN` as they don't involve the AST.
- Correct/clarify the help text for the options.
---
 clang/include/clang/Basic/LangOptions.def | 20 ++---
 clang/include/clang/Basic/LangOptions.h   | 11 +++
 clang/include/clang/Driver/Options.td | 23 +++---
 clang/lib/CodeGen/CodeGenModule.cpp   | 81 ---
 .../CodeGenCXX/visibility-dllstorageclass.cpp | 28 ++-
 .../test/Driver/visibility-dllstorageclass.c  | 34 +++-
 6 files changed, 148 insertions(+), 49 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c3d5399905a3fd..1ebe33f7151e87 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -357,16 +357,16 @@ BENIGN_ENUM_LANGOPT(TypeVisibilityMode, Visibility, 3, 
DefaultVisibility,
  "default visibility for types [-ftype-visibility]")
 LANGOPT(SetVisibilityForExternDecls, 1, 0,
 "apply global symbol visibility to external declarations without an 
explicit visibility")
-LANGOPT(VisibilityFromDLLStorageClass, 1, 0,
-"set the visiblity of globals from their DLL storage class 
[-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(DLLExportVisibility, Visibility, 3, DefaultVisibility,
- "visibility for functions and variables with dllexport 
annotations [-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(NoDLLStorageClassVisibility, Visibility, 3, HiddenVisibility,
- "visibility for functions and variables without an explicit DLL 
storage class [-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(ExternDeclDLLImportVisibility, Visibility, 3, DefaultVisibility,
- "visibility for external declarations with dllimport annotations 
[-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, Visibility, 3, 
HiddenVisibility,
- "visibility for external declarations without an explicit DLL 
storage class [-fvisibility-from-dllstorageclass]")
+BENIGN_LANGOPT(VisibilityFromDLLStorageClass, 1, 0,
+   "override the visibility of globals based on their final DLL 
storage class [-fvisibility-from-dllstorageclass]")
+BENIGN_ENUM_LANGOPT(DLLExportVisibility, VisibilityFromDLLStorageClassKinds, 
3, VisibilityFromDLLStorageClassKinds::Default,
+ "how to adjust the visibility for functions and variables with 
dllexport annotations [-fvisibility-dllexport]")
+BENIGN_ENUM_LANGOPT(NoDLLStorageClassVisibility, 
VisibilityFromDLLStorageClassKinds, 3, 
VisibilityFromDLLStorageClassKinds::Hidden,
+ "how to adjust the visibility for functions and variables without 
an explicit DLL storage class [-fvisibility-nodllstorageclass]")
+BENIGN_ENUM_LANGOPT(ExternDeclDLLImportVisibility, 
VisibilityFromDLLStorageClassKinds, 3, 
VisibilityFromDLLStorageClassKinds::Default,
+ "how to adjust the visibility for external declarations with 
dllimport annotations [-fvisibility-externs-dllimport]")
+BENIGN_ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, 
VisibilityFromDLLStorageClassKinds, 3,  
VisibilityFromDLLStorageClassKinds::Hidden,
+ "how to adjust the visibility for external declarations without 
an explicit DLL storage class [-fvisibility-externs-nodllstorageclass]")
 BENIGN_LANGOPT

[clang] [llvm] [RISCV] Relax march string order constraint (PR #78120)

2024-01-19 Thread Fangrui Song via cfe-commits

MaskRay wrote:

> Address the 
> https://github.com/riscv-non-isa/riscv-toolchain-conventions/pull/14
>
> This patch relax the -march string for accept any order.

Perhaps:

Follow https://github.com/riscv-non-isa/riscv-toolchain-conventions/pull/14 by 
dropping the order requirement of `-march`.

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


[compiler-rt] [llvm] [flang] [clang-tools-extra] [clang] [lld] [libc] [libcxx] [lldb] Make clang report invalid target versions for all environment types. (PR #78655)

2024-01-19 Thread via cfe-commits

https://github.com/ZijunZhaoCCK updated 
https://github.com/llvm/llvm-project/pull/78655

>From f440f44e7e270d4636ad39f4e4223c904e496d3a Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Fri, 19 Jan 2024 00:47:05 +
Subject: [PATCH] Make clang report invalid target versions for all
 environment.

Followup for https://github.com/llvm/llvm-project/pull/75373

1. Make this feature not just available for android, but everyone.
2. Correct some target triples/
3. Add opencl to the environment type list.
---
 clang/lib/Driver/Driver.cpp  | 19 ++-
 clang/test/CodeGen/fp128_complex.c   |  2 +-
 clang/test/Driver/mips-features.c|  4 ++--
 clang/test/Frontend/fixed_point_bit_widths.c |  4 ++--
 llvm/include/llvm/TargetParser/Triple.h  |  2 +-
 llvm/lib/TargetParser/Triple.cpp | 14 ++
 6 files changed, 30 insertions(+), 15 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 1889ea28079df1..2d6986d145483b 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1430,15 +1430,16 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
   const ToolChain &TC = getToolChain(
   *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
 
-  if (TC.getTriple().isAndroid()) {
-llvm::Triple Triple = TC.getTriple();
-StringRef TripleVersionName = Triple.getEnvironmentVersionString();
-
-if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "") {
-  Diags.Report(diag::err_drv_triple_version_invalid)
-  << TripleVersionName << TC.getTripleString();
-  ContainsError = true;
-}
+  // Check if the environment version is valid.
+  llvm::Triple Triple = TC.getTriple();
+  StringRef TripleVersionName = Triple.getEnvironmentVersionString();
+  StringRef TripleObjectFormat = 
Triple.getObjectFormatTypeName(Triple.getObjectFormat());
+
+  if (Triple.getEnvironmentVersion().empty() && TripleVersionName != ""
+&& TripleVersionName != TripleObjectFormat) {
+Diags.Report(diag::err_drv_triple_version_invalid)
+<< TripleVersionName << TC.getTripleString();
+ContainsError = true;
   }
 
   // Report warning when arm64EC option is overridden by specified target
diff --git a/clang/test/CodeGen/fp128_complex.c 
b/clang/test/CodeGen/fp128_complex.c
index 48659d22416841..0e87cbe8ce8121 100644
--- a/clang/test/CodeGen/fp128_complex.c
+++ b/clang/test/CodeGen/fp128_complex.c
@@ -1,4 +1,4 @@
-// RUN: %clang -target aarch64-linux-gnuabi %s -S -emit-llvm -o - | FileCheck 
%s
+// RUN: %clang -target aarch64-linux-gnueabi %s -S -emit-llvm -o - | FileCheck 
%s
 
 _Complex long double a, b, c, d;
 void test_fp128_compound_assign(void) {
diff --git a/clang/test/Driver/mips-features.c 
b/clang/test/Driver/mips-features.c
index fad6009ffb89ba..18edcd05ea85c9 100644
--- a/clang/test/Driver/mips-features.c
+++ b/clang/test/Driver/mips-features.c
@@ -400,12 +400,12 @@
 // LONG-CALLS-DEF-NOT: "long-calls"
 //
 // -mbranch-likely
-// RUN: %clang -target -mips-mti-linux-gnu -### -c %s -mbranch-likely 2>&1 \
+// RUN: %clang -target mips-mti-linux-gnu -### -c %s -mbranch-likely 2>&1 \
 // RUN:   | FileCheck --check-prefix=BRANCH-LIKELY %s
 // BRANCH-LIKELY: argument unused during compilation: '-mbranch-likely'
 //
 // -mno-branch-likely
-// RUN: %clang -target -mips-mti-linux-gnu -### -c %s -mno-branch-likely 2>&1 \
+// RUN: %clang -target mips-mti-linux-gnu -### -c %s -mno-branch-likely 2>&1 \
 // RUN:   | FileCheck --check-prefix=NO-BRANCH-LIKELY %s
 // NO-BRANCH-LIKELY: argument unused during compilation: '-mno-branch-likely'
 
diff --git a/clang/test/Frontend/fixed_point_bit_widths.c 
b/clang/test/Frontend/fixed_point_bit_widths.c
index ac8db49ed516ae..e56f787e824f24 100644
--- a/clang/test/Frontend/fixed_point_bit_widths.c
+++ b/clang/test/Frontend/fixed_point_bit_widths.c
@@ -1,7 +1,7 @@
 // RUN: %clang -x c -ffixed-point -S -emit-llvm -o - %s | FileCheck %s
-// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - 
--target=x86_64-scei-ps4-ubuntu-fast %s | FileCheck %s
+// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - --target=x86_64-scei-ps4 
%s | FileCheck %s
 // RUN: %clang -x c -ffixed-point -S -emit-llvm -o - --target=ppc64 %s | 
FileCheck %s
-// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - 
--target=x86_64-scei-ps4-windows10pro-fast %s | FileCheck %s
+// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - --target=x86_64-scei-ps4 
%s | FileCheck %s
 
 /* Primary signed _Accum */
 
diff --git a/llvm/include/llvm/TargetParser/Triple.h 
b/llvm/include/llvm/TargetParser/Triple.h
index 95014a546f7245..525ea6df3643ca 100644
--- a/llvm/include/llvm/TargetParser/Triple.h
+++ b/llvm/include/llvm/TargetParser/Triple.h
@@ -273,7 +273,7 @@ class Triple {
 Callable,
 Mesh,
 Amplification,
-
+OpenCL,
 OpenHOS,
 
 LastEnvironmentType = OpenHOS
diff --git a/llvm/lib/TargetParser/Triple.cpp b/llvm/lib/TargetParser/Triple.cpp
index b9

[clang] [llvm] [RISCV] Relax march string order constraint (PR #78120)

2024-01-19 Thread Fangrui Song via cfe-commits


@@ -337,10 +319,79 @@ TEST(ParseArchString, 
AcceptsUnderscoreSplittingExtensions) {
   }
 }
 
+TEST(ParseArchString, AcceptsRelaxSingleLetterExtensions) {
+  for (StringRef Input :
+   {"rv32imfad", "rv32im_fa_d", "rv32im2p0fad", "rv32i2p1m2p0fad"}) {
+auto MaybeISAInfo = RISCVISAInfo::parseArchString(Input, true);
+ASSERT_THAT_EXPECTED(MaybeISAInfo, Succeeded());
+RISCVISAInfo::OrderedExtensionMap Exts = (*MaybeISAInfo)->getExtensions();
+EXPECT_EQ(Exts.size(), 6UL);
+EXPECT_EQ(Exts.count("i"), 1U);
+EXPECT_EQ(Exts.count("m"), 1U);
+EXPECT_EQ(Exts.count("f"), 1U);
+EXPECT_EQ(Exts.count("a"), 1U);
+EXPECT_EQ(Exts.count("d"), 1U);
+EXPECT_EQ(Exts.count("zicsr"), 1U);
+  }
+}
+
+TEST(ParseArchString, AcceptsRelaxMixedLetterExtensions) {
+  for (StringRef Input :
+   {"rv32i_zihintntl_m_a_f_d_svinval", "rv32izihintntl_mafdsvinval",
+"rv32i_zihintntl_mafd_svinval"}) {
+auto MaybeISAInfo = RISCVISAInfo::parseArchString(Input, true);
+ASSERT_THAT_EXPECTED(MaybeISAInfo, Succeeded());
+RISCVISAInfo::OrderedExtensionMap Exts = (*MaybeISAInfo)->getExtensions();
+EXPECT_EQ(Exts.size(), 8UL);
+EXPECT_EQ(Exts.count("i"), 1U);
+EXPECT_EQ(Exts.count("m"), 1U);
+EXPECT_EQ(Exts.count("a"), 1U);
+EXPECT_EQ(Exts.count("f"), 1U);
+EXPECT_EQ(Exts.count("d"), 1U);
+EXPECT_EQ(Exts.count("zihintntl"), 1U);
+EXPECT_EQ(Exts.count("svinval"), 1U);
+EXPECT_EQ(Exts.count("zicsr"), 1U);
+  }
+}
+
+TEST(ParseArchString, AcceptsAmbiguousFromRelaxExtensions) {
+  for (StringRef Input : {"rv32i_zba_m", "rv32izba_m", "rv32izba1p0_m2p0"}) {

MaskRay wrote:

Consider another test where i is after zba

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


[llvm] [clang] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-19 Thread Jonas Paulsson via cfe-commits


@@ -11,6 +11,7 @@
 
//===--===//
 
 #include "SystemZ.h"
+#include "clang/AST/Decl.h"

JonPsson1 wrote:

Ok, that makes more sense to me know considering different ways of building 
clang, thanks.

Patch updated: I tried to follow your suggestion by splitting up the work and 
basically inspecting the VarDecl in ASTContext and then pass only a boolean to 
TargetInfo.  Is this something like what you had in mind?


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


[libcxx] [llvm] [compiler-rt] [clang] [libc] [lld] [lldb] [clang-tools-extra] [flang] Make clang report invalid target versions for all environment types. (PR #78655)

2024-01-19 Thread via cfe-commits

https://github.com/ZijunZhaoCCK updated 
https://github.com/llvm/llvm-project/pull/78655

>From f440f44e7e270d4636ad39f4e4223c904e496d3a Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Fri, 19 Jan 2024 00:47:05 +
Subject: [PATCH] Make clang report invalid target versions for all
 environment.

Followup for https://github.com/llvm/llvm-project/pull/75373

1. Make this feature not just available for android, but everyone.
2. Correct some target triples/
3. Add opencl to the environment type list.
---
 clang/lib/Driver/Driver.cpp  | 19 ++-
 clang/test/CodeGen/fp128_complex.c   |  2 +-
 clang/test/Driver/mips-features.c|  4 ++--
 clang/test/Frontend/fixed_point_bit_widths.c |  4 ++--
 llvm/include/llvm/TargetParser/Triple.h  |  2 +-
 llvm/lib/TargetParser/Triple.cpp | 14 ++
 6 files changed, 30 insertions(+), 15 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 1889ea28079df10..2d6986d145483b8 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1430,15 +1430,16 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
   const ToolChain &TC = getToolChain(
   *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
 
-  if (TC.getTriple().isAndroid()) {
-llvm::Triple Triple = TC.getTriple();
-StringRef TripleVersionName = Triple.getEnvironmentVersionString();
-
-if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "") {
-  Diags.Report(diag::err_drv_triple_version_invalid)
-  << TripleVersionName << TC.getTripleString();
-  ContainsError = true;
-}
+  // Check if the environment version is valid.
+  llvm::Triple Triple = TC.getTriple();
+  StringRef TripleVersionName = Triple.getEnvironmentVersionString();
+  StringRef TripleObjectFormat = 
Triple.getObjectFormatTypeName(Triple.getObjectFormat());
+
+  if (Triple.getEnvironmentVersion().empty() && TripleVersionName != ""
+&& TripleVersionName != TripleObjectFormat) {
+Diags.Report(diag::err_drv_triple_version_invalid)
+<< TripleVersionName << TC.getTripleString();
+ContainsError = true;
   }
 
   // Report warning when arm64EC option is overridden by specified target
diff --git a/clang/test/CodeGen/fp128_complex.c 
b/clang/test/CodeGen/fp128_complex.c
index 48659d224168416..0e87cbe8ce81219 100644
--- a/clang/test/CodeGen/fp128_complex.c
+++ b/clang/test/CodeGen/fp128_complex.c
@@ -1,4 +1,4 @@
-// RUN: %clang -target aarch64-linux-gnuabi %s -S -emit-llvm -o - | FileCheck 
%s
+// RUN: %clang -target aarch64-linux-gnueabi %s -S -emit-llvm -o - | FileCheck 
%s
 
 _Complex long double a, b, c, d;
 void test_fp128_compound_assign(void) {
diff --git a/clang/test/Driver/mips-features.c 
b/clang/test/Driver/mips-features.c
index fad6009ffb89bab..18edcd05ea85c9f 100644
--- a/clang/test/Driver/mips-features.c
+++ b/clang/test/Driver/mips-features.c
@@ -400,12 +400,12 @@
 // LONG-CALLS-DEF-NOT: "long-calls"
 //
 // -mbranch-likely
-// RUN: %clang -target -mips-mti-linux-gnu -### -c %s -mbranch-likely 2>&1 \
+// RUN: %clang -target mips-mti-linux-gnu -### -c %s -mbranch-likely 2>&1 \
 // RUN:   | FileCheck --check-prefix=BRANCH-LIKELY %s
 // BRANCH-LIKELY: argument unused during compilation: '-mbranch-likely'
 //
 // -mno-branch-likely
-// RUN: %clang -target -mips-mti-linux-gnu -### -c %s -mno-branch-likely 2>&1 \
+// RUN: %clang -target mips-mti-linux-gnu -### -c %s -mno-branch-likely 2>&1 \
 // RUN:   | FileCheck --check-prefix=NO-BRANCH-LIKELY %s
 // NO-BRANCH-LIKELY: argument unused during compilation: '-mno-branch-likely'
 
diff --git a/clang/test/Frontend/fixed_point_bit_widths.c 
b/clang/test/Frontend/fixed_point_bit_widths.c
index ac8db49ed516aef..e56f787e824f24a 100644
--- a/clang/test/Frontend/fixed_point_bit_widths.c
+++ b/clang/test/Frontend/fixed_point_bit_widths.c
@@ -1,7 +1,7 @@
 // RUN: %clang -x c -ffixed-point -S -emit-llvm -o - %s | FileCheck %s
-// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - 
--target=x86_64-scei-ps4-ubuntu-fast %s | FileCheck %s
+// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - --target=x86_64-scei-ps4 
%s | FileCheck %s
 // RUN: %clang -x c -ffixed-point -S -emit-llvm -o - --target=ppc64 %s | 
FileCheck %s
-// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - 
--target=x86_64-scei-ps4-windows10pro-fast %s | FileCheck %s
+// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - --target=x86_64-scei-ps4 
%s | FileCheck %s
 
 /* Primary signed _Accum */
 
diff --git a/llvm/include/llvm/TargetParser/Triple.h 
b/llvm/include/llvm/TargetParser/Triple.h
index 95014a546f72453..525ea6df3643ca6 100644
--- a/llvm/include/llvm/TargetParser/Triple.h
+++ b/llvm/include/llvm/TargetParser/Triple.h
@@ -273,7 +273,7 @@ class Triple {
 Callable,
 Mesh,
 Amplification,
-
+OpenCL,
 OpenHOS,
 
 LastEnvironmentType = OpenHOS
diff --git a/llvm/lib/TargetParser/Triple.cpp b/llvm/lib/TargetParser/Triple.cp

[clang] [openmp] [OpenMP][USM] Introduces -fopenmp-force-usm flag (PR #76571)

2024-01-19 Thread Jan Patrick Lehr via cfe-commits

https://github.com/jplehr updated 
https://github.com/llvm/llvm-project/pull/76571

>From 41b227e2c84b3c7eeedb6a9ebf559bec2c34aec3 Mon Sep 17 00:00:00 2001
From: JP Lehr 
Date: Fri, 29 Dec 2023 04:32:24 -0500
Subject: [PATCH] [OpenMP][USM] Introduces -fopenmp-force-usm flag

This flag forces the compiler to generate code for OpenMP target regions
as if the user specified the #pragma omp requires unified_shared_memory
in each source file.

The option does not have a -fno-* friend since OpenMP requires the
unified_shared_memory clause to be present in all source files. Since
this flag does no harm if the clause is present, it can be used in
conjunction. My understanding is that USM should not be turned off
selectively, hence, no -fno- version.

This adds a basic test to check the correct generation of double
indirect access to declare target globals in USM mode vs non-USM mode.
Which I think is the only difference observable in code generation.

This runtime test checks for the (non-)occurence of data movement between host
and device. It does one run without the flag and one with the flag to
also see that both versions behave as expected. In the case w/o the new
flag data movement between host and device is expected. In the case with
the flag such data movement should not be present / reported.
---
 clang/include/clang/Basic/LangOptions.def |  1 +
 clang/include/clang/Driver/Options.td |  4 +
 clang/lib/CodeGen/CGOpenMPRuntime.cpp |  7 ++
 clang/lib/Driver/ToolChains/Clang.cpp |  2 +
 clang/test/OpenMP/force-usm.c | 74 +++
 openmp/libomptarget/test/lit.cfg  |  8 ++
 .../test/offloading/force-usm.cpp | 59 +++
 7 files changed, 155 insertions(+)
 create mode 100644 clang/test/OpenMP/force-usm.c
 create mode 100644 openmp/libomptarget/test/offloading/force-usm.cpp

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 21abc346cf17ac..81cf2ad9498a7f 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -260,6 +260,7 @@ LANGOPT(OpenMPTeamSubscription  , 1, 0, "Assume distributed 
loops do not have mo
 LANGOPT(OpenMPNoThreadState  , 1, 0, "Assume that no thread in a parallel 
region will modify an ICV.")
 LANGOPT(OpenMPNoNestedParallelism  , 1, 0, "Assume that no thread in a 
parallel region will encounter a parallel region")
 LANGOPT(OpenMPOffloadMandatory  , 1, 0, "Assert that offloading is mandatory 
and do not create a host fallback.")
+LANGOPT(OpenMPForceUSM , 1, 0, "Enable OpenMP unified shared memory mode 
via compiler.")
 LANGOPT(NoGPULib  , 1, 0, "Indicate a build without the standard GPU 
libraries.")
 LANGOPT(RenderScript  , 1, 0, "RenderScript")
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 2b93ddf033499c..28290da438c62d 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3451,6 +3451,10 @@ def fopenmp_offload_mandatory : Flag<["-"], 
"fopenmp-offload-mandatory">, Group<
   Flags<[NoArgumentUnused]>, Visibility<[ClangOption, CC1Option]>,
   HelpText<"Do not create a host fallback if offloading to the device fails.">,
   MarshallingInfoFlag>;
+def fopenmp_force_usm : Flag<["-"], "fopenmp-force-usm">, Group,
+  Flags<[NoArgumentUnused]>, Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Force behvaior as if the user specified pragma omp requires 
unified_shared_memory.">,
+  MarshallingInfoFlag>;
 def fopenmp_target_jit : Flag<["-"], "fopenmp-target-jit">, Group,
   Flags<[NoArgumentUnused]>, Visibility<[ClangOption, CLOption]>,
   HelpText<"Emit code that can be JIT compiled for OpenMP offloading. Implies 
-foffload-lto=full">;
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index ea6645a39e8321..4855e7410a015a 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1044,6 +1044,13 @@ CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
  ? CGM.getLangOpts().OMPHostIRFile
  : StringRef{});
   OMPBuilder.setConfig(Config);
+
+  // The user forces the compiler to behave as if omp requires
+  // unified_shared_memory was given.
+  if (CGM.getLangOpts().OpenMPForceUSM) {
+HasRequiresUnifiedSharedMemory = true;
+OMPBuilder.Config.setHasRequiresUnifiedSharedMemory(true);
+  }
 }
 
 void CGOpenMPRuntime::clear() {
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index acfa119805068d..ffc24201ab2e0b 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6382,6 +6382,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
   if (Args.hasArg(options::OPT_fopenmp_offlo

[clang] [clang] Fix behavior of `__is_trivially_relocatable(volatile int)` (PR #77092)

2024-01-19 Thread Amirreza Ashouri via cfe-commits


@@ -2669,6 +2669,8 @@ bool QualType::isTriviallyRelocatableType(const 
ASTContext &Context) const {
 return false;
   } else if (const auto *RD = BaseElementType->getAsRecordDecl()) {
 return RD->canPassInRegisters();
+  } else if (BaseElementType.isTriviallyCopyableType(Context)) {
+return true;
   } else {
 switch (isNonTrivialToPrimitiveDestructiveMove()) {

AMP999 wrote:

You mean why is `isNonTrivialToPrimitiveDestructiveMove` different from 
`isTriviallyRelocatable`? I don't know, but I think it has to do with 
Objective-C, so I left it alone.

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


[clang] Add a "don't override" mapping for -fvisibility-from-dllstorageclass (PR #74629)

2024-01-19 Thread Paul T Robinson via cfe-commits


@@ -79,6 +107,8 @@ extern void __declspec(dllimport) imported_e();
 // EXPLICIT-DAG: declare hidden void @_Z10imported_ev()
 // ALL_DEFAULT-DAG: declare void @_Z1ev()
 // ALL_DEFAULT-DAG: declare void @_Z10imported_ev()
+// ALL_KEEP-DAG: declare hidden void @_Z1ev()
+// ALL_KEEP-DAG: void @_Z10imported_ev()

pogo59 wrote:

Oh, this line looks like it would allow any visibility (missing `declare` and 
whatever might be between that and the `void`)

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


[clang] [flang] [flang]Add support for -moutline-atomics and -mno-outline-atomics (PR #78755)

2024-01-19 Thread Kiran Chandramohan via cfe-commits


@@ -0,0 +1,11 @@
+! Test that flang-new forwards the -moutline-atomics and -mno-outline-atomics.
+! RUN: %flang -moutline-atomics --target=aarch64-none-none -### %s -o %t 2>&1  
| FileCheck %s
+! CHECK: "-target-feature" "+outline-atomics"
+
+! RUN: %flang -mno-outline-atomics --target=aarch64-none-none -### %s -o %t 
2>&1  | FileCheck %s --check-prefix=CHECK-NOOUTLINE
+! CHECK-NOOUTLINE: "-target-feature" "-outline-atomics"
+
+! RUN: %flang -mno-outline-atomics --target=x86-none-none -### %s -o %t 2>&1  
| FileCheck %s --check-prefix=CHECK-ERRMSG
+! CHECK-ERRMSG: warning: 'x86' does not support '-mno-outline-atomics'

kiranchandramohan wrote:

Should there be a test to check the behaviour when no outline flags are 
specified and the target is `aarch64`?

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


[clang] [flang] [flang]Add support for -moutline-atomics and -mno-outline-atomics (PR #78755)

2024-01-19 Thread Kiran Chandramohan via cfe-commits


@@ -354,6 +354,27 @@ void Flang::addTargetOptions(const ArgList &Args,
 CmdArgs.push_back(Args.MakeArgString(CPU));
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
+   options::OPT_mno_outline_atomics)) {
+// Option -moutline-atomics supported for AArch64 target only.
+if (!Triple.isAArch64()) {
+  D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
+  << Triple.getArchName() << A->getOption().getName();
+} else {
+  if (A->getOption().matches(options::OPT_moutline_atomics)) {
+CmdArgs.push_back("-target-feature");
+CmdArgs.push_back("+outline-atomics");
+  } else {
+CmdArgs.push_back("-target-feature");
+CmdArgs.push_back("-outline-atomics");
+  }
+}
+  } else if (Triple.isAArch64() &&
+ getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
+CmdArgs.push_back("-target-feature");
+CmdArgs.push_back("+outline-atomics");
+  }

kiranchandramohan wrote:

Can this code be shared with `Clang` ?

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


[compiler-rt] [llvm] [flang] [clang-tools-extra] [clang] [lld] [libc] [libcxx] [lldb] Make clang report invalid target versions for all environment types. (PR #78655)

2024-01-19 Thread via cfe-commits

https://github.com/ZijunZhaoCCK updated 
https://github.com/llvm/llvm-project/pull/78655

>From f440f44e7e270d4636ad39f4e4223c904e496d3a Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Fri, 19 Jan 2024 00:47:05 +
Subject: [PATCH 1/2] Make clang report invalid target versions for all
 environment.

Followup for https://github.com/llvm/llvm-project/pull/75373

1. Make this feature not just available for android, but everyone.
2. Correct some target triples/
3. Add opencl to the environment type list.
---
 clang/lib/Driver/Driver.cpp  | 19 ++-
 clang/test/CodeGen/fp128_complex.c   |  2 +-
 clang/test/Driver/mips-features.c|  4 ++--
 clang/test/Frontend/fixed_point_bit_widths.c |  4 ++--
 llvm/include/llvm/TargetParser/Triple.h  |  2 +-
 llvm/lib/TargetParser/Triple.cpp | 14 ++
 6 files changed, 30 insertions(+), 15 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 1889ea28079df1..2d6986d145483b 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1430,15 +1430,16 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
   const ToolChain &TC = getToolChain(
   *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
 
-  if (TC.getTriple().isAndroid()) {
-llvm::Triple Triple = TC.getTriple();
-StringRef TripleVersionName = Triple.getEnvironmentVersionString();
-
-if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "") {
-  Diags.Report(diag::err_drv_triple_version_invalid)
-  << TripleVersionName << TC.getTripleString();
-  ContainsError = true;
-}
+  // Check if the environment version is valid.
+  llvm::Triple Triple = TC.getTriple();
+  StringRef TripleVersionName = Triple.getEnvironmentVersionString();
+  StringRef TripleObjectFormat = 
Triple.getObjectFormatTypeName(Triple.getObjectFormat());
+
+  if (Triple.getEnvironmentVersion().empty() && TripleVersionName != ""
+&& TripleVersionName != TripleObjectFormat) {
+Diags.Report(diag::err_drv_triple_version_invalid)
+<< TripleVersionName << TC.getTripleString();
+ContainsError = true;
   }
 
   // Report warning when arm64EC option is overridden by specified target
diff --git a/clang/test/CodeGen/fp128_complex.c 
b/clang/test/CodeGen/fp128_complex.c
index 48659d22416841..0e87cbe8ce8121 100644
--- a/clang/test/CodeGen/fp128_complex.c
+++ b/clang/test/CodeGen/fp128_complex.c
@@ -1,4 +1,4 @@
-// RUN: %clang -target aarch64-linux-gnuabi %s -S -emit-llvm -o - | FileCheck 
%s
+// RUN: %clang -target aarch64-linux-gnueabi %s -S -emit-llvm -o - | FileCheck 
%s
 
 _Complex long double a, b, c, d;
 void test_fp128_compound_assign(void) {
diff --git a/clang/test/Driver/mips-features.c 
b/clang/test/Driver/mips-features.c
index fad6009ffb89ba..18edcd05ea85c9 100644
--- a/clang/test/Driver/mips-features.c
+++ b/clang/test/Driver/mips-features.c
@@ -400,12 +400,12 @@
 // LONG-CALLS-DEF-NOT: "long-calls"
 //
 // -mbranch-likely
-// RUN: %clang -target -mips-mti-linux-gnu -### -c %s -mbranch-likely 2>&1 \
+// RUN: %clang -target mips-mti-linux-gnu -### -c %s -mbranch-likely 2>&1 \
 // RUN:   | FileCheck --check-prefix=BRANCH-LIKELY %s
 // BRANCH-LIKELY: argument unused during compilation: '-mbranch-likely'
 //
 // -mno-branch-likely
-// RUN: %clang -target -mips-mti-linux-gnu -### -c %s -mno-branch-likely 2>&1 \
+// RUN: %clang -target mips-mti-linux-gnu -### -c %s -mno-branch-likely 2>&1 \
 // RUN:   | FileCheck --check-prefix=NO-BRANCH-LIKELY %s
 // NO-BRANCH-LIKELY: argument unused during compilation: '-mno-branch-likely'
 
diff --git a/clang/test/Frontend/fixed_point_bit_widths.c 
b/clang/test/Frontend/fixed_point_bit_widths.c
index ac8db49ed516ae..e56f787e824f24 100644
--- a/clang/test/Frontend/fixed_point_bit_widths.c
+++ b/clang/test/Frontend/fixed_point_bit_widths.c
@@ -1,7 +1,7 @@
 // RUN: %clang -x c -ffixed-point -S -emit-llvm -o - %s | FileCheck %s
-// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - 
--target=x86_64-scei-ps4-ubuntu-fast %s | FileCheck %s
+// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - --target=x86_64-scei-ps4 
%s | FileCheck %s
 // RUN: %clang -x c -ffixed-point -S -emit-llvm -o - --target=ppc64 %s | 
FileCheck %s
-// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - 
--target=x86_64-scei-ps4-windows10pro-fast %s | FileCheck %s
+// RUN: %clang -x c -ffixed-point -S -emit-llvm -o - --target=x86_64-scei-ps4 
%s | FileCheck %s
 
 /* Primary signed _Accum */
 
diff --git a/llvm/include/llvm/TargetParser/Triple.h 
b/llvm/include/llvm/TargetParser/Triple.h
index 95014a546f7245..525ea6df3643ca 100644
--- a/llvm/include/llvm/TargetParser/Triple.h
+++ b/llvm/include/llvm/TargetParser/Triple.h
@@ -273,7 +273,7 @@ class Triple {
 Callable,
 Mesh,
 Amplification,
-
+OpenCL,
 OpenHOS,
 
 LastEnvironmentType = OpenHOS
diff --git a/llvm/lib/TargetParser/Triple.cpp b/llvm/lib/TargetParser/Triple.cpp
inde

[clang] Add a "don't override" mapping for -fvisibility-from-dllstorageclass (PR #74629)

2024-01-19 Thread via cfe-commits

https://github.com/bd1976bris updated 
https://github.com/llvm/llvm-project/pull/74629

>From 5bae541608ffacfee767da592afe65003ccdad79 Mon Sep 17 00:00:00 2001
From: Ben Dunbobbin 
Date: Wed, 6 Dec 2023 15:47:52 +
Subject: [PATCH 1/4] Add a "don't override" mapping for
 -fvisibility-from-dllstorageclass

`-fvisibility-from-dllstorageclass` allows for overriding the visibility
of globals from their DLL storage class. The visibility to apply can be
customised for the different classes of globals via a set of dependent
options that specify the mapping values:
- `-fvisibility-dllexport=`
- `-fvisibility-nodllstorageclass=`
- `-fvisibility-externs-dllimport=`
- `-fvisibility-externs-nodllstorageclass=`
Currently, one of the existing LLVM visibilities, `hidden`, `protected`,
`default`, can be used as a mapping value. This change adds a new
mapping value: `keep`, which specifies that the visibility should not
be overridden for that class of globals. The behaviour of
`-fvisibility-from-dllstorageclass` is otherwise unchanged and existing
uses of this set of options will be unaffected.

The background to this change is that currently the PS4 and PS5
compilers effectively ignore visibility - dllimport/export is the
supported method for export control in C/C++ source code. Now, we would
like to support visibility attributes and options in our frontend, in
addition to dllimport/export. To support this, we will override the
visibility of globals with explicit dllimport/export attributes but use
the `keep` setting for globals which do not have an explicit
dllimport/export.

There are also some minor improvements to the existing options:
- Make the LANGOPS `BENIGN` as they don't involve the AST.
- Correct/clarify the help text for the options.
---
 clang/include/clang/Basic/LangOptions.def | 20 ++---
 clang/include/clang/Basic/LangOptions.h   | 11 +++
 clang/include/clang/Driver/Options.td | 23 +++---
 clang/lib/CodeGen/CodeGenModule.cpp   | 81 ---
 .../CodeGenCXX/visibility-dllstorageclass.cpp | 28 ++-
 .../test/Driver/visibility-dllstorageclass.c  | 34 +++-
 6 files changed, 148 insertions(+), 49 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c3d5399905a3fd..1ebe33f7151e87 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -357,16 +357,16 @@ BENIGN_ENUM_LANGOPT(TypeVisibilityMode, Visibility, 3, 
DefaultVisibility,
  "default visibility for types [-ftype-visibility]")
 LANGOPT(SetVisibilityForExternDecls, 1, 0,
 "apply global symbol visibility to external declarations without an 
explicit visibility")
-LANGOPT(VisibilityFromDLLStorageClass, 1, 0,
-"set the visiblity of globals from their DLL storage class 
[-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(DLLExportVisibility, Visibility, 3, DefaultVisibility,
- "visibility for functions and variables with dllexport 
annotations [-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(NoDLLStorageClassVisibility, Visibility, 3, HiddenVisibility,
- "visibility for functions and variables without an explicit DLL 
storage class [-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(ExternDeclDLLImportVisibility, Visibility, 3, DefaultVisibility,
- "visibility for external declarations with dllimport annotations 
[-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, Visibility, 3, 
HiddenVisibility,
- "visibility for external declarations without an explicit DLL 
storage class [-fvisibility-from-dllstorageclass]")
+BENIGN_LANGOPT(VisibilityFromDLLStorageClass, 1, 0,
+   "override the visibility of globals based on their final DLL 
storage class [-fvisibility-from-dllstorageclass]")
+BENIGN_ENUM_LANGOPT(DLLExportVisibility, VisibilityFromDLLStorageClassKinds, 
3, VisibilityFromDLLStorageClassKinds::Default,
+ "how to adjust the visibility for functions and variables with 
dllexport annotations [-fvisibility-dllexport]")
+BENIGN_ENUM_LANGOPT(NoDLLStorageClassVisibility, 
VisibilityFromDLLStorageClassKinds, 3, 
VisibilityFromDLLStorageClassKinds::Hidden,
+ "how to adjust the visibility for functions and variables without 
an explicit DLL storage class [-fvisibility-nodllstorageclass]")
+BENIGN_ENUM_LANGOPT(ExternDeclDLLImportVisibility, 
VisibilityFromDLLStorageClassKinds, 3, 
VisibilityFromDLLStorageClassKinds::Default,
+ "how to adjust the visibility for external declarations with 
dllimport annotations [-fvisibility-externs-dllimport]")
+BENIGN_ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, 
VisibilityFromDLLStorageClassKinds, 3,  
VisibilityFromDLLStorageClassKinds::Hidden,
+ "how to adjust the visibility for external declarations without 
an explicit DLL storage class [-fvisibility-externs-nodllstorageclass]")
 BENIGN_LANGOPT

[clang] Add a "don't override" mapping for -fvisibility-from-dllstorageclass (PR #74629)

2024-01-19 Thread via cfe-commits


@@ -79,6 +107,8 @@ extern void __declspec(dllimport) imported_e();
 // EXPLICIT-DAG: declare hidden void @_Z10imported_ev()
 // ALL_DEFAULT-DAG: declare void @_Z1ev()
 // ALL_DEFAULT-DAG: declare void @_Z10imported_ev()
+// ALL_KEEP-DAG: declare hidden void @_Z1ev()
+// ALL_KEEP-DAG: void @_Z10imported_ev()

bd1976bris wrote:

Yes. Thanks the declare is missing here. I have added it back.

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


[compiler-rt] [clang] [llvm] [AArch64][FMV] Support feature MOPS in Function Multi Versioning. (PR #78788)

2024-01-19 Thread Alexandros Lamprineas via cfe-commits

https://github.com/labrinea created 
https://github.com/llvm/llvm-project/pull/78788

The patch adds support for FEAT_MOPS (Memory Copy and Memory Set instructions) 
in Function Multi Versioning. The bits [19:16] of the system register 
ID_AA64ISAR2_EL1 indicate whether FEAT_MOPS is implemented in AArch64 state.

>From bbf4a8885905a03a614af1d5010347f5ae42f08e Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Fri, 19 Jan 2024 21:07:46 +
Subject: [PATCH] [AArch64][FMV] Support feature MOPS in Function Multi
 Versioning.

The patch adds support for FEAT_MOPS (Memory Copy and Memory Set
instructions) in Function Multi Versioning. The bits [19:16] of
the system register ID_AA64ISAR2_EL1 indicate whether FEAT_MOPS
is implemented in AArch64 state.
---
 clang/test/CodeGen/attr-target-version.c  | 30 +--
 clang/test/Sema/attr-target-clones-aarch64.c  |  2 +-
 clang/test/SemaCXX/attr-target-version.cpp|  1 +
 compiler-rt/lib/builtins/cpu_model/aarch64.c  |  1 +
 .../builtins/cpu_model/aarch64/fmv/mrs.inc|  5 
 .../llvm/TargetParser/AArch64TargetParser.h   |  3 +-
 6 files changed, 25 insertions(+), 17 deletions(-)

diff --git a/clang/test/CodeGen/attr-target-version.c 
b/clang/test/CodeGen/attr-target-version.c
index a7cd6f7bf802c5..fb8834b46b9104 100644
--- a/clang/test/CodeGen/attr-target-version.c
+++ b/clang/test/CodeGen/attr-target-version.c
@@ -35,7 +35,7 @@ inline int __attribute__((target_version("sve+sve-bf16"))) 
fmv_inline(void) { re
 inline int __attribute__((target_version("sve2-aes+sve2-sha3"))) 
fmv_inline(void) { return 5; }
 inline int __attribute__((target_version("sve2+sve2-pmull128+sve2-bitperm"))) 
fmv_inline(void) { return 9; }
 inline int __attribute__((target_version("sve2-sm4+memtag2"))) 
fmv_inline(void) { return 10; }
-inline int __attribute__((target_version("memtag3+rcpc3"))) fmv_inline(void) { 
return 11; }
+inline int __attribute__((target_version("memtag3+rcpc3+mops"))) 
fmv_inline(void) { return 11; }
 inline int __attribute__((target_version("default"))) fmv_inline(void) { 
return 3; }
 
 __attribute__((target_version("ls64"))) int fmv_e(void);
@@ -265,36 +265,36 @@ int hoo(void) {
 // CHECK-NEXT:ret ptr @fmv_inline._Mfp16Mfp16MfcmaMsme
 // CHECK:   resolver_else:
 // CHECK-NEXT:[[TMP4:%.*]] = load i64, ptr @__aarch64_cpu_features, align 8
-// CHECK-NEXT:[[TMP5:%.*]] = and i64 [[TMP4]], 893353197568
-// CHECK-NEXT:[[TMP6:%.*]] = icmp eq i64 [[TMP5]], 893353197568
+// CHECK-NEXT:[[TMP5:%.*]] = and i64 [[TMP4]], 864726312827224064
+// CHECK-NEXT:[[TMP6:%.*]] = icmp eq i64 [[TMP5]], 864726312827224064
 // CHECK-NEXT:[[TMP7:%.*]] = and i1 true, [[TMP6]]
 // CHECK-NEXT:br i1 [[TMP7]], label [[RESOLVER_RETURN1:%.*]], label 
[[RESOLVER_ELSE2:%.*]]
 // CHECK:   resolver_return1:
-// CHECK-NEXT:ret ptr @fmv_inline._Msve2Msve2-pmull128Msve2-bitperm
+// CHECK-NEXT:ret ptr @fmv_inline._Mrcpc3Mmemtag3Mmops
 // CHECK:   resolver_else2:
 // CHECK-NEXT:[[TMP8:%.*]] = load i64, ptr @__aarch64_cpu_features, align 8
-// CHECK-NEXT:[[TMP9:%.*]] = and i64 [[TMP8]], 34359773184
-// CHECK-NEXT:[[TMP10:%.*]] = icmp eq i64 [[TMP9]], 34359773184
+// CHECK-NEXT:[[TMP9:%.*]] = and i64 [[TMP8]], 893353197568
+// CHECK-NEXT:[[TMP10:%.*]] = icmp eq i64 [[TMP9]], 893353197568
 // CHECK-NEXT:[[TMP11:%.*]] = and i1 true, [[TMP10]]
 // CHECK-NEXT:br i1 [[TMP11]], label [[RESOLVER_RETURN3:%.*]], label 
[[RESOLVER_ELSE4:%.*]]
 // CHECK:   resolver_return3:
-// CHECK-NEXT:ret ptr @fmv_inline._Msha1MpmullMf64mm
+// CHECK-NEXT:ret ptr @fmv_inline._Msve2Msve2-pmull128Msve2-bitperm
 // CHECK:   resolver_else4:
 // CHECK-NEXT:[[TMP12:%.*]] = load i64, ptr @__aarch64_cpu_features, align 
8
-// CHECK-NEXT:[[TMP13:%.*]] = and i64 [[TMP12]], 17246986240
-// CHECK-NEXT:[[TMP14:%.*]] = icmp eq i64 [[TMP13]], 17246986240
+// CHECK-NEXT:[[TMP13:%.*]] = and i64 [[TMP12]], 34359773184
+// CHECK-NEXT:[[TMP14:%.*]] = icmp eq i64 [[TMP13]], 34359773184
 // CHECK-NEXT:[[TMP15:%.*]] = and i1 true, [[TMP14]]
 // CHECK-NEXT:br i1 [[TMP15]], label [[RESOLVER_RETURN5:%.*]], label 
[[RESOLVER_ELSE6:%.*]]
 // CHECK:   resolver_return5:
-// CHECK-NEXT:ret ptr @fmv_inline._Msha3Mi8mmMf32mm
+// CHECK-NEXT:ret ptr @fmv_inline._Msha1MpmullMf64mm
 // CHECK:   resolver_else6:
 // CHECK-NEXT:[[TMP16:%.*]] = load i64, ptr @__aarch64_cpu_features, align 
8
-// CHECK-NEXT:[[TMP17:%.*]] = and i64 [[TMP16]], 288265560523800576
-// CHECK-NEXT:[[TMP18:%.*]] = icmp eq i64 [[TMP17]], 288265560523800576
+// CHECK-NEXT:[[TMP17:%.*]] = and i64 [[TMP16]], 17246986240
+// CHECK-NEXT:[[TMP18:%.*]] = icmp eq i64 [[TMP17]], 17246986240
 // CHECK-NEXT:[[TMP19:%.*]] = and i1 true, [[TMP18]]
 // CHECK-NEXT:br i1 [[TMP19]], label [[RESOLVER_RETURN7:%.*]], label 
[[RESOLVER_ELSE8:%.*]]
 // CHECK:   resolver_return7:
-// CHECK-NEXT:ret ptr @fmv_inline._Mrcp

[compiler-rt] [clang] [llvm] [AArch64][FMV] Support feature MOPS in Function Multi Versioning. (PR #78788)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alexandros Lamprineas (labrinea)


Changes

The patch adds support for FEAT_MOPS (Memory Copy and Memory Set instructions) 
in Function Multi Versioning. The bits [19:16] of the system register 
ID_AA64ISAR2_EL1 indicate whether FEAT_MOPS is implemented in AArch64 state.

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


6 Files Affected:

- (modified) clang/test/CodeGen/attr-target-version.c (+15-15) 
- (modified) clang/test/Sema/attr-target-clones-aarch64.c (+1-1) 
- (modified) clang/test/SemaCXX/attr-target-version.cpp (+1) 
- (modified) compiler-rt/lib/builtins/cpu_model/aarch64.c (+1) 
- (modified) compiler-rt/lib/builtins/cpu_model/aarch64/fmv/mrs.inc (+5) 
- (modified) llvm/include/llvm/TargetParser/AArch64TargetParser.h (+2-1) 


``diff
diff --git a/clang/test/CodeGen/attr-target-version.c 
b/clang/test/CodeGen/attr-target-version.c
index a7cd6f7bf802c5..fb8834b46b9104 100644
--- a/clang/test/CodeGen/attr-target-version.c
+++ b/clang/test/CodeGen/attr-target-version.c
@@ -35,7 +35,7 @@ inline int __attribute__((target_version("sve+sve-bf16"))) 
fmv_inline(void) { re
 inline int __attribute__((target_version("sve2-aes+sve2-sha3"))) 
fmv_inline(void) { return 5; }
 inline int __attribute__((target_version("sve2+sve2-pmull128+sve2-bitperm"))) 
fmv_inline(void) { return 9; }
 inline int __attribute__((target_version("sve2-sm4+memtag2"))) 
fmv_inline(void) { return 10; }
-inline int __attribute__((target_version("memtag3+rcpc3"))) fmv_inline(void) { 
return 11; }
+inline int __attribute__((target_version("memtag3+rcpc3+mops"))) 
fmv_inline(void) { return 11; }
 inline int __attribute__((target_version("default"))) fmv_inline(void) { 
return 3; }
 
 __attribute__((target_version("ls64"))) int fmv_e(void);
@@ -265,36 +265,36 @@ int hoo(void) {
 // CHECK-NEXT:ret ptr @fmv_inline._Mfp16Mfp16MfcmaMsme
 // CHECK:   resolver_else:
 // CHECK-NEXT:[[TMP4:%.*]] = load i64, ptr @__aarch64_cpu_features, align 8
-// CHECK-NEXT:[[TMP5:%.*]] = and i64 [[TMP4]], 893353197568
-// CHECK-NEXT:[[TMP6:%.*]] = icmp eq i64 [[TMP5]], 893353197568
+// CHECK-NEXT:[[TMP5:%.*]] = and i64 [[TMP4]], 864726312827224064
+// CHECK-NEXT:[[TMP6:%.*]] = icmp eq i64 [[TMP5]], 864726312827224064
 // CHECK-NEXT:[[TMP7:%.*]] = and i1 true, [[TMP6]]
 // CHECK-NEXT:br i1 [[TMP7]], label [[RESOLVER_RETURN1:%.*]], label 
[[RESOLVER_ELSE2:%.*]]
 // CHECK:   resolver_return1:
-// CHECK-NEXT:ret ptr @fmv_inline._Msve2Msve2-pmull128Msve2-bitperm
+// CHECK-NEXT:ret ptr @fmv_inline._Mrcpc3Mmemtag3Mmops
 // CHECK:   resolver_else2:
 // CHECK-NEXT:[[TMP8:%.*]] = load i64, ptr @__aarch64_cpu_features, align 8
-// CHECK-NEXT:[[TMP9:%.*]] = and i64 [[TMP8]], 34359773184
-// CHECK-NEXT:[[TMP10:%.*]] = icmp eq i64 [[TMP9]], 34359773184
+// CHECK-NEXT:[[TMP9:%.*]] = and i64 [[TMP8]], 893353197568
+// CHECK-NEXT:[[TMP10:%.*]] = icmp eq i64 [[TMP9]], 893353197568
 // CHECK-NEXT:[[TMP11:%.*]] = and i1 true, [[TMP10]]
 // CHECK-NEXT:br i1 [[TMP11]], label [[RESOLVER_RETURN3:%.*]], label 
[[RESOLVER_ELSE4:%.*]]
 // CHECK:   resolver_return3:
-// CHECK-NEXT:ret ptr @fmv_inline._Msha1MpmullMf64mm
+// CHECK-NEXT:ret ptr @fmv_inline._Msve2Msve2-pmull128Msve2-bitperm
 // CHECK:   resolver_else4:
 // CHECK-NEXT:[[TMP12:%.*]] = load i64, ptr @__aarch64_cpu_features, align 
8
-// CHECK-NEXT:[[TMP13:%.*]] = and i64 [[TMP12]], 17246986240
-// CHECK-NEXT:[[TMP14:%.*]] = icmp eq i64 [[TMP13]], 17246986240
+// CHECK-NEXT:[[TMP13:%.*]] = and i64 [[TMP12]], 34359773184
+// CHECK-NEXT:[[TMP14:%.*]] = icmp eq i64 [[TMP13]], 34359773184
 // CHECK-NEXT:[[TMP15:%.*]] = and i1 true, [[TMP14]]
 // CHECK-NEXT:br i1 [[TMP15]], label [[RESOLVER_RETURN5:%.*]], label 
[[RESOLVER_ELSE6:%.*]]
 // CHECK:   resolver_return5:
-// CHECK-NEXT:ret ptr @fmv_inline._Msha3Mi8mmMf32mm
+// CHECK-NEXT:ret ptr @fmv_inline._Msha1MpmullMf64mm
 // CHECK:   resolver_else6:
 // CHECK-NEXT:[[TMP16:%.*]] = load i64, ptr @__aarch64_cpu_features, align 
8
-// CHECK-NEXT:[[TMP17:%.*]] = and i64 [[TMP16]], 288265560523800576
-// CHECK-NEXT:[[TMP18:%.*]] = icmp eq i64 [[TMP17]], 288265560523800576
+// CHECK-NEXT:[[TMP17:%.*]] = and i64 [[TMP16]], 17246986240
+// CHECK-NEXT:[[TMP18:%.*]] = icmp eq i64 [[TMP17]], 17246986240
 // CHECK-NEXT:[[TMP19:%.*]] = and i1 true, [[TMP18]]
 // CHECK-NEXT:br i1 [[TMP19]], label [[RESOLVER_RETURN7:%.*]], label 
[[RESOLVER_ELSE8:%.*]]
 // CHECK:   resolver_return7:
-// CHECK-NEXT:ret ptr @fmv_inline._Mrcpc3Mmemtag3
+// CHECK-NEXT:ret ptr @fmv_inline._Msha3Mi8mmMf32mm
 // CHECK:   resolver_else8:
 // CHECK-NEXT:[[TMP20:%.*]] = load i64, ptr @__aarch64_cpu_features, align 
8
 // CHECK-NEXT:[[TMP21:%.*]] = and i64 [[TMP20]], 19791209299968
@@ -437,7 +437,7 @@ int hoo(void) {
 // CHECK-LABEL: @fmv_inline._Msve2-sm4Mme

[clang] Add a "don't override" mapping for -fvisibility-from-dllstorageclass (PR #74629)

2024-01-19 Thread via cfe-commits

https://github.com/bd1976bris updated 
https://github.com/llvm/llvm-project/pull/74629

>From 5bae541608ffacfee767da592afe65003ccdad79 Mon Sep 17 00:00:00 2001
From: Ben Dunbobbin 
Date: Wed, 6 Dec 2023 15:47:52 +
Subject: [PATCH 1/5] Add a "don't override" mapping for
 -fvisibility-from-dllstorageclass

`-fvisibility-from-dllstorageclass` allows for overriding the visibility
of globals from their DLL storage class. The visibility to apply can be
customised for the different classes of globals via a set of dependent
options that specify the mapping values:
- `-fvisibility-dllexport=`
- `-fvisibility-nodllstorageclass=`
- `-fvisibility-externs-dllimport=`
- `-fvisibility-externs-nodllstorageclass=`
Currently, one of the existing LLVM visibilities, `hidden`, `protected`,
`default`, can be used as a mapping value. This change adds a new
mapping value: `keep`, which specifies that the visibility should not
be overridden for that class of globals. The behaviour of
`-fvisibility-from-dllstorageclass` is otherwise unchanged and existing
uses of this set of options will be unaffected.

The background to this change is that currently the PS4 and PS5
compilers effectively ignore visibility - dllimport/export is the
supported method for export control in C/C++ source code. Now, we would
like to support visibility attributes and options in our frontend, in
addition to dllimport/export. To support this, we will override the
visibility of globals with explicit dllimport/export attributes but use
the `keep` setting for globals which do not have an explicit
dllimport/export.

There are also some minor improvements to the existing options:
- Make the LANGOPS `BENIGN` as they don't involve the AST.
- Correct/clarify the help text for the options.
---
 clang/include/clang/Basic/LangOptions.def | 20 ++---
 clang/include/clang/Basic/LangOptions.h   | 11 +++
 clang/include/clang/Driver/Options.td | 23 +++---
 clang/lib/CodeGen/CodeGenModule.cpp   | 81 ---
 .../CodeGenCXX/visibility-dllstorageclass.cpp | 28 ++-
 .../test/Driver/visibility-dllstorageclass.c  | 34 +++-
 6 files changed, 148 insertions(+), 49 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c3d5399905a3fd..1ebe33f7151e87 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -357,16 +357,16 @@ BENIGN_ENUM_LANGOPT(TypeVisibilityMode, Visibility, 3, 
DefaultVisibility,
  "default visibility for types [-ftype-visibility]")
 LANGOPT(SetVisibilityForExternDecls, 1, 0,
 "apply global symbol visibility to external declarations without an 
explicit visibility")
-LANGOPT(VisibilityFromDLLStorageClass, 1, 0,
-"set the visiblity of globals from their DLL storage class 
[-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(DLLExportVisibility, Visibility, 3, DefaultVisibility,
- "visibility for functions and variables with dllexport 
annotations [-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(NoDLLStorageClassVisibility, Visibility, 3, HiddenVisibility,
- "visibility for functions and variables without an explicit DLL 
storage class [-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(ExternDeclDLLImportVisibility, Visibility, 3, DefaultVisibility,
- "visibility for external declarations with dllimport annotations 
[-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, Visibility, 3, 
HiddenVisibility,
- "visibility for external declarations without an explicit DLL 
storage class [-fvisibility-from-dllstorageclass]")
+BENIGN_LANGOPT(VisibilityFromDLLStorageClass, 1, 0,
+   "override the visibility of globals based on their final DLL 
storage class [-fvisibility-from-dllstorageclass]")
+BENIGN_ENUM_LANGOPT(DLLExportVisibility, VisibilityFromDLLStorageClassKinds, 
3, VisibilityFromDLLStorageClassKinds::Default,
+ "how to adjust the visibility for functions and variables with 
dllexport annotations [-fvisibility-dllexport]")
+BENIGN_ENUM_LANGOPT(NoDLLStorageClassVisibility, 
VisibilityFromDLLStorageClassKinds, 3, 
VisibilityFromDLLStorageClassKinds::Hidden,
+ "how to adjust the visibility for functions and variables without 
an explicit DLL storage class [-fvisibility-nodllstorageclass]")
+BENIGN_ENUM_LANGOPT(ExternDeclDLLImportVisibility, 
VisibilityFromDLLStorageClassKinds, 3, 
VisibilityFromDLLStorageClassKinds::Default,
+ "how to adjust the visibility for external declarations with 
dllimport annotations [-fvisibility-externs-dllimport]")
+BENIGN_ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, 
VisibilityFromDLLStorageClassKinds, 3,  
VisibilityFromDLLStorageClassKinds::Hidden,
+ "how to adjust the visibility for external declarations without 
an explicit DLL storage class [-fvisibility-externs-nodllstorageclass]")
 BENIGN_LANGOPT

[clang] Add a "don't override" mapping for -fvisibility-from-dllstorageclass (PR #74629)

2024-01-19 Thread Paul T Robinson via cfe-commits

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

Re-approving.

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


[clang] 9175dd9 - [CMake] Detect properly new linker introduced in Xcode 15 (#77806)

2024-01-19 Thread via cfe-commits

Author: Eric Miotto
Date: 2024-01-19T16:32:32-05:00
New Revision: 9175dd9cbcad01a47acea9f1b99a0c96bf1a9a29

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

LOG: [CMake] Detect properly new linker introduced in Xcode 15 (#77806)

As explained in [1], this linker is functionally equivalent to the
classic one (`ld64`) for build system purposes -- in particular to 
enable the use of order files to link `clang`. For this reason, in 
addition to fixing the detection rename `LLVM_LINKER_IS_LD64` to 
`LLVM_LINKER_IS_APPLE` to make the result of such detection more 
clear -- this should not cause any issue to downstream users, from 
a quick search in SourceGraph [2], only Swift uses the value of
this variable (which I will take care of updating in due time).

[1]: 
https://developer.apple.com/documentation/xcode-release-notes/xcode-15-release-notes#Linking
[2]: 
https://sourcegraph.com/search?q=context:global+LLVM_LINKER_IS_LD64+lang:cmake+fork:no+-file:AddLLVM.cmake+-file:clang/tools/driver/CMakeLists.txt&patternType=standard&sm=1&groupBy=repo
rdar://120740222

Added: 


Modified: 
clang/tools/driver/CMakeLists.txt
llvm/cmake/modules/AddLLVM.cmake

Removed: 




diff  --git a/clang/tools/driver/CMakeLists.txt 
b/clang/tools/driver/CMakeLists.txt
index 2182486f93a555..d70b92b0984e52 100644
--- a/clang/tools/driver/CMakeLists.txt
+++ b/clang/tools/driver/CMakeLists.txt
@@ -103,10 +103,10 @@ if (APPLE)
 endif()
 
 if(CLANG_ORDER_FILE AND
-(LLVM_LINKER_IS_LD64 OR LLVM_LINKER_IS_GOLD OR LLVM_LINKER_IS_LLD))
+(LLVM_LINKER_IS_APPLE OR LLVM_LINKER_IS_GOLD OR LLVM_LINKER_IS_LLD))
   include(LLVMCheckLinkerFlag)
 
-  if (LLVM_LINKER_IS_LD64 OR (LLVM_LINKER_IS_LLD AND APPLE))
+  if (LLVM_LINKER_IS_APPLE OR (LLVM_LINKER_IS_LLD AND APPLE))
 set(LINKER_ORDER_FILE_OPTION "-Wl,-order_file,${CLANG_ORDER_FILE}")
   elseif (LLVM_LINKER_IS_GOLD)
 set(LINKER_ORDER_FILE_OPTION 
"-Wl,--section-ordering-file,${CLANG_ORDER_FILE}")

diff  --git a/llvm/cmake/modules/AddLLVM.cmake 
b/llvm/cmake/modules/AddLLVM.cmake
index 14c0837c35964d..5e989618552824 100644
--- a/llvm/cmake/modules/AddLLVM.cmake
+++ b/llvm/cmake/modules/AddLLVM.cmake
@@ -211,10 +211,10 @@ if (NOT DEFINED LLVM_LINKER_DETECTED AND NOT WIN32)
 )
 
   if(APPLE)
-if("${stderr}" MATCHES "PROJECT:ld64")
+if("${stderr}" MATCHES "PROGRAM:ld")
   set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
-  set(LLVM_LINKER_IS_LD64 YES CACHE INTERNAL "")
-  message(STATUS "Linker detection: ld64")
+  set(LLVM_LINKER_IS_APPLE YES CACHE INTERNAL "")
+  message(STATUS "Linker detection: Apple")
 elseif("${stderr}" MATCHES "^LLD" OR
"${stdout}" MATCHES "^LLD")
   set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")



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


[clang] [llvm] [CMake] Detect properly new linker introduced in Xcode 15 (PR #77806)

2024-01-19 Thread Louis Dionne via cfe-commits

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


[clang] [llvm] [Clang] Correct __builtin_dynamic_object_size for subobject types (PR #78526)

2024-01-19 Thread Richard Smith via cfe-commits

zygoloid wrote:

> For unions, clang will use the type of the union member with the largest size 
> as the alloca type, regardless of which union member is active. I haven't 
> tried, but your patch will probably compute the subobject size based on that 
> arbitrarily picked member, rather than the one being accessed.

Another concrete case where using the IR type won't work is arrays whose 
initializer is mostly-zeroes. For example, for
```
int arr[20] = {[5] = 6};
```
we give `arr` the IR type `<{ i32, i32, i32, i32, i32, i32, [14 x i32] }>` so 
that we can use a `zeroinitializer` to fill the trailing portion of the array.

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


[llvm] [clang] [Clang] Correct __builtin_dynamic_object_size for subobject types (PR #78526)

2024-01-19 Thread Bill Wendling via cfe-commits

bwendling wrote:

> @bwendling I think you are reading the GCC docs too pedantically. In 
> particular, they also say

> > If there are multiple objects ptr can point to and all of them are known at 
> > compile time, the returned number is the maximum of remaining byte counts 
> > in those objects if type & 2 is 0 and minimum if nonzero.

Isn't this referring to pointing to an object in a union? That's only way this 
makes sense (in C).

> which makes it abundantly clear that what you get is an upper bound or lower 
> bound, respectively. -1 and 0 are just the upper and lower bounds if you have 
> no useful information at all. If you want to check whether the size is 
> _exactly_ known, you'll have to compare both bounds. Outside of doing that, 
> you can never assume that the bound is precise.

I'm still not convinced that it's abundantly clear... but if we want to compare 
max vs. min, things get worse because we return `0` when the `type` is `3` 
(https://godbolt.org/z/4f5onM3W7). So even with checking upper and lower 
bounds, we come away knowing nothing about the size of the object (probably a 
deficiency in Clang).

> Btw, it looks like your initial example gets 48 for both modes on GCC as 
> well? https://c.godbolt.org/z/EfGWv4Wrh

If you remove the `argc = 1;`, you get the difference. Your example might be a 
GCC bug.

> > All of these are explicit in the LLVM IR. Is the worry that they've been 
> > changed from some transformations? Or are there others I'm missing?
> 
> Apart from the fact that what you are doing is simply illegal under our IR 
> semantics, a practical case where this will likely compute incorrect results 
> are unions.

?? I think it's a bit much to say that this is "illegal." We may not get every 
instance of something, but we can certainly determine the size of a struct. If 
by "illegal" you mean determining what a sub-object is, I don't agree but if 
it's so there might be a way to retain whatever information is needed to 
determine what a sub-object is.

> For unions, clang will use the type of the union member with the largest size 
> as the alloca type, regardless of which union member is active. I haven't 
> tried, but your patch will probably compute the subobject size based on that 
> arbitrarily picked member, rather than the one being accessed.

We don't seem to support unions correctly now:

```
$ cat ~/llvm/__bdos3.c
struct suspend_stats {
int failed_resume_noirq;
int last_failed_dev;
union {
  charfailed_devs[2][40];
  charfailed_devs2[38];
};
int last_failed_errno;
int bar;
};

#define report(x) __builtin_printf(#x ": %zu\n", x)

int main(int argc, char *argv[])
{
struct suspend_stats foo;

report(__builtin_dynamic_object_size(&foo.failed_devs2[argc], 0));
report(__builtin_dynamic_object_size(&foo.failed_devs2[argc], 1));

report(__builtin_dynamic_object_size(&foo.failed_devs2[argc], 2));
report(__builtin_dynamic_object_size(&foo.failed_devs2[argc], 3));


return 0;
}
$ clang -O2 ~/llvm/__bdos3.c && ./a.out
__builtin_dynamic_object_size(&foo.failed_devs2[argc], 0): 87
__builtin_dynamic_object_size(&foo.failed_devs2[argc], 1): 87
__builtin_dynamic_object_size(&foo.failed_devs2[argc], 2): 87
__builtin_dynamic_object_size(&foo.failed_devs2[argc], 3): 0
$ gcc -O2 ~/llvm/__bdos3.c && ./a.out
__builtin_dynamic_object_size(&foo.failed_devs2[argc], 0): 87
__builtin_dynamic_object_size(&foo.failed_devs2[argc], 1): 37
__builtin_dynamic_object_size(&foo.failed_devs2[argc], 2): 87
__builtin_dynamic_object_size(&foo.failed_devs2[argc], 3): 37
```

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


[clang] [llvm] [Clang] Correct __builtin_dynamic_object_size for subobject types (PR #78526)

2024-01-19 Thread Bill Wendling via cfe-commits

bwendling wrote:

> > For unions, clang will use the type of the union member with the largest 
> > size as the alloca type, regardless of which union member is active. I 
> > haven't tried, but your patch will probably compute the subobject size 
> > based on that arbitrarily picked member, rather than the one being accessed.
> 
> Another concrete case where using the IR type won't work is arrays whose 
> initializer is mostly-zeroes. For example, for
> 
> ```
> int arr[20] = {[5] = 6};
> ```
> 
> we give `arr` the IR type `<{ i32, i32, i32, i32, i32, i32, [14 x i32] }>` so 
> that we can use a `zeroinitializer` to fill the trailing portion of the array.

My patch only works with structs.

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


[clang] Add a "don't override" mapping for -fvisibility-from-dllstorageclass (PR #74629)

2024-01-19 Thread via cfe-commits

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


[clang] cd05ade - Add a "don't override" mapping for -fvisibility-from-dllstorageclass (#74629)

2024-01-19 Thread via cfe-commits

Author: bd1976bris
Date: 2024-01-19T21:57:40Z
New Revision: cd05ade13a66d4fb2daff489b2c02ac1ae2070d1

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

LOG: Add a "don't override" mapping for -fvisibility-from-dllstorageclass 
(#74629)

`-fvisibility-from-dllstorageclass` allows for overriding the visibility
of globals from their DLL storage class. The visibility to apply can be
customised for the different classes of globals via a set of dependent
options that specify the mapping values:
- `-fvisibility-dllexport=`
- `-fvisibility-nodllstorageclass=`
- `-fvisibility-externs-dllimport=`
- `-fvisibility-externs-nodllstorageclass=` 

Currently, one of the existing LLVM visibilities, `hidden`, `protected`,
`default`, can be used as a mapping value. This change adds a new
mapping value: `keep`, which specifies that the visibility should not be
overridden for that class of globals. The behaviour of
`-fvisibility-from-dllstorageclass` is otherwise unchanged and existing
uses of this set of options will be unaffected.

The background to this change is that currently the PS4 and PS5
compilers effectively ignore visibility - dllimport/export is the
supported method for export control in C/C++ source code. Now, we would
like to support visibility attributes and options in our frontend, in
addition to dllimport/export. To support this, we will override the
visibility of globals with explicit dllimport/export annotations but use
the `keep` setting for globals which do not have an explicit
dllimport/export.

There are also some minor improvements to the existing options:
- Make the `LANGOPS` `BENIGN` as they don't involve the AST.
- Correct/clarify the help text for the options.

Added: 


Modified: 
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Basic/LangOptions.h
clang/include/clang/Driver/Options.td
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGenCXX/visibility-dllstorageclass.cpp
clang/test/Driver/visibility-dllstorageclass.c

Removed: 




diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 04ebffbcba69db..f181da9aea6f97 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -359,16 +359,16 @@ BENIGN_ENUM_LANGOPT(TypeVisibilityMode, Visibility, 3, 
DefaultVisibility,
  "default visibility for types [-ftype-visibility]")
 LANGOPT(SetVisibilityForExternDecls, 1, 0,
 "apply global symbol visibility to external declarations without an 
explicit visibility")
-LANGOPT(VisibilityFromDLLStorageClass, 1, 0,
-"set the visiblity of globals from their DLL storage class 
[-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(DLLExportVisibility, Visibility, 3, DefaultVisibility,
- "visibility for functions and variables with dllexport 
annotations [-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(NoDLLStorageClassVisibility, Visibility, 3, HiddenVisibility,
- "visibility for functions and variables without an explicit DLL 
storage class [-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(ExternDeclDLLImportVisibility, Visibility, 3, DefaultVisibility,
- "visibility for external declarations with dllimport annotations 
[-fvisibility-from-dllstorageclass]")
-ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, Visibility, 3, 
HiddenVisibility,
- "visibility for external declarations without an explicit DLL 
storage class [-fvisibility-from-dllstorageclass]")
+BENIGN_LANGOPT(VisibilityFromDLLStorageClass, 1, 0,
+   "override the visibility of globals based on their final DLL 
storage class [-fvisibility-from-dllstorageclass]")
+BENIGN_ENUM_LANGOPT(DLLExportVisibility, VisibilityFromDLLStorageClassKinds, 
3, VisibilityFromDLLStorageClassKinds::Default,
+ "how to adjust the visibility for functions and variables with 
dllexport annotations [-fvisibility-dllexport]")
+BENIGN_ENUM_LANGOPT(NoDLLStorageClassVisibility, 
VisibilityFromDLLStorageClassKinds, 3, 
VisibilityFromDLLStorageClassKinds::Hidden,
+ "how to adjust the visibility for functions and variables without 
an explicit DLL storage class [-fvisibility-nodllstorageclass]")
+BENIGN_ENUM_LANGOPT(ExternDeclDLLImportVisibility, 
VisibilityFromDLLStorageClassKinds, 3, 
VisibilityFromDLLStorageClassKinds::Default,
+ "how to adjust the visibility for external declarations with 
dllimport annotations [-fvisibility-externs-dllimport]")
+BENIGN_ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, 
VisibilityFromDLLStorageClassKinds, 3,  
VisibilityFromDLLStorageClassKinds::Hidden,
+ "how to adjust the visibility for external declarations without 
an explicit DLL storage class [-fvi

[llvm] [clang] [Clang] Correct __builtin_dynamic_object_size for subobject types (PR #78526)

2024-01-19 Thread Richard Smith via cfe-commits

zygoloid wrote:

> > But mode 0 and 1 are in general asking for an upper bound on the accessible 
> > bytes (that is, an N so any.access beyond N bytes is definitely out of 
> > bounds), so it seems to me that returning -1 is strictly worse than 
> > returning 48.
> 
> It's the second bit that controls whether it's an upper bound or lower bound 
> that's returned, not the least significant bit.

Right, that's what I said: modes 0 and 1 ask for an upper bound. (Modes 2 and 3 
ask for a lower bound.)

> We're trying to implement a GNU builtin, and the only defined semantics we 
> have to go on are GNU's documentation. I can't see how we can deviate from 
> their documentation unless it's to say "we can't determine this value" and so 
> return `-1` instead of an answer that might be wildly wrong and potentially 
> cause a memory leak of some sort.

We're not really deviating from the documented rules. By the time we get to 
LLVM IR lowering of the builtin, we have lost the precise frontend information. 
But we know the pointer might point into the complete object (where it would be 
able to write to 48 bytes) or to some subobject of that complete object (where 
it would be able to write to 48 bytes or less). Therefore the correct answer to 
return is 48.

In the same way, it would be correct to return 48 here:

```
char a[48];
char b[40];
bool always_false = false; // happens to never be modified
int n = __builtin_dynamic_object_size(always_false ? a  : b, 1);
```

... though we miscompile this and return 40 regardless of whether we're in 
upper bound or lower bound mode. :-(

> In my made-up example, if we said, "Yes you can write up to 48 bytes into 
> `p->failed_devs[argc]`, then a user may overwrite the two fields after 
> `field_devs`. If we return `-1`, they'll have to take the "slow", but ideally 
> more secure, route.

No, that is not what we are saying when we return 48. We're saying "a write 
past 48 bytes is definitely bad". If you want a lower bound on the number of 
bytes that you can write, then you need to use mode 2 or 3 instead.

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


[clang] [clang-tools-extra] [clang] Remove `CXXNewInitializationStyle::Implicit` (PR #78793)

2024-01-19 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll created 
https://github.com/llvm/llvm-project/pull/78793

This is a follow up to https://github.com/llvm/llvm-project/pull/71417 , which 
aims to resolve concerns brought up there. Namely, this patch replaces 
`CXXNewInitializationStyle::Implicit` with a dedicated `HasInitializer` flag. 
This makes `CXXNewInitializationStyle` to model syntax again. This patch also 
renames `Call` and `List` to less confusing `Parens` and `Braces`.

>From f6a599d6e662121f19529f59ffa44cc6177c0835 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Sat, 20 Jan 2024 00:58:06 +0300
Subject: [PATCH] [clang] Remove `CXXNewInitializationStyle::Implicit`

This is a follow up to https://github.com/llvm/llvm-project/pull/71417 , which 
aims to resolve concerns brought up there. Namely, this patch replaces 
`CXXNewInitializationStyle::Implicit` with a dedicated `HasInitializer` flag. 
This makes `CXXNewInitializationStyle` to model syntax again. This patch also 
renames `Call` and `List` to less confusing `Parens` and `Braces`.
---
 .../modernize/MakeSmartPtrCheck.cpp   |  7 +++--
 clang/include/clang/AST/ExprCXX.h | 19 +++---
 clang/include/clang/AST/Stmt.h|  8 +++---
 clang/lib/AST/ExprCXX.cpp | 10 +++
 clang/lib/AST/ItaniumMangle.cpp   |  4 +--
 clang/lib/AST/JSONNodeDumper.cpp  |  5 ++--
 clang/lib/AST/StmtPrinter.cpp |  5 ++--
 clang/lib/Sema/SemaExprCXX.cpp| 26 ++-
 clang/lib/Serialization/ASTReaderStmt.cpp |  1 +
 clang/lib/Serialization/ASTWriterStmt.cpp |  1 +
 10 files changed, 32 insertions(+), 54 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
index 616e57efa76ded5..d1d7e9dcfa9c0d2 100644
--- a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -323,8 +323,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
 return false;
   };
   switch (New->getInitializationStyle()) {
-  case CXXNewInitializationStyle::None:
-  case CXXNewInitializationStyle::Implicit: {
+  case CXXNewInitializationStyle::None: {
 if (ArraySizeExpr.empty()) {
   Diag << FixItHint::CreateRemoval(SourceRange(NewStart, NewEnd));
 } else {
@@ -335,7 +334,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
 }
 break;
   }
-  case CXXNewInitializationStyle::Call: {
+  case CXXNewInitializationStyle::Parens: {
 // FIXME: Add fixes for constructors with parameters that can be created
 // with a C++11 braced-init-list (e.g. std::vector, std::map).
 // Unlike ordinal cases, braced list can not be deduced in
@@ -372,7 +371,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
 }
 break;
   }
-  case CXXNewInitializationStyle::List: {
+  case CXXNewInitializationStyle::Braces: {
 // Range of the substring that we do not want to remove.
 SourceRange InitRange;
 if (const auto *NewConstruct = New->getConstructExpr()) {
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index 24278016431837b..9a7c632c36c5e8a 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -2210,14 +2210,11 @@ enum class CXXNewInitializationStyle {
   /// New-expression has no initializer as written.
   None,
 
-  /// New-expression has no written initializer, but has an implicit one.
-  Implicit,
-
   /// New-expression has a C++98 paren-delimited initializer.
-  Call,
+  Parens,
 
   /// New-expression has a C++11 list-initializer.
-  List
+  Braces
 };
 
 /// Represents a new-expression for memory allocation and constructor
@@ -2388,17 +2385,7 @@ class CXXNewExpr final
   bool isGlobalNew() const { return CXXNewExprBits.IsGlobalNew; }
 
   /// Whether this new-expression has any initializer at all.
-  bool hasInitializer() const {
-switch (getInitializationStyle()) {
-case CXXNewInitializationStyle::None:
-  return false;
-case CXXNewInitializationStyle::Implicit:
-case CXXNewInitializationStyle::Call:
-case CXXNewInitializationStyle::List:
-  return true;
-}
-llvm_unreachable("Unknown initializer");
-  }
+  bool hasInitializer() const { return CXXNewExprBits.HasInitializer; }
 
   /// The kind of initializer this new-expression has.
   CXXNewInitializationStyle getInitializationStyle() const {
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index e1fde24e647789a..55eca4007d17ea2 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -868,9 +868,11 @@ class alignas(void *) Stmt {
 LLVM_PREFERRED_TYPE(bool)
 unsigned UsualArrayDeleteWantsSize : 1;
 
-/// What kind of initializer do we have? Could be none, parens, or braces.
-/// In storage, we distinguish between "none,

[clang] [clang-tools-extra] [clang] Remove `CXXNewInitializationStyle::Implicit` (PR #78793)

2024-01-19 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-tidy

@llvm/pr-subscribers-clang-modules

Author: Vlad Serebrennikov (Endilll)


Changes

This is a follow up to https://github.com/llvm/llvm-project/pull/71417 , which 
aims to resolve concerns brought up there. Namely, this patch replaces 
`CXXNewInitializationStyle::Implicit` with a dedicated `HasInitializer` flag. 
This makes `CXXNewInitializationStyle` to model syntax again. This patch also 
renames `Call` and `List` to less confusing `Parens` and `Braces`.

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


10 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp 
(+3-4) 
- (modified) clang/include/clang/AST/ExprCXX.h (+3-16) 
- (modified) clang/include/clang/AST/Stmt.h (+5-3) 
- (modified) clang/lib/AST/ExprCXX.cpp (+5-5) 
- (modified) clang/lib/AST/ItaniumMangle.cpp (+2-2) 
- (modified) clang/lib/AST/JSONNodeDumper.cpp (+2-3) 
- (modified) clang/lib/AST/StmtPrinter.cpp (+2-3) 
- (modified) clang/lib/Sema/SemaExprCXX.cpp (+8-18) 
- (modified) clang/lib/Serialization/ASTReaderStmt.cpp (+1) 
- (modified) clang/lib/Serialization/ASTWriterStmt.cpp (+1) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
index 616e57efa76ded..d1d7e9dcfa9c0d 100644
--- a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -323,8 +323,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
 return false;
   };
   switch (New->getInitializationStyle()) {
-  case CXXNewInitializationStyle::None:
-  case CXXNewInitializationStyle::Implicit: {
+  case CXXNewInitializationStyle::None: {
 if (ArraySizeExpr.empty()) {
   Diag << FixItHint::CreateRemoval(SourceRange(NewStart, NewEnd));
 } else {
@@ -335,7 +334,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
 }
 break;
   }
-  case CXXNewInitializationStyle::Call: {
+  case CXXNewInitializationStyle::Parens: {
 // FIXME: Add fixes for constructors with parameters that can be created
 // with a C++11 braced-init-list (e.g. std::vector, std::map).
 // Unlike ordinal cases, braced list can not be deduced in
@@ -372,7 +371,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
 }
 break;
   }
-  case CXXNewInitializationStyle::List: {
+  case CXXNewInitializationStyle::Braces: {
 // Range of the substring that we do not want to remove.
 SourceRange InitRange;
 if (const auto *NewConstruct = New->getConstructExpr()) {
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index 24278016431837..9a7c632c36c5e8 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -2210,14 +2210,11 @@ enum class CXXNewInitializationStyle {
   /// New-expression has no initializer as written.
   None,
 
-  /// New-expression has no written initializer, but has an implicit one.
-  Implicit,
-
   /// New-expression has a C++98 paren-delimited initializer.
-  Call,
+  Parens,
 
   /// New-expression has a C++11 list-initializer.
-  List
+  Braces
 };
 
 /// Represents a new-expression for memory allocation and constructor
@@ -2388,17 +2385,7 @@ class CXXNewExpr final
   bool isGlobalNew() const { return CXXNewExprBits.IsGlobalNew; }
 
   /// Whether this new-expression has any initializer at all.
-  bool hasInitializer() const {
-switch (getInitializationStyle()) {
-case CXXNewInitializationStyle::None:
-  return false;
-case CXXNewInitializationStyle::Implicit:
-case CXXNewInitializationStyle::Call:
-case CXXNewInitializationStyle::List:
-  return true;
-}
-llvm_unreachable("Unknown initializer");
-  }
+  bool hasInitializer() const { return CXXNewExprBits.HasInitializer; }
 
   /// The kind of initializer this new-expression has.
   CXXNewInitializationStyle getInitializationStyle() const {
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index e1fde24e647789..55eca4007d17ea 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -868,9 +868,11 @@ class alignas(void *) Stmt {
 LLVM_PREFERRED_TYPE(bool)
 unsigned UsualArrayDeleteWantsSize : 1;
 
-/// What kind of initializer do we have? Could be none, parens, or braces.
-/// In storage, we distinguish between "none, and no initializer expr", and
-/// "none, but an implicit initializer expr".
+// Is initializer expr present?
+LLVM_PREFERRED_TYPE(bool)
+unsigned HasInitializer : 1;
+
+/// What kind of initializer syntax used? Could be none, parens, or braces.
 LLVM_PREFERRED_TYPE(CXXNewInitializationStyle)
 unsigned StoredInitializationStyle : 2;
 
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 83af7998f68338..e61c11dffd8841 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b

[clang] [clang-tools-extra] [clang] Remove `CXXNewInitializationStyle::Implicit` (PR #78793)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

This is a follow up to https://github.com/llvm/llvm-project/pull/71417 , which 
aims to resolve concerns brought up there. Namely, this patch replaces 
`CXXNewInitializationStyle::Implicit` with a dedicated `HasInitializer` flag. 
This makes `CXXNewInitializationStyle` to model syntax again. This patch also 
renames `Call` and `List` to less confusing `Parens` and `Braces`.

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


10 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp 
(+3-4) 
- (modified) clang/include/clang/AST/ExprCXX.h (+3-16) 
- (modified) clang/include/clang/AST/Stmt.h (+5-3) 
- (modified) clang/lib/AST/ExprCXX.cpp (+5-5) 
- (modified) clang/lib/AST/ItaniumMangle.cpp (+2-2) 
- (modified) clang/lib/AST/JSONNodeDumper.cpp (+2-3) 
- (modified) clang/lib/AST/StmtPrinter.cpp (+2-3) 
- (modified) clang/lib/Sema/SemaExprCXX.cpp (+8-18) 
- (modified) clang/lib/Serialization/ASTReaderStmt.cpp (+1) 
- (modified) clang/lib/Serialization/ASTWriterStmt.cpp (+1) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
index 616e57efa76ded..d1d7e9dcfa9c0d 100644
--- a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -323,8 +323,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
 return false;
   };
   switch (New->getInitializationStyle()) {
-  case CXXNewInitializationStyle::None:
-  case CXXNewInitializationStyle::Implicit: {
+  case CXXNewInitializationStyle::None: {
 if (ArraySizeExpr.empty()) {
   Diag << FixItHint::CreateRemoval(SourceRange(NewStart, NewEnd));
 } else {
@@ -335,7 +334,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
 }
 break;
   }
-  case CXXNewInitializationStyle::Call: {
+  case CXXNewInitializationStyle::Parens: {
 // FIXME: Add fixes for constructors with parameters that can be created
 // with a C++11 braced-init-list (e.g. std::vector, std::map).
 // Unlike ordinal cases, braced list can not be deduced in
@@ -372,7 +371,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
 }
 break;
   }
-  case CXXNewInitializationStyle::List: {
+  case CXXNewInitializationStyle::Braces: {
 // Range of the substring that we do not want to remove.
 SourceRange InitRange;
 if (const auto *NewConstruct = New->getConstructExpr()) {
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index 24278016431837..9a7c632c36c5e8 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -2210,14 +2210,11 @@ enum class CXXNewInitializationStyle {
   /// New-expression has no initializer as written.
   None,
 
-  /// New-expression has no written initializer, but has an implicit one.
-  Implicit,
-
   /// New-expression has a C++98 paren-delimited initializer.
-  Call,
+  Parens,
 
   /// New-expression has a C++11 list-initializer.
-  List
+  Braces
 };
 
 /// Represents a new-expression for memory allocation and constructor
@@ -2388,17 +2385,7 @@ class CXXNewExpr final
   bool isGlobalNew() const { return CXXNewExprBits.IsGlobalNew; }
 
   /// Whether this new-expression has any initializer at all.
-  bool hasInitializer() const {
-switch (getInitializationStyle()) {
-case CXXNewInitializationStyle::None:
-  return false;
-case CXXNewInitializationStyle::Implicit:
-case CXXNewInitializationStyle::Call:
-case CXXNewInitializationStyle::List:
-  return true;
-}
-llvm_unreachable("Unknown initializer");
-  }
+  bool hasInitializer() const { return CXXNewExprBits.HasInitializer; }
 
   /// The kind of initializer this new-expression has.
   CXXNewInitializationStyle getInitializationStyle() const {
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index e1fde24e647789..55eca4007d17ea 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -868,9 +868,11 @@ class alignas(void *) Stmt {
 LLVM_PREFERRED_TYPE(bool)
 unsigned UsualArrayDeleteWantsSize : 1;
 
-/// What kind of initializer do we have? Could be none, parens, or braces.
-/// In storage, we distinguish between "none, and no initializer expr", and
-/// "none, but an implicit initializer expr".
+// Is initializer expr present?
+LLVM_PREFERRED_TYPE(bool)
+unsigned HasInitializer : 1;
+
+/// What kind of initializer syntax used? Could be none, parens, or braces.
 LLVM_PREFERRED_TYPE(CXXNewInitializationStyle)
 unsigned StoredInitializationStyle : 2;
 
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 83af7998f68338..e61c11dffd8841 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -194,14 +1

[clang] [Sema] Provide `-fvisibility-global-new-delete=` option (PR #75364)

2024-01-19 Thread via cfe-commits

https://github.com/bd1976bris updated 
https://github.com/llvm/llvm-project/pull/75364

>From 97efed8c73aed4fdca5510013c844e84953ec256 Mon Sep 17 00:00:00 2001
From: Ben Dunbobbin 
Date: Tue, 12 Dec 2023 08:07:17 +
Subject: [PATCH 1/6] [Sema] Provide `-fno-/-fvisibility-global-new-delete`
 option

By default the implicitly declared replaceable global new and delete
operators are given a `default` visibility attribute. Previous work,
see: https://reviews.llvm.org/D53787, added
`-fvisibility-global-new-delete-hidden` to change this to a `hidden`
visibility attribute.

This change adds: `-fno/-fvisibility-global-new-delete` which controls
whether or not to add a visibility attribute to the implicit
declarations for these functions. Without the attribute the replaceable
global new and delete operators behave normally (like other functions)
with respect to visibility attributes, pragmas and options.

The command line help for these options is rendered as:

  -fvisibility-global-new-delete
  Add a visibility attribute to the implicit
  global C++ operator new and delete declarations

  -fno-visibility-global-new-delete
  Do not add a visibility attribute to the implicit
  global C++ operator new and delete declarations

The motivation is to allow users to specify
`-fno-visibility-global-new-delete` when they intend to replace these
functions either for a single linkage unit or set of linkage units.

`-fno-visibility-global-new-delete` can be applied globally to the
compilations in a build where `-fvisibility-global-new-delete-hidden`
cannot; as it conflicts with a common pattern where these functions are
dynamically imported.

`-fno-visibility-global-new-delete` makes sense as the default for PS5.
Users that want the normal toolchain behaviour will be able to supply
`-fvisibility-global-new-delete`.
---
 clang/include/clang/Basic/LangOptions.def |  3 +-
 clang/include/clang/Driver/Options.td |  6 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 12 +
 clang/lib/Driver/ToolChains/PS4CPU.cpp|  6 +++
 clang/lib/Sema/SemaExprCXX.cpp|  9 ++--
 .../visibility-global-new-delete.cpp  | 13 +
 .../Driver/visibility-global-new-delete.cl| 47 +++
 7 files changed, 91 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/visibility-global-new-delete.cpp
 create mode 100644 clang/test/Driver/visibility-global-new-delete.cl

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c3d5399905a3fd..1471fc11e11663 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -306,7 +306,8 @@ BENIGN_LANGOPT(IgnoreXCOFFVisibility, 1, 0, "All the 
visibility attributes that
 BENIGN_LANGOPT(VisibilityInlinesHiddenStaticLocalVar, 1, 0,
"hidden visibility for static local variables in inline C++ "
"methods when -fvisibility-inlines hidden is enabled")
-LANGOPT(GlobalAllocationFunctionVisibilityHidden , 1, 0, "hidden visibility 
for global operator new and delete declaration")
+LANGOPT(GlobalAllocationFunctionVisibility, 1, 1, "add a visibility attribute 
to the implicit global operator new and delete declarations")
+LANGOPT(GlobalAllocationFunctionVisibilityHidden, 1, 0, "hidden visibility for 
global operator new and delete declarations")
 LANGOPT(NewInfallible , 1, 0, "Treats throwing global C++ operator new as 
always returning valid memory (annotates with __attribute__((returns_nonnull)) 
and throw()). This is detectable in source.")
 BENIGN_LANGOPT(ParseUnknownAnytype, 1, 0, "__unknown_anytype")
 BENIGN_LANGOPT(DebuggerSupport , 1, 0, "debugger support")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index db2190318c931a..a9f43b18df6fbf 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3863,6 +3863,12 @@ defm visibility_inlines_hidden_static_local_var : 
BoolFOption<"visibility-inline
 def fvisibility_ms_compat : Flag<["-"], "fvisibility-ms-compat">, 
Group,
   HelpText<"Give global types 'default' visibility and global functions and "
"variables 'hidden' visibility by default">;
+defm visibility_global_new_delete : BoolFOption<"visibility-global-new-delete",
+  LangOpts<"GlobalAllocationFunctionVisibility">, DefaultTrue,
+  PosFlag,
+  NegFlag,
+  BothFlags<[], [ClangOption, CC1Option],
+  " a visibility attribute to the implicit global C++ operator new and 
delete declarations">>;
 def fvisibility_global_new_delete_hidden : Flag<["-"], 
"fvisibility-global-new-delete-hidden">, Group,
   HelpText<"Give global C++ operator new and delete declarations hidden 
visibility">,
   Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
inde

[clang] [Sema] Provide `-fvisibility-global-new-delete=` option (PR #75364)

2024-01-19 Thread via cfe-commits


@@ -359,6 +359,12 @@ void toolchains::PS4PS5Base::addClangTargetOptions(
 
   CC1Args.push_back("-fno-use-init-array");
 
+  // Default to -fglobal-new-delete-visibility=source for PS5.

bd1976bris wrote:

Thanks - now using the correct spelling.

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


[clang] [llvm] [compiler-rt] [AArch64][FMV] Support feature MOPS in Function Multi Versioning. (PR #78788)

2024-01-19 Thread Pavel Iliin via cfe-commits


@@ -172,6 +172,11 @@ static void __init_cpu_features_constructor(unsigned long 
hwcap,
 // ID_AA64ISAR1_EL1.LS64 >= 0b0011
 if (extractBits(ftr, 60, 4) >= 0x3)
   setCPUFeature(FEAT_LS64_ACCDATA);
+

ilinpv wrote:

There is HWCAP2_MOPS support in ELF hwcaps 
https://docs.kernel.org/arch/arm64/elf_hwcaps.html
which can be also used for mops detection if available

https://github.com/llvm/llvm-project/pull/78788
___
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 crash in modernize-loop-convert when int is used as iterator (PR #78796)

2024-01-19 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL created 
https://github.com/llvm/llvm-project/pull/78796

Fix crash when built-in type (like int) is used as iterator, or when call to 
begin() return integer.

Closes #78381

>From 812b49d8e5e6c07a9d26b36413b26e6f0dbe277f Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Fri, 19 Jan 2024 22:05:35 +
Subject: [PATCH] [clang-tidy] Fix crash in modernize-loop-convert when int is
 used as iterator

Fix crash when built-in type (like int) is used as iterator,
or when call to begin() return integer.

Closes #78381
---
 .../clang-tidy/modernize/LoopConvertCheck.cpp   | 12 
 clang-tools-extra/docs/ReleaseNotes.rst |  5 +++--
 .../checkers/modernize/loop-convert-basic.cpp   | 13 +
 3 files changed, 24 insertions(+), 6 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
index 8beaa62c78ba0a..f0791da143ad9d 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -942,11 +942,15 @@ bool LoopConvertCheck::isConvertible(ASTContext *Context,
 CanonicalInitVarType->isPointerType()) {
   // If the initializer and the variable are both pointers check if the
   // un-qualified pointee types match, otherwise we don't use auto.
-  if (!Context->hasSameUnqualifiedType(
-  CanonicalBeginType->getPointeeType(),
-  CanonicalInitVarType->getPointeeType()))
-return false;
+  return Context->hasSameUnqualifiedType(
+  CanonicalBeginType->getPointeeType(),
+  CanonicalInitVarType->getPointeeType());
 }
+
+if (CanonicalBeginType->isBuiltinType() ||
+CanonicalInitVarType->isBuiltinType())
+  return false;
+
   } else if (FixerKind == LFK_PseudoArray) {
 if (const auto *EndCall = Nodes.getNodeAs(EndCallName)) 
{
   // This call is required to obtain the container.
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index d77267588db915..7f618e71afd1ce 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -410,7 +410,8 @@ Changes in existing checks
 - Improved :doc:`modernize-loop-convert
   ` to support for-loops with
   iterators initialized by free functions like ``begin``, ``end``, or ``size``
-  and avoid crash for array of dependent array.
+  and avoid crash for array of dependent array and non-dereferenceable builtin
+  types used as iterators.
 
 - Improved :doc:`modernize-make-shared
   ` check to support
@@ -502,7 +503,7 @@ Changes in existing checks
   ` check to take
   do-while loops into account for the `AllowIntegerConditions` and
   `AllowPointerConditions` options. It also now provides more consistent
-  suggestions when parentheses are added to the return value or expressions. 
+  suggestions when parentheses are added to the return value or expressions.
   It also ignores false-positives for comparison containing bool bitfield.
 
 - Improved :doc:`readability-misleading-indentation
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
index e2b9336d620f50..c29fbc9f9b23b7 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
@@ -954,3 +954,16 @@ void dependenceArrayTest() {
 }
 
 } // namespace PseudoArray
+
+namespace PR78381 {
+  struct blocked_range {
+int begin() const;
+int end() const;
+  };
+
+  void test() {
+blocked_range r;
+for (auto i = r.begin(); i!=r.end(); ++i) {
+}
+  }
+}

___
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 crash in modernize-loop-convert when int is used as iterator (PR #78796)

2024-01-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Piotr Zegar (PiotrZSL)


Changes

Fix crash when built-in type (like int) is used as iterator, or when call to 
begin() return integer.

Closes #78381

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


3 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp (+8-4) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+3-2) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp 
(+13) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
index 8beaa62c78ba0ab..f0791da143ad9df 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -942,11 +942,15 @@ bool LoopConvertCheck::isConvertible(ASTContext *Context,
 CanonicalInitVarType->isPointerType()) {
   // If the initializer and the variable are both pointers check if the
   // un-qualified pointee types match, otherwise we don't use auto.
-  if (!Context->hasSameUnqualifiedType(
-  CanonicalBeginType->getPointeeType(),
-  CanonicalInitVarType->getPointeeType()))
-return false;
+  return Context->hasSameUnqualifiedType(
+  CanonicalBeginType->getPointeeType(),
+  CanonicalInitVarType->getPointeeType());
 }
+
+if (CanonicalBeginType->isBuiltinType() ||
+CanonicalInitVarType->isBuiltinType())
+  return false;
+
   } else if (FixerKind == LFK_PseudoArray) {
 if (const auto *EndCall = Nodes.getNodeAs(EndCallName)) 
{
   // This call is required to obtain the container.
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index d77267588db9158..7f618e71afd1ce0 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -410,7 +410,8 @@ Changes in existing checks
 - Improved :doc:`modernize-loop-convert
   ` to support for-loops with
   iterators initialized by free functions like ``begin``, ``end``, or ``size``
-  and avoid crash for array of dependent array.
+  and avoid crash for array of dependent array and non-dereferenceable builtin
+  types used as iterators.
 
 - Improved :doc:`modernize-make-shared
   ` check to support
@@ -502,7 +503,7 @@ Changes in existing checks
   ` check to take
   do-while loops into account for the `AllowIntegerConditions` and
   `AllowPointerConditions` options. It also now provides more consistent
-  suggestions when parentheses are added to the return value or expressions. 
+  suggestions when parentheses are added to the return value or expressions.
   It also ignores false-positives for comparison containing bool bitfield.
 
 - Improved :doc:`readability-misleading-indentation
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
index e2b9336d620f507..c29fbc9f9b23b71 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
@@ -954,3 +954,16 @@ void dependenceArrayTest() {
 }
 
 } // namespace PseudoArray
+
+namespace PR78381 {
+  struct blocked_range {
+int begin() const;
+int end() const;
+  };
+
+  void test() {
+blocked_range r;
+for (auto i = r.begin(); i!=r.end(); ++i) {
+}
+  }
+}

``




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


[clang] [Sema] Provide `-fvisibility-global-new-delete=` option (PR #75364)

2024-01-19 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,52 @@
+/// Check driver handling for "-fvisibility-global-new-delete-hidden" and 
"-fvisibility-global-new-delete=".
+
+/// These options are not added by default.
+// RUN: %clang -### -target x86_64-unknown-unknown -x cl -c -emit-llvm %s 2>&1 
| \

MaskRay wrote:

`--target=` instead of deprecated `-target ` for new tests

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


[clang] [Sema] Provide `-fvisibility-global-new-delete=` option (PR #75364)

2024-01-19 Thread Fangrui Song via cfe-commits

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


[clang] [llvm] [Clang] Correct __builtin_dynamic_object_size for subobject types (PR #78526)

2024-01-19 Thread Richard Smith via cfe-commits

zygoloid wrote:

Taking a step back, while this patch is not the right direction, we can and 
should do better for the original example. Probably the best way to do that is 
to analyze the operand to `__builtin_[dynamic_]object_size` in the frontend and 
compute a better bound based on the form of the expression. It looks like it 
should be feasible to produce a tighter bound for an array-to-pointer-decay 
expression like `f.bar[argc]` in subobject mode, as:

- `select llvm.is.constant(argc) and (argc < 0 or argc >= 2), 0, 
sizeof(f.bar[argc])` for the non-dynamic case, and just
- `select (argc < 0 or argc >= 2), 0, sizeof(f.bar[argc])` for the dynamic case.

A possibly simpler alternative would be for the frontend to pass an upper bound 
on the result to the LLVM builtin in mode 1, so Clang could say "I know the 
result will never be more than 40" and LLVM could provide either that size or 
the complete object size, whichever is smaller. That wouldn't give as tight a 
bound for the argc == 2 case, though.

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


[clang] [clang-tools-extra] [clang] Remove `CXXNewInitializationStyle::Implicit` (PR #78793)

2024-01-19 Thread via cfe-commits

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


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


[clang] [llvm] [Clang] Correct __builtin_dynamic_object_size for subobject types (PR #78526)

2024-01-19 Thread Bill Wendling via cfe-commits

bwendling wrote:

> > > But mode 0 and 1 are in general asking for an upper bound on the 
> > > accessible bytes (that is, an N so any.access beyond N bytes is 
> > > definitely out of bounds), so it seems to me that returning -1 is 
> > > strictly worse than returning 48.
> > 
> > 
> > It's the second bit that controls whether it's an upper bound or lower 
> > bound that's returned, not the least significant bit.
> 
> Right, that's what I said: modes 0 and 1 ask for an upper bound. (Modes 2 and 
> 3 ask for a lower bound.)

Perhaps we need clarification on what GCC means by "may point to multiple 
objects" in this instance. To me that means either "get me the size of the 
largest of these multiple objects" or "size of the smallest." In my eyes, that 
means pointing to a union field.

> > We're trying to implement a GNU builtin, and the only defined semantics we 
> > have to go on are GNU's documentation. I can't see how we can deviate from 
> > their documentation unless it's to say "we can't determine this value" and 
> > so return `-1` instead of an answer that might be wildly wrong and 
> > potentially cause a memory leak of some sort.
> 
> We're not really deviating from the documented rules. By the time we get to 
> LLVM IR lowering of the builtin, we have lost the precise frontend 
> information. But we know the pointer might point into the complete object 
> (where it would be able to write to 48 bytes) or to some subobject of that 
> complete object (where it would be able to write to 48 bytes or less). 
> Therefore the correct answer to return is 48.
> 
> In the same way, it would be correct to return 48 here:
> 
> ```
> char a[48];
> char b[40];
> bool always_false = false; // happens to never be modified
> int n = __builtin_dynamic_object_size(always_false ? a  : b, 1);
> ```
> 
> ... though we miscompile this and return 40 regardless of whether we're in 
> upper bound or lower bound mode. :-(
> 
> > In my made-up example, if we said, "Yes you can write up to 48 bytes into 
> > `p->failed_devs[argc]`, then a user may overwrite the two fields after 
> > `field_devs`. If we return `-1`, they'll have to take the "slow", but 
> > ideally more secure, route.
> 
> No, that is not what we are saying when we return 48. We're saying "a write 
> past 48 bytes is definitely bad". If you want a lower bound on the number of 
> bytes that you can write, then you need to use mode 2 or 3 instead.

But in the example, writing up to 48 bytes *is* definitely bad. And as I 
mentioned, we disagree on what's meant by "upper" and "lower" bounds in the 
case of a pointer to a non-union field. For me, that's managed by the first bit.

I know that we lose precise struct information going to LLVM IR. If that's 
what's needed here, there are ways to pass this information along. We retain 
this information via DWARF. We could use similar metadata for this instance. 
Would that be acceptable?

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


[clang] [llvm] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-19 Thread NAKAMURA Takumi via cfe-commits


@@ -11,6 +11,7 @@
 
//===--===//
 
 #include "SystemZ.h"
+#include "clang/AST/Decl.h"

chapuni wrote:

Thanks. Now you can remove this. This is the only point from my side.

> (note that clang itself builds fine)
You were introducing layering violation. "Clang could be built apparently."

> Why did you remove clangAST from the cmake file to begin with - was there 
> some discussion preceding this?
In principle, we can prune redundant deps. In contrast, the discussion would be 
required for introducing new deps.

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


[clang] [llvm] [clang, SystemZ] Pass HasDef flag to getMinGlobalAlign(). (PR #73511)

2024-01-19 Thread NAKAMURA Takumi via cfe-commits

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


[clang] [Sema] Provide `-fvisibility-global-new-delete=` option (PR #75364)

2024-01-19 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 %s -std=c++11 -triple x86_64-unknown-unknown 
-fvisibility=hidden -emit-llvm -o - | FileCheck %s -DLINKAGE=dso_local
+// RUN: %clang_cc1 %s -std=c++11 -triple x86_64-unknown-unknown 
-fvisibility=default -fvisibility-global-new-delete=force-hidden -emit-llvm -o 
- | FileCheck %s -DLINKAGE=hidden
+// RUN: %clang_cc1 %s -std=c++11 -triple x86_64-unknown-unknown 
-fvisibility=hidden -fvisibility-global-new-delete=force-protected -emit-llvm 
-o - | FileCheck %s -DLINKAGE=protected
+// RUN: %clang_cc1 %s -std=c++11 -triple x86_64-unknown-unknown 
-fvisibility=hidden -fvisibility-global-new-delete=force-default -emit-llvm -o 
- | FileCheck %s -DLINKAGE=dso_local
+// RUN: %clang_cc1 %s -std=c++11 -triple x86_64-unknown-unknown 
-fvisibility=hidden -fvisibility-global-new-delete=source -emit-llvm -o - | 
FileCheck %s -DLINKAGE=hidden
+
+namespace std {
+  typedef __typeof__(sizeof(0)) size_t;
+  struct nothrow_t {};
+}
+
+// Definition which inherits visibility from the implicit compiler generated 
declaration.
+void operator delete(void*) throw() {}
+// CHECK: define [[LINKAGE]] void @_ZdlPv

MaskRay wrote:

Add a test for `operator new`?

`-fvisibility-global-new-delete-hidden`, from https://reviews.llvm.org/D53787, 
does not have a test. Thanks for adding the test

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


[clang] [Sema] Provide `-fvisibility-global-new-delete=` option (PR #75364)

2024-01-19 Thread Fangrui Song via cfe-commits


@@ -3864,9 +3864,16 @@ def fvisibility_ms_compat : Flag<["-"], 
"fvisibility-ms-compat">, Group
   HelpText<"Give global types 'default' visibility and global functions and "
"variables 'hidden' visibility by default">;
 def fvisibility_global_new_delete_hidden : Flag<["-"], 
"fvisibility-global-new-delete-hidden">, Group,
-  HelpText<"Give global C++ operator new and delete declarations hidden 
visibility">,
+  HelpText<"Give global C++ operator new and delete declarations hidden 
visibility">;
+class MarshallingInfoVisibilityGlobalNewDelete
+  : MarshallingInfoEnum,
+Values<"force-default,force-protected,force-hidden,source">,
+NormalizedValuesScope<"LangOptions::VisibilityForcedKinds">,
+NormalizedValues<["ForceDefault", "ForceProtected", "ForceHidden", 
"Source"]> {}
+def fvisibility_global_new_delete_EQ : Joined<["-"], 
"fvisibility-global-new-delete=">, Group,
   Visibility<[ClangOption, CC1Option]>,
-  MarshallingInfoFlag>;
+  HelpText<"The visibility for global C++ operator new and delete declarations 
definitions. If source is specified the visibility is not adjusted">,

MaskRay wrote:

Single quotes around `source`

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


[clang] [llvm] [Clang] Correct __builtin_dynamic_object_size for subobject types (PR #78526)

2024-01-19 Thread Bill Wendling via cfe-commits

bwendling wrote:

> Taking a step back, while this patch is not the right direction, we can and 
> should do better for the original example. Probably the best way to do that 
> is to analyze the operand to `__builtin_[dynamic_]object_size` in the 
> frontend and compute a better bound based on the form of the expression. It 
> looks like it should be feasible to produce a tighter bound for an 
> array-to-pointer-decay expression like `f.bar[argc]` in subobject mode, as:
> 
> * `select llvm.is.constant(argc) and (argc < 0 or argc >= 2), 0, 
> sizeof(f.bar[argc])` for the non-dynamic case, and just
> * `select (argc < 0 or argc >= 2), 0, sizeof(f.bar[argc])` for the dynamic 
> case.
> 
> A possibly simpler alternative would be for the frontend to pass an upper 
> bound on the result to the LLVM builtin in mode 1, so Clang could say "I know 
> the result will never be more than 40" and LLVM could provide either that 
> size or the complete object size, whichever is smaller. That wouldn't give as 
> tight a bound for the argc == 2 case, though.

It might be possible to do something like this. If retaining precise type 
information from the front-end is the sticking issue, it could be as simple as 
casting this pointer top the type of the sub-object. I'll see what I can do.

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


  1   2   3   4   5   6   >