[clang] Sanitizer: Support -fwrapv with -fsanitize=signed-integer-overflow (PR #82432)

2024-03-15 Thread Fangrui Song via cfe-commits

MaskRay wrote:

> Shouldn't plain `-fsanitize=undefined` disable this sanitizer by default 
> (requiring explicit opt-in)? In `-fwrapv` mode this is not undefined 
> behavior, so `-fsanitize=undefined` should not complain about it.

I was on the fence whether `-fsanitize=undefined` should expand to 
signed-integer-overflow: 
https://github.com/llvm/llvm-project/pull/80089#issuecomment-1945202620

Perhaps you have run into some convenience issues? #85501 for the 
signed-integer-overflow suppresion.

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


[clang] [Driver] -fsanitize=undefined: don't expand to signed-integer-overflow if -fwrapv (PR #85501)

2024-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Fangrui Song (MaskRay)


Changes

Linux kernel uses -fwrapv to change signed integer overflows from
undefined behaviors to defined behaviors. However, the security folks
still want -fsanitize=signed-integer-overflow diagnostics. Their
intention can be expressed with -fwrapv
-fsanitize=signed-integer-overflow (#80089). This mode by default
reports recoverable errors while still making signed integer overflows
defined (most UBSan checks are recoverable by default: you get errors in
stderr, but the program is not halted).

-fsanitize=undefined -fwrapv users likely want to suppress
signed-integer-overflow, unless signed-integer-overflow is explicitly
enabled. Implement this suppression.


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


2 Files Affected:

- (modified) clang/lib/Driver/SanitizerArgs.cpp (+8) 
- (added) clang/test/Driver/fsanitize-signed-integer-overflow.c (+28) 


``diff
diff --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 56d497eb4c32b8..8bfe9f02a091d1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -487,6 +487,14 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
 Add &= ~NotAllowedWithExecuteOnly;
   if (CfiCrossDso)
 Add &= ~SanitizerKind::CFIMFCall;
+  // -fsanitize=undefined does not expand to signed-integer-overflow in
+  // -fwrapv (implied by -fno-strict-overflow) mode.
+  if (Add & SanitizerKind::UndefinedGroup) {
+bool S = Args.hasFlagNoClaim(options::OPT_fno_strict_overflow,
+ options::OPT_fstrict_overflow, false);
+if (Args.hasFlagNoClaim(options::OPT_fwrapv, options::OPT_fno_wrapv, 
S))
+  Add &= ~SanitizerKind::SignedIntegerOverflow;
+  }
   Add &= Supported;
 
   if (Add & SanitizerKind::Fuzzer)
diff --git a/clang/test/Driver/fsanitize-signed-integer-overflow.c 
b/clang/test/Driver/fsanitize-signed-integer-overflow.c
new file mode 100644
index 00..4a9345493b6aa8
--- /dev/null
+++ b/clang/test/Driver/fsanitize-signed-integer-overflow.c
@@ -0,0 +1,28 @@
+/// When -fwrapv (implied by -fno-strict-overflow) is enabled,
+/// -fsanitize=undefined does not expand to signed-integer-overflow.
+/// -fsanitize=signed-integer-overflow is unaffected by -fwrapv.
+
+// RUN: %clang -### --target=x86_64-linux -fwrapv 
-fsanitize=signed-integer-overflow %s 2>&1 | FileCheck %s
+// CHECK: -fsanitize=signed-integer-overflow
+// CHECK: -fsanitize-recover=signed-integer-overflow
+
+// RUN: %clang -### --target=x86_64-linux -fno-strict-overflow 
-fsanitize=undefined %s 2>&1 | FileCheck %s --check-prefix=EXCLUDE
+// RUN: %clang -### --target=x86_64-linux -fstrict-overflow -fwrapv 
-fsanitize=undefined %s 2>&1 | FileCheck %s --check-prefix=EXCLUDE
+// EXCLUDE: -fsanitize=alignment,array-bounds,
+// EXCLUDE-NOT: signed-integer-overflow,
+// EXCLUDE:  -fsanitize-recover=alignment,array-bounds,
+// EXCLUDE-SAME: signed-integer-overflow
+
+// RUN: %clang -### --target=x86_64-linux -fwrapv -fsanitize=undefined 
-fsanitize=signed-integer-overflow %s 2>&1 | FileCheck %s --check-prefix=INCLUDE
+// RUN: %clang -### --target=x86_64-linux -fno-strict-overflow 
-fno-sanitize=signed-integer-overflow -fsanitize=undefined 
-fsanitize=signed-integer-overflow %s 2>&1 | FileCheck %s --check-prefix=INCLUDE
+// INCLUDE:  -fsanitize=alignment,array-bounds,
+// INCLUDE-SAME: signed-integer-overflow
+// INCLUDE:  -fsanitize-recover=alignment,array-bounds,
+// INCLUDE-SAME: signed-integer-overflow
+
+/// -fsanitize-trap=undefined expands to signed-integer-overflow regardless of 
-fwrapv.
+// RUN: %clang -### --target=x86_64-linux -fwrapv -fsanitize=undefined 
-fsanitize=signed-integer-overflow -fsanitize-trap=undefined %s 2>&1 | 
FileCheck %s --check-prefix=INCLUDE-TRAP
+// INCLUDE-TRAP:  -fsanitize=alignment,array-bounds,
+// INCLUDE-TRAP-SAME: signed-integer-overflow
+// INCLUDE-TRAP:  -fsanitize-trap=alignment,array-bounds,
+// INCLUDE-TRAP-SAME: signed-integer-overflow

``




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


[clang] [Driver] -fsanitize=undefined: don't expand to signed-integer-overflow if -fwrapv (PR #85501)

2024-03-15 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay created 
https://github.com/llvm/llvm-project/pull/85501

Linux kernel uses -fwrapv to change signed integer overflows from
undefined behaviors to defined behaviors. However, the security folks
still want -fsanitize=signed-integer-overflow diagnostics. Their
intention can be expressed with -fwrapv
-fsanitize=signed-integer-overflow (#80089). This mode by default
reports recoverable errors while still making signed integer overflows
defined (most UBSan checks are recoverable by default: you get errors in
stderr, but the program is not halted).

-fsanitize=undefined -fwrapv users likely want to suppress
signed-integer-overflow, unless signed-integer-overflow is explicitly
enabled. Implement this suppression.


>From d4cd5d737fbd686d54377584288ee336b95fe113 Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Fri, 15 Mar 2024 23:44:24 -0700
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.5-bogner
---
 clang/lib/Driver/SanitizerArgs.cpp|  8 ++
 .../fsanitize-signed-integer-overflow.c   | 28 +++
 2 files changed, 36 insertions(+)
 create mode 100644 clang/test/Driver/fsanitize-signed-integer-overflow.c

diff --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 56d497eb4c32b8..8bfe9f02a091d1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -487,6 +487,14 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
 Add &= ~NotAllowedWithExecuteOnly;
   if (CfiCrossDso)
 Add &= ~SanitizerKind::CFIMFCall;
+  // -fsanitize=undefined does not expand to signed-integer-overflow in
+  // -fwrapv (implied by -fno-strict-overflow) mode.
+  if (Add & SanitizerKind::UndefinedGroup) {
+bool S = Args.hasFlagNoClaim(options::OPT_fno_strict_overflow,
+ options::OPT_fstrict_overflow, false);
+if (Args.hasFlagNoClaim(options::OPT_fwrapv, options::OPT_fno_wrapv, 
S))
+  Add &= ~SanitizerKind::SignedIntegerOverflow;
+  }
   Add &= Supported;
 
   if (Add & SanitizerKind::Fuzzer)
diff --git a/clang/test/Driver/fsanitize-signed-integer-overflow.c 
b/clang/test/Driver/fsanitize-signed-integer-overflow.c
new file mode 100644
index 00..4a9345493b6aa8
--- /dev/null
+++ b/clang/test/Driver/fsanitize-signed-integer-overflow.c
@@ -0,0 +1,28 @@
+/// When -fwrapv (implied by -fno-strict-overflow) is enabled,
+/// -fsanitize=undefined does not expand to signed-integer-overflow.
+/// -fsanitize=signed-integer-overflow is unaffected by -fwrapv.
+
+// RUN: %clang -### --target=x86_64-linux -fwrapv 
-fsanitize=signed-integer-overflow %s 2>&1 | FileCheck %s
+// CHECK: -fsanitize=signed-integer-overflow
+// CHECK: -fsanitize-recover=signed-integer-overflow
+
+// RUN: %clang -### --target=x86_64-linux -fno-strict-overflow 
-fsanitize=undefined %s 2>&1 | FileCheck %s --check-prefix=EXCLUDE
+// RUN: %clang -### --target=x86_64-linux -fstrict-overflow -fwrapv 
-fsanitize=undefined %s 2>&1 | FileCheck %s --check-prefix=EXCLUDE
+// EXCLUDE: -fsanitize=alignment,array-bounds,
+// EXCLUDE-NOT: signed-integer-overflow,
+// EXCLUDE:  -fsanitize-recover=alignment,array-bounds,
+// EXCLUDE-SAME: signed-integer-overflow
+
+// RUN: %clang -### --target=x86_64-linux -fwrapv -fsanitize=undefined 
-fsanitize=signed-integer-overflow %s 2>&1 | FileCheck %s --check-prefix=INCLUDE
+// RUN: %clang -### --target=x86_64-linux -fno-strict-overflow 
-fno-sanitize=signed-integer-overflow -fsanitize=undefined 
-fsanitize=signed-integer-overflow %s 2>&1 | FileCheck %s --check-prefix=INCLUDE
+// INCLUDE:  -fsanitize=alignment,array-bounds,
+// INCLUDE-SAME: signed-integer-overflow
+// INCLUDE:  -fsanitize-recover=alignment,array-bounds,
+// INCLUDE-SAME: signed-integer-overflow
+
+/// -fsanitize-trap=undefined expands to signed-integer-overflow regardless of 
-fwrapv.
+// RUN: %clang -### --target=x86_64-linux -fwrapv -fsanitize=undefined 
-fsanitize=signed-integer-overflow -fsanitize-trap=undefined %s 2>&1 | 
FileCheck %s --check-prefix=INCLUDE-TRAP
+// INCLUDE-TRAP:  -fsanitize=alignment,array-bounds,
+// INCLUDE-TRAP-SAME: signed-integer-overflow
+// INCLUDE-TRAP:  -fsanitize-trap=alignment,array-bounds,
+// INCLUDE-TRAP-SAME: signed-integer-overflow

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


[clang] [AArch64][PAC][clang][ELF] Support PAuth ABI compatibility tag (PR #85235)

2024-03-15 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 4a21e3afa29521192ce686605eb945495455ca5e 
435c7eae0148f950a56c017fab408a69bedd84af -- 
clang/test/CodeGen/aarch64-elf-pauthabi.c clang/test/Driver/ptrauth.c 
clang/test/Preprocessor/ptrauth.c clang/include/clang/Basic/LangOptions.h 
clang/lib/CodeGen/CodeGenModule.cpp clang/lib/Driver/ToolChains/Clang.cpp 
clang/lib/Frontend/CompilerInvocation.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 800973fa33..dd8bdfe07b 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7186,8 +7186,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
options::OPT_fno_ptrauth_intrinsics, false))
 CmdArgs.push_back("-fptrauth-intrinsics");
 
-  if (Args.hasFlag(options::OPT_fptrauth_calls,
-   options::OPT_fno_ptrauth_calls, false))
+  if (Args.hasFlag(options::OPT_fptrauth_calls, options::OPT_fno_ptrauth_calls,
+   false))
 CmdArgs.push_back("-fptrauth-calls");
 
   if (Args.hasFlag(options::OPT_fptrauth_returns,
@@ -7210,8 +7210,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 CmdArgs.push_back("-fptrauth-vtable-pointer-type-discrimination");
 
   if (Args.hasFlag(options::OPT_fptrauth_init_fini,
-   options::OPT_fno_ptrauth_init_fini,
-   false))
+   options::OPT_fno_ptrauth_init_fini, false))
 CmdArgs.push_back("-fptrauth-init-fini");
 
   // -fsigned-bitfields is default, and clang doesn't yet support

``




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


[clang] [PAC][clang] Define ptrauth driver flags and preprocessor features (PR #85232)

2024-03-15 Thread Daniil Kovalev via cfe-commits

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


[clang] [AArch64][PAC][clang][ELF] Support PAuth ABI compatibility tag (PR #85235)

2024-03-15 Thread Daniil Kovalev via cfe-commits

https://github.com/kovdan01 updated 
https://github.com/llvm/llvm-project/pull/85235

>From 8e65b4402201f74d5312ed257c4abde4a6615964 Mon Sep 17 00:00:00 2001
From: Daniil Kovalev 
Date: Thu, 14 Mar 2024 12:19:26 +0300
Subject: [PATCH 1/2] [PAC][clang] Define ptrauth driver flags and preprocessor
 features

Define the following clang driver flags:

- `-fptrauth-intrinsics`: `PointerAuth.intrinsics()` in `LangOptions`,
  `ptrauth_intrinsics` preprocessor feature;

- `-fptrauth-calls`: `PointerAuth.calls()` in `LangOptions`, `ptrauth_calls` and
  and `ptrauth_member_function_pointer_type_discrimination` preprocessor
  features;

- `-fptrauth-returns`: `PointerAuth.returns()` in `LangOptions`,
  `ptrauth_returns` preprocessor feature;

- `-fptrauth-auth-traps`: `PointerAuth.authTraps()` in `LangOptions`;

- `-fptrauth-vtable-pointer-address-discrimination`:
  `PointerAuth.vtptrAddressDiscrimination()` in `LangOptions`,
  `ptrauth_vtable_pointer_address_discrimination` preprocessor feature;

- `-fptrauth-vtable-pointer-type-discrimination`:
  `PointerAuth.vtptrTypeDiscrimination()` in `LangOptions`,
  `ptrauth_vtable_pointer_type_discrimination` preprocessor feature;

- `-fptrauth-init-fini`: `PointerAuth.initFini()` in `LangOptions`,
  `ptrauth_init_fini` preprocessor feature.

The patch only defines the flags and having corresponding `LangOptions`
set does not affect codegen yet.

Co-authored-by: Ahmed Bougacha 
---
 clang/include/clang/Basic/Features.def|   7 ++
 clang/include/clang/Basic/LangOptions.h   |  18 
 clang/include/clang/Driver/Options.td |  26 +
 clang/lib/Driver/ToolChains/Clang.cpp |  32 ++
 clang/lib/Frontend/CompilerInvocation.cpp |  33 +++
 clang/test/Driver/ptrauth.c   |  32 ++
 clang/test/Preprocessor/ptrauth.c | 113 ++
 7 files changed, 261 insertions(+)
 create mode 100644 clang/test/Driver/ptrauth.c
 create mode 100644 clang/test/Preprocessor/ptrauth.c

diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index 5fad5fc3623cb6..182a44a1079ef2 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -101,6 +101,13 @@ FEATURE(memory_sanitizer,
 FEATURE(thread_sanitizer, LangOpts.Sanitize.has(SanitizerKind::Thread))
 FEATURE(dataflow_sanitizer, LangOpts.Sanitize.has(SanitizerKind::DataFlow))
 FEATURE(scudo, LangOpts.Sanitize.hasOneOf(SanitizerKind::Scudo))
+FEATURE(ptrauth_intrinsics, LangOpts.PointerAuth.intrinsics())
+FEATURE(ptrauth_calls, LangOpts.PointerAuth.calls())
+FEATURE(ptrauth_returns, LangOpts.PointerAuth.returns())
+FEATURE(ptrauth_vtable_pointer_address_discrimination, 
LangOpts.PointerAuth.vtptrAddressDiscrimination())
+FEATURE(ptrauth_vtable_pointer_type_discrimination, 
LangOpts.PointerAuth.vtptrTypeDiscrimination())
+FEATURE(ptrauth_member_function_pointer_type_discrimination, 
LangOpts.PointerAuth.calls())
+FEATURE(ptrauth_init_fini, LangOpts.PointerAuth.initFini())
 FEATURE(swiftasynccc,
   PP.getTargetInfo().checkCallingConvention(CC_SwiftAsync) ==
   clang::TargetInfo::CCCR_OK)
diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 862952d336ef31..e9ade66a8df2ac 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -532,6 +532,24 @@ class LangOptions : public LangOptionsBase {
   // implementation on real-world examples.
   std::string OpenACCMacroOverride;
 
+  struct {
+bool Flags[7] = {false};
+bool intrinsics() const { return Flags[0]; }
+bool &intrinsics() { return Flags[0]; }
+bool calls() const { return Flags[1]; }
+bool &calls() { return Flags[1]; }
+bool returns() const { return Flags[2]; }
+bool &returns() { return Flags[2]; }
+bool authTraps() const { return Flags[3]; }
+bool &authTraps() { return Flags[3]; }
+bool vtptrAddressDiscrimination() const { return Flags[4]; }
+bool &vtptrAddressDiscrimination() { return Flags[4]; }
+bool vtptrTypeDiscrimination() const { return Flags[5]; }
+bool &vtptrTypeDiscrimination() { return Flags[5]; }
+bool initFini() const { return Flags[6]; }
+bool &initFini() { return Flags[6]; }
+  } PointerAuth;
+
   LangOptions();
 
   /// Set language defaults for the given input language and
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index aca8c9b0d5487a..868b164d8f7174 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4085,6 +4085,32 @@ defm strict_return : BoolFOption<"strict-return",
 " of a non-void function as unreachable">,
   PosFlag>;
 
+let Group = f_Group in {
+  let Visibility = [ClangOption,CC1Option] in {
+def fptrauth_intrinsics : Flag<["-"], "fptrauth-intrinsics">,
+  HelpText<"Enable pointer-authentication intrinsics">;
+def fptrauth_calls : Flag<["-"], "fptrauth-calls">,
+  HelpText<"

[clang] [AArch64][PAC][clang][ELF] Support PAuth ABI compatibility tag (PR #85235)

2024-03-15 Thread Daniil Kovalev via cfe-commits

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


[clang] [clang-format] Correctly parse C++11 attributes in enum specifiers (PR #85498)

2024-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Fixes #85476.

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


2 Files Affected:

- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+9-6) 
- (modified) clang/unittests/Format/FormatTest.cpp (+21) 


``diff
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index a1f6ce05e45ebc..2b893f7abe4023 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1224,7 +1224,6 @@ void UnwrappedLineParser::parsePPUnknown() {
 static bool tokenCanStartNewLine(const FormatToken &Tok) {
   // Semicolon can be a null-statement, l_square can be a start of a macro or
   // a C++11 attribute, but this doesn't seem to be common.
-  assert(Tok.isNot(TT_AttributeSquare));
   return !Tok.isOneOf(tok::semi, tok::l_brace,
   // Tokens that can only be used as binary operators and a
   // part of overloaded operator names.
@@ -3712,14 +3711,19 @@ bool UnwrappedLineParser::parseEnum() {
   if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
 return false;
 
-  // Eat up enum class ...
-  if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
-nextToken();
+  if (IsCpp) {
+// Eat up enum class ...
+if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
+  nextToken();
+while (FormatTok->is(tok::l_square))
+  if (!handleCppAttributes())
+return false;
+  }
 
   while (FormatTok->Tok.getIdentifierInfo() ||
  FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
 tok::greater, tok::comma, tok::question,
-tok::l_square, tok::r_square)) {
+tok::l_square)) {
 if (Style.isVerilog()) {
   FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
   nextToken();
@@ -3732,7 +3736,6 @@ bool UnwrappedLineParser::parseEnum() {
 // We can have macros or attributes in between 'enum' and the enum name.
 if (FormatTok->is(tok::l_paren))
   parseParens();
-assert(FormatTok->isNot(TT_AttributeSquare));
 if (FormatTok->is(tok::identifier)) {
   nextToken();
   // If there are two identifiers in a row, this is likely an elaborate
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index fc367a7a5a8981..add92d3e111089 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3802,6 +3802,27 @@ TEST_F(FormatTest, FormatsEnum) {
"  // Comment 2\n"
"  TWO,\n"
"};");
+  verifyFormat("enum [[clang::enum_extensibility(open)]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO\n"
+   "};");
+  verifyFormat("enum [[nodiscard]] [[clang::enum_extensibility(open)]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO\n"
+   "};");
+  verifyFormat("enum [[clang::enum_extensibility(open)]] E { // foo\n"
+   "  A,\n"
+   "  // bar\n"
+   "  B\n"
+   "};",
+   "enum [[clang::enum_extensibility(open)]] E{// foo\n"
+   "   A,\n"
+   "   // bar\n"
+   "   B};");
 
   // Not enums.
   verifyFormat("enum X f() {\n"

``




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


[clang] [clang-format] Correctly parse C++11 attributes in enum specifiers (PR #85498)

2024-03-15 Thread Owen Pan via cfe-commits

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

Fixes #85476.

>From 89c06a9acfebffa4f9e65c6d683c3c46774edc88 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 15 Mar 2024 22:14:01 -0700
Subject: [PATCH] [clang-format] Correctly parse C++11 attributes in enum
 specifiers

Fixes #85476.
---
 clang/lib/Format/UnwrappedLineParser.cpp | 15 +--
 clang/unittests/Format/FormatTest.cpp| 21 +
 2 files changed, 30 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index a1f6ce05e45ebc..2b893f7abe4023 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1224,7 +1224,6 @@ void UnwrappedLineParser::parsePPUnknown() {
 static bool tokenCanStartNewLine(const FormatToken &Tok) {
   // Semicolon can be a null-statement, l_square can be a start of a macro or
   // a C++11 attribute, but this doesn't seem to be common.
-  assert(Tok.isNot(TT_AttributeSquare));
   return !Tok.isOneOf(tok::semi, tok::l_brace,
   // Tokens that can only be used as binary operators and a
   // part of overloaded operator names.
@@ -3712,14 +3711,19 @@ bool UnwrappedLineParser::parseEnum() {
   if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
 return false;
 
-  // Eat up enum class ...
-  if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
-nextToken();
+  if (IsCpp) {
+// Eat up enum class ...
+if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
+  nextToken();
+while (FormatTok->is(tok::l_square))
+  if (!handleCppAttributes())
+return false;
+  }
 
   while (FormatTok->Tok.getIdentifierInfo() ||
  FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
 tok::greater, tok::comma, tok::question,
-tok::l_square, tok::r_square)) {
+tok::l_square)) {
 if (Style.isVerilog()) {
   FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
   nextToken();
@@ -3732,7 +3736,6 @@ bool UnwrappedLineParser::parseEnum() {
 // We can have macros or attributes in between 'enum' and the enum name.
 if (FormatTok->is(tok::l_paren))
   parseParens();
-assert(FormatTok->isNot(TT_AttributeSquare));
 if (FormatTok->is(tok::identifier)) {
   nextToken();
   // If there are two identifiers in a row, this is likely an elaborate
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index fc367a7a5a8981..add92d3e111089 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3802,6 +3802,27 @@ TEST_F(FormatTest, FormatsEnum) {
"  // Comment 2\n"
"  TWO,\n"
"};");
+  verifyFormat("enum [[clang::enum_extensibility(open)]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO\n"
+   "};");
+  verifyFormat("enum [[nodiscard]] [[clang::enum_extensibility(open)]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO\n"
+   "};");
+  verifyFormat("enum [[clang::enum_extensibility(open)]] E { // foo\n"
+   "  A,\n"
+   "  // bar\n"
+   "  B\n"
+   "};",
+   "enum [[clang::enum_extensibility(open)]] E{// foo\n"
+   "   A,\n"
+   "   // bar\n"
+   "   B};");
 
   // Not enums.
   verifyFormat("enum X f() {\n"

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


[clang] 426bf0c - [clang][Interp] Try to fix builtin-functions test on AIX

2024-03-15 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-03-16T06:05:03+01:00
New Revision: 426bf0c915aca9e9d78b6192898b95a44d9afcf4

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

LOG: [clang][Interp] Try to fix builtin-functions test on AIX

See
https://github.com/llvm/llvm-project/commit/0a739eb75fe68b1cec4e4aaad8b5395bb5da9a89#commitcomment-139850284

Added: 


Modified: 
clang/test/AST/Interp/builtin-functions.cpp

Removed: 




diff  --git a/clang/test/AST/Interp/builtin-functions.cpp 
b/clang/test/AST/Interp/builtin-functions.cpp
index 6c8df99a159730..a09c6d3acca5da 100644
--- a/clang/test/AST/Interp/builtin-functions.cpp
+++ b/clang/test/AST/Interp/builtin-functions.cpp
@@ -514,7 +514,9 @@ namespace bswap {
 #define CFSTR __builtin___CFStringMakeConstantString
 void test7(void) {
   const void *X;
+#if !defined(_AIX)
   X = CFSTR("\242"); // both-warning {{input conversion stopped}}
+#endif
   X = CFSTR("\0"); // no-warning
   X = CFSTR(242); // both-error {{cannot initialize a parameter of type 'const 
char *' with an rvalue of type 'int'}}
   X = CFSTR("foo", "bar"); // both-error {{too many arguments to function 
call}}



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


[clang] fix: constexpr bit_cast with empty base classes (PR #82383)

2024-03-15 Thread Timm Baeder via cfe-commits

tbaederr wrote:

There's still a merge conflict now. Do you not have the necessary permissions 
to merge it yourself?

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: Younan Zhang (zyn0217)


Changes

This is in preparation for implementing go-to-definition support on type inlay 
hints, switching the label field within the InlayHint protocol to an array of 
InlayHintLabelPart.

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


7 Files Affected:

- (modified) clang-tools-extra/clangd/ClangdLSPServer.cpp (+1-1) 
- (modified) clang-tools-extra/clangd/InlayHints.cpp (+3-2) 
- (modified) clang-tools-extra/clangd/Protocol.cpp (+39-1) 
- (modified) clang-tools-extra/clangd/Protocol.h (+40-1) 
- (modified) clang-tools-extra/clangd/test/inlayHints.test (+5-1) 
- (modified) clang-tools-extra/clangd/tool/Check.cpp (+7-1) 
- (modified) clang-tools-extra/clangd/unittests/InlayHintTests.cpp (+5-4) 


``diff
diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index f29dadde2b86d5..7fd599d4e1a0b0 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1390,7 +1390,7 @@ void ClangdLSPServer::onClangdInlayHints(const 
InlayHintsParams &Params,
   // Extension doesn't have paddingLeft/Right so adjust the label
   // accordingly.
   {"label",
-   ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.label) +
+   ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.joinLabels()) 
+
 (Hint.paddingRight ? " " : ""))
.str()},
   });
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index a0ebc631ef8285..cd4f1931b3ce1d 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -977,8 +977,9 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
   return;
 bool PadLeft = Prefix.consume_front(" ");
 bool PadRight = Suffix.consume_back(" ");
-Results.push_back(InlayHint{LSPPos, (Prefix + Label + Suffix).str(), Kind,
-PadLeft, PadRight, LSPRange});
+Results.push_back(InlayHint{LSPPos,
+/*label=*/{(Prefix + Label + Suffix).str()},
+Kind, PadLeft, PadRight, LSPRange});
   }
 
   // Get the range of the main file that *exactly* corresponds to R.
diff --git a/clang-tools-extra/clangd/Protocol.cpp 
b/clang-tools-extra/clangd/Protocol.cpp
index 8aa18bb0058abe..b1e29953337256 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -1483,9 +1483,18 @@ llvm::json::Value toJSON(const InlayHintKind &Kind) {
   llvm_unreachable("Unknown clang.clangd.InlayHintKind");
 }
 
+namespace {
+
+llvm::json::Array toJSON(const std::vector &Labels) {
+  return llvm::json::Array{
+  llvm::map_range(Labels, [](auto &Label) { return toJSON(Label); })};
+}
+
+} // namespace
+
 llvm::json::Value toJSON(const InlayHint &H) {
   llvm::json::Object Result{{"position", H.position},
-{"label", H.label},
+{"label", toJSON(H.label)},
 {"paddingLeft", H.paddingLeft},
 {"paddingRight", H.paddingRight}};
   auto K = toJSON(H.kind);
@@ -1501,6 +1510,10 @@ bool operator<(const InlayHint &A, const InlayHint &B) {
   return std::tie(A.position, A.range, A.kind, A.label) <
  std::tie(B.position, B.range, B.kind, B.label);
 }
+std::string InlayHint::joinLabels() const {
+  return llvm::join(llvm::map_range(label, [](auto &L) { return L.value; }),
+"");
+}
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, InlayHintKind Kind) {
   auto ToString = [](InlayHintKind K) {
@@ -1519,6 +1532,31 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 
InlayHintKind Kind) {
   return OS << ToString(Kind);
 }
 
+llvm::json::Value toJSON(const InlayHintLabelPart &L) {
+  llvm::json::Object Result{{"value", L.value}};
+  if (L.tooltip)
+Result["tooltip"] = *L.tooltip;
+  if (L.location)
+Result["location"] = *L.location;
+  return Result;
+}
+
+bool operator==(const InlayHintLabelPart &LHS, const InlayHintLabelPart &RHS) {
+  return std::tie(LHS.value, LHS.location) == std::tie(RHS.value, 
RHS.location);
+}
+
+bool operator<(const InlayHintLabelPart &LHS, const InlayHintLabelPart &RHS) {
+  return std::tie(LHS.value, LHS.location) < std::tie(RHS.value, RHS.location);
+}
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+  const InlayHintLabelPart &L) {
+  OS << L.value;
+  if (L.location)
+OS << " (" << L.location << ")";
+  return OS;
+}
+
 static const char *toString(OffsetEncoding OE) {
   switch (OE) {
   case OffsetEncoding::UTF8:
diff --git a/clang-tools-extra/clangd/Protocol.h 
b/clang-tools-extra/clangd/Protocol.h
index 358d4c6feaf87d..6fd6b9955bfb91 100644
--- a/clang-tools-extra/clangd/Protocol.h
+++ b/clang-tools-extra/clangd/Protocol.h
@@ -1

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-15 Thread Younan Zhang via cfe-commits

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


[clang] [Concepts] Add Decls from the outer scope of the current lambda for conversion function constraints (PR #83420)

2024-03-15 Thread Younan Zhang via cfe-commits

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


[clang] 3e69e5a - [Concepts] Add Decls from the outer scope of the current lambda for conversion function constraints (#83420)

2024-03-15 Thread via cfe-commits

Author: Younan Zhang
Date: 2024-03-16T12:56:11+08:00
New Revision: 3e69e5a15782a5776a3245170aeb5d97ef746fa5

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

LOG: [Concepts] Add Decls from the outer scope of the current lambda for 
conversion function constraints (#83420)

This fixes the case shown by
https://github.com/llvm/llvm-project/issues/64808#issuecomment-1929131611.

Similar to
https://github.com/llvm/llvm-project/commit/f9caa12328b265b77221fe7a310d4504673d814a,
we have some calls to constraint checking for a lambda's conversion
function while determining the conversion sequence.

This patch addresses the problem where the requires-expression within
such a lambda references to a Decl outside of the lambda by adding these
Decls to the current instantiation scope.

I'm abusing the flag `ForOverloadResolution` of
CheckFunctionConstraints, which is actually meant to consider the Decls
from parent DeclContexts.

-

Co-authored-by: cor3ntin 

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaConcept.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1ae35e6881d2f8..93cc5291e2391f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -387,6 +387,8 @@ Bug Fixes to C++ Support
   Fixes (#GH80997)
 - Fix an issue where missing set friend declaration in template class 
instantiation.
   Fixes (#GH84368).
+- Fixed a crash while checking constraints of a trailing requires-expression 
of a lambda, that the
+  expression references to an entity declared outside of the lambda. (#GH64808)
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index a8e387e35fb4c9..1c546e9f5894f0 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -692,11 +692,15 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl 
*FD,
   // A lambda conversion operator has the same constraints as the call operator
   // and constraints checking relies on whether we are in a lambda call 
operator
   // (and may refer to its parameters), so check the call operator instead.
+  // Note that the declarations outside of the lambda should also be
+  // considered. Turning on the 'ForOverloadResolution' flag results in the
+  // LocalInstantiationScope not looking into its parents, but we can still
+  // access Decls from the parents while building a lambda RAII scope later.
   if (const auto *MD = dyn_cast(FD);
   MD && isLambdaConversionOperator(const_cast(MD)))
 return CheckFunctionConstraints(MD->getParent()->getLambdaCallOperator(),
 Satisfaction, UsageLoc,
-ForOverloadResolution);
+/*ShouldAddDeclsFromParentScope=*/true);
 
   DeclContext *CtxToSave = const_cast(FD);
 

diff  --git a/clang/test/SemaTemplate/concepts.cpp 
b/clang/test/SemaTemplate/concepts.cpp
index bac209a28da912..b7ea0d003a52d7 100644
--- a/clang/test/SemaTemplate/concepts.cpp
+++ b/clang/test/SemaTemplate/concepts.cpp
@@ -1085,3 +1085,32 @@ template void Struct::bar<>();
 template int Struct::field<1, 2>;
 
 }
+
+namespace GH64808 {
+
+template  struct basic_sender {
+  T func;
+  basic_sender(T) : func(T()) {}
+};
+
+auto a = basic_sender{[](auto... __captures) {
+  return []() // #note-a-1
+requires((__captures, ...), false) // #note-a-2
+  {};
+}()};
+
+auto b = basic_sender{[](auto... __captures) {
+  return []()
+requires([](int, double) { return true; }(decltype(__captures)()...))
+  {};
+}(1, 2.33)};
+
+void foo() {
+  a.func();
+  // expected-error@-1{{no matching function for call}}
+  // expected-note@#note-a-1{{constraints not satisfied}}
+  // expected-note@#note-a-2{{evaluated to false}}
+  b.func();
+}
+
+} // namespace GH64808



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


[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2024-03-15 Thread via cfe-commits


@@ -0,0 +1,11 @@
+// Note: %s must be preceded by --, otherwise it may be interpreted as a
+// command-line option, e.g. on Mac where %s is commonly under /Users.
+//
+// Note: see also cl-zc.cpp
+
+// RUN: %clang_cl /TC /dev/null /E -Xclang -dM /Zc:__STDC__- 2>&1 | FileCheck 
%s --check-prefix=ZCSTDCIGNORED
+// ZCSTDCIGNORED-NOT: #define __STDC__ 1
+// ZCSTDCIGNORED: argument unused during compilation
+
+// RUN: not %clang -Xclang -fno-ms-define-stdc %s 2>&1 | FileCheck %s 
--check-prefix="NOARG"

xbjfk wrote:

Hmmm, this test was requested by @AaronBallman - what would you do in this case?

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-15 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff fd3eaf76ba3392a4406247d996e757ef49f7a8b2 
6d61aa1e43bb522412904bdd77c7f1cfc4b42889 -- 
clang-tools-extra/clangd/ClangdLSPServer.cpp 
clang-tools-extra/clangd/InlayHints.cpp clang-tools-extra/clangd/Protocol.cpp 
clang-tools-extra/clangd/Protocol.h clang-tools-extra/clangd/tool/Check.cpp 
clang-tools-extra/clangd/unittests/InlayHintTests.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index 5a9ec9ab67..cd4f1931b3 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -979,10 +979,7 @@ private:
 bool PadRight = Suffix.consume_back(" ");
 Results.push_back(InlayHint{LSPPos,
 /*label=*/{(Prefix + Label + Suffix).str()},
-Kind,
-PadLeft,
-PadRight,
-LSPRange});
+Kind, PadLeft, PadRight, LSPRange});
   }
 
   // Get the range of the main file that *exactly* corresponds to R.
diff --git a/clang-tools-extra/clangd/Protocol.h 
b/clang-tools-extra/clangd/Protocol.h
index 1f9c562552..6fd6b9955b 100644
--- a/clang-tools-extra/clangd/Protocol.h
+++ b/clang-tools-extra/clangd/Protocol.h
@@ -1701,21 +1701,21 @@ struct InlayHintLabelPart {
   std::string value;
 
   /// The tooltip text when you hover over this label part. Depending on
-   /// the client capability `inlayHint.resolveSupport`, clients might 
resolve
-   /// this property late using the resolve request.
+  /// the client capability `inlayHint.resolveSupport`, clients might resolve
+  /// this property late using the resolve request.
   std::optional tooltip;
 
-   /// An optional source code location that represents this
-   /// label part.
-   ///
-   /// The editor will use this location for the hover and for code 
navigation
-   /// features: This part will become a clickable link that resolves to 
the
-   /// definition of the symbol at the given location (not necessarily the
-   /// location itself), it shows the hover that shows at the given 
location,
-   /// and it shows a context menu with further code navigation commands.
-   ///
-   /// Depending on the client capability `inlayHint.resolveSupport` 
clients
-   /// might resolve this property late using the resolve request.
+  /// An optional source code location that represents this
+  /// label part.
+  ///
+  /// The editor will use this location for the hover and for code navigation
+  /// features: This part will become a clickable link that resolves to the
+  /// definition of the symbol at the given location (not necessarily the
+  /// location itself), it shows the hover that shows at the given location,
+  /// and it shows a context menu with further code navigation commands.
+  ///
+  /// Depending on the client capability `inlayHint.resolveSupport` clients
+  /// might resolve this property late using the resolve request.
   std::optional location;
 
   /// The command field is not used for now, hence omitted.

``




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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-15 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/85497

>From 6d61aa1e43bb522412904bdd77c7f1cfc4b42889 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 12:33:58 +0800
Subject: [PATCH 1/2] [clangd] Support go-to-definition on type hints. The
 protocol part

This is in preparation for implementing go-to-definition support
on type inlay hints, switching the label field within the InlayHint
protocol to an array of InlayHintLabelPart.
---
 clang-tools-extra/clangd/ClangdLSPServer.cpp  |  2 +-
 clang-tools-extra/clangd/InlayHints.cpp   |  8 +++-
 clang-tools-extra/clangd/Protocol.cpp | 40 +-
 clang-tools-extra/clangd/Protocol.h   | 41 ++-
 clang-tools-extra/clangd/test/inlayHints.test |  6 ++-
 clang-tools-extra/clangd/tool/Check.cpp   |  8 +++-
 .../clangd/unittests/InlayHintTests.cpp   |  9 ++--
 7 files changed, 103 insertions(+), 11 deletions(-)

diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index f29dadde2b86d5..7fd599d4e1a0b0 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1390,7 +1390,7 @@ void ClangdLSPServer::onClangdInlayHints(const 
InlayHintsParams &Params,
   // Extension doesn't have paddingLeft/Right so adjust the label
   // accordingly.
   {"label",
-   ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.label) +
+   ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.joinLabels()) 
+
 (Hint.paddingRight ? " " : ""))
.str()},
   });
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index a0ebc631ef8285..5a9ec9ab6762fa 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -977,8 +977,12 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
   return;
 bool PadLeft = Prefix.consume_front(" ");
 bool PadRight = Suffix.consume_back(" ");
-Results.push_back(InlayHint{LSPPos, (Prefix + Label + Suffix).str(), Kind,
-PadLeft, PadRight, LSPRange});
+Results.push_back(InlayHint{LSPPos,
+/*label=*/{(Prefix + Label + Suffix).str()},
+Kind,
+PadLeft,
+PadRight,
+LSPRange});
   }
 
   // Get the range of the main file that *exactly* corresponds to R.
diff --git a/clang-tools-extra/clangd/Protocol.cpp 
b/clang-tools-extra/clangd/Protocol.cpp
index 8aa18bb0058abe..b1e29953337256 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -1483,9 +1483,18 @@ llvm::json::Value toJSON(const InlayHintKind &Kind) {
   llvm_unreachable("Unknown clang.clangd.InlayHintKind");
 }
 
+namespace {
+
+llvm::json::Array toJSON(const std::vector &Labels) {
+  return llvm::json::Array{
+  llvm::map_range(Labels, [](auto &Label) { return toJSON(Label); })};
+}
+
+} // namespace
+
 llvm::json::Value toJSON(const InlayHint &H) {
   llvm::json::Object Result{{"position", H.position},
-{"label", H.label},
+{"label", toJSON(H.label)},
 {"paddingLeft", H.paddingLeft},
 {"paddingRight", H.paddingRight}};
   auto K = toJSON(H.kind);
@@ -1501,6 +1510,10 @@ bool operator<(const InlayHint &A, const InlayHint &B) {
   return std::tie(A.position, A.range, A.kind, A.label) <
  std::tie(B.position, B.range, B.kind, B.label);
 }
+std::string InlayHint::joinLabels() const {
+  return llvm::join(llvm::map_range(label, [](auto &L) { return L.value; }),
+"");
+}
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, InlayHintKind Kind) {
   auto ToString = [](InlayHintKind K) {
@@ -1519,6 +1532,31 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 
InlayHintKind Kind) {
   return OS << ToString(Kind);
 }
 
+llvm::json::Value toJSON(const InlayHintLabelPart &L) {
+  llvm::json::Object Result{{"value", L.value}};
+  if (L.tooltip)
+Result["tooltip"] = *L.tooltip;
+  if (L.location)
+Result["location"] = *L.location;
+  return Result;
+}
+
+bool operator==(const InlayHintLabelPart &LHS, const InlayHintLabelPart &RHS) {
+  return std::tie(LHS.value, LHS.location) == std::tie(RHS.value, 
RHS.location);
+}
+
+bool operator<(const InlayHintLabelPart &LHS, const InlayHintLabelPart &RHS) {
+  return std::tie(LHS.value, LHS.location) < std::tie(RHS.value, RHS.location);
+}
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+  const InlayHintLabelPart &L) {
+  OS << L.value;
+  if (L.location)
+OS << " (" << L.location << ")";
+  return OS;
+}
+
 static const char *toString(OffsetEncoding OE) {
   switch (OE) {
   case Of

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-15 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 created 
https://github.com/llvm/llvm-project/pull/85497

This is in preparation for implementing go-to-definition support on type inlay 
hints, switching the label field within the InlayHint protocol to an array of 
InlayHintLabelPart.

>From 6d61aa1e43bb522412904bdd77c7f1cfc4b42889 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 12:33:58 +0800
Subject: [PATCH] [clangd] Support go-to-definition on type hints. The protocol
 part

This is in preparation for implementing go-to-definition support
on type inlay hints, switching the label field within the InlayHint
protocol to an array of InlayHintLabelPart.
---
 clang-tools-extra/clangd/ClangdLSPServer.cpp  |  2 +-
 clang-tools-extra/clangd/InlayHints.cpp   |  8 +++-
 clang-tools-extra/clangd/Protocol.cpp | 40 +-
 clang-tools-extra/clangd/Protocol.h   | 41 ++-
 clang-tools-extra/clangd/test/inlayHints.test |  6 ++-
 clang-tools-extra/clangd/tool/Check.cpp   |  8 +++-
 .../clangd/unittests/InlayHintTests.cpp   |  9 ++--
 7 files changed, 103 insertions(+), 11 deletions(-)

diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index f29dadde2b86d5..7fd599d4e1a0b0 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1390,7 +1390,7 @@ void ClangdLSPServer::onClangdInlayHints(const 
InlayHintsParams &Params,
   // Extension doesn't have paddingLeft/Right so adjust the label
   // accordingly.
   {"label",
-   ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.label) +
+   ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.joinLabels()) 
+
 (Hint.paddingRight ? " " : ""))
.str()},
   });
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index a0ebc631ef8285..5a9ec9ab6762fa 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -977,8 +977,12 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
   return;
 bool PadLeft = Prefix.consume_front(" ");
 bool PadRight = Suffix.consume_back(" ");
-Results.push_back(InlayHint{LSPPos, (Prefix + Label + Suffix).str(), Kind,
-PadLeft, PadRight, LSPRange});
+Results.push_back(InlayHint{LSPPos,
+/*label=*/{(Prefix + Label + Suffix).str()},
+Kind,
+PadLeft,
+PadRight,
+LSPRange});
   }
 
   // Get the range of the main file that *exactly* corresponds to R.
diff --git a/clang-tools-extra/clangd/Protocol.cpp 
b/clang-tools-extra/clangd/Protocol.cpp
index 8aa18bb0058abe..b1e29953337256 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -1483,9 +1483,18 @@ llvm::json::Value toJSON(const InlayHintKind &Kind) {
   llvm_unreachable("Unknown clang.clangd.InlayHintKind");
 }
 
+namespace {
+
+llvm::json::Array toJSON(const std::vector &Labels) {
+  return llvm::json::Array{
+  llvm::map_range(Labels, [](auto &Label) { return toJSON(Label); })};
+}
+
+} // namespace
+
 llvm::json::Value toJSON(const InlayHint &H) {
   llvm::json::Object Result{{"position", H.position},
-{"label", H.label},
+{"label", toJSON(H.label)},
 {"paddingLeft", H.paddingLeft},
 {"paddingRight", H.paddingRight}};
   auto K = toJSON(H.kind);
@@ -1501,6 +1510,10 @@ bool operator<(const InlayHint &A, const InlayHint &B) {
   return std::tie(A.position, A.range, A.kind, A.label) <
  std::tie(B.position, B.range, B.kind, B.label);
 }
+std::string InlayHint::joinLabels() const {
+  return llvm::join(llvm::map_range(label, [](auto &L) { return L.value; }),
+"");
+}
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, InlayHintKind Kind) {
   auto ToString = [](InlayHintKind K) {
@@ -1519,6 +1532,31 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 
InlayHintKind Kind) {
   return OS << ToString(Kind);
 }
 
+llvm::json::Value toJSON(const InlayHintLabelPart &L) {
+  llvm::json::Object Result{{"value", L.value}};
+  if (L.tooltip)
+Result["tooltip"] = *L.tooltip;
+  if (L.location)
+Result["location"] = *L.location;
+  return Result;
+}
+
+bool operator==(const InlayHintLabelPart &LHS, const InlayHintLabelPart &RHS) {
+  return std::tie(LHS.value, LHS.location) == std::tie(RHS.value, 
RHS.location);
+}
+
+bool operator<(const InlayHintLabelPart &LHS, const InlayHintLabelPart &RHS) {
+  return std::tie(LHS.value, LHS.location) < std::tie(RHS.value, RHS.location);
+}
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+  const InlayHintLabelPart &

[clang] Revert "[clang-format][NFC] Eliminate the IsCpp parameter in all functions" (PR #85353)

2024-03-15 Thread Owen Pan via cfe-commits

owenca wrote:

See e.g. https://lab.llvm.org/buildbot/#/builders/272/builds/11332.

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


[clang] 426e694 - [clang-format][NFC] Delete redundant and extraneous #include lines

2024-03-15 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2024-03-15T20:51:57-07:00
New Revision: 426e6945897afbec01c042bec4771522a2aac176

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

LOG: [clang-format][NFC] Delete redundant and extraneous #include lines

Added: 


Modified: 
clang/lib/Format/BreakableToken.h
clang/lib/Format/ContinuationIndenter.h
clang/lib/Format/Encoding.h
clang/lib/Format/Format.cpp
clang/lib/Format/FormatInternal.h
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.h
clang/lib/Format/FormatTokenSource.h
clang/lib/Format/Macros.h
clang/lib/Format/SortJavaScriptImports.h
clang/lib/Format/TokenAnalyzer.h
clang/lib/Format/TokenAnnotator.h
clang/lib/Format/UnwrappedLineFormatter.h
clang/lib/Format/UnwrappedLineParser.h
clang/lib/Format/WhitespaceManager.h

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.h 
b/clang/lib/Format/BreakableToken.h
index e7c0680641e294..8b9360a3335ef4 100644
--- a/clang/lib/Format/BreakableToken.h
+++ b/clang/lib/Format/BreakableToken.h
@@ -18,11 +18,8 @@
 #define LLVM_CLANG_LIB_FORMAT_BREAKABLETOKEN_H
 
 #include "Encoding.h"
-#include "TokenAnnotator.h"
 #include "WhitespaceManager.h"
 #include "llvm/ADT/StringSet.h"
-#include "llvm/Support/Regex.h"
-#include 
 
 namespace clang {
 namespace format {

diff  --git a/clang/lib/Format/ContinuationIndenter.h 
b/clang/lib/Format/ContinuationIndenter.h
index 2598947bb624c5..18441e10a12492 100644
--- a/clang/lib/Format/ContinuationIndenter.h
+++ b/clang/lib/Format/ContinuationIndenter.h
@@ -17,11 +17,6 @@
 
 #include "Encoding.h"
 #include "FormatToken.h"
-#include "clang/Format/Format.h"
-#include "llvm/Support/Regex.h"
-#include 
-#include 
-#include 
 
 namespace clang {
 class SourceManager;

diff  --git a/clang/lib/Format/Encoding.h b/clang/lib/Format/Encoding.h
index a0d664121b2bba..12f9043bb95ad8 100644
--- a/clang/lib/Format/Encoding.h
+++ b/clang/lib/Format/Encoding.h
@@ -16,7 +16,6 @@
 #define LLVM_CLANG_LIB_FORMAT_ENCODING_H
 
 #include "clang/Basic/LLVM.h"
-#include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/Unicode.h"
 

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index faf65c619b237b..d5d115a3c8db85 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -13,44 +13,16 @@
 
//===--===//
 
 #include "clang/Format/Format.h"
-#include "AffectedRangeManager.h"
-#include "BreakableToken.h"
-#include "ContinuationIndenter.h"
 #include "DefinitionBlockSeparator.h"
-#include "FormatInternal.h"
-#include "FormatToken.h"
-#include "FormatTokenLexer.h"
 #include "IntegerLiteralSeparatorFixer.h"
 #include "NamespaceEndCommentsFixer.h"
 #include "ObjCPropertyAttributeOrderFixer.h"
 #include "QualifierAlignmentFixer.h"
 #include "SortJavaScriptImports.h"
-#include "TokenAnalyzer.h"
-#include "TokenAnnotator.h"
 #include "UnwrappedLineFormatter.h"
-#include "UnwrappedLineParser.h"
 #include "UsingDeclarationsSorter.h"
-#include "WhitespaceManager.h"
-#include "clang/Basic/Diagnostic.h"
-#include "clang/Basic/DiagnosticOptions.h"
-#include "clang/Basic/SourceManager.h"
-#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Inclusions/HeaderIncludes.h"
-#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/Sequence.h"
-#include "llvm/ADT/StringRef.h"
-#include "llvm/Support/Allocator.h"
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/Path.h"
-#include "llvm/Support/Regex.h"
-#include "llvm/Support/VirtualFileSystem.h"
-#include "llvm/Support/YAMLTraits.h"
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
 
 #define DEBUG_TYPE "format-formatter"
 

diff  --git a/clang/lib/Format/FormatInternal.h 
b/clang/lib/Format/FormatInternal.h
index 9043ce32e9e32a..87974a853365c6 100644
--- a/clang/lib/Format/FormatInternal.h
+++ b/clang/lib/Format/FormatInternal.h
@@ -15,9 +15,6 @@
 #ifndef LLVM_CLANG_LIB_FORMAT_FORMATINTERNAL_H
 #define LLVM_CLANG_LIB_FORMAT_FORMATINTERNAL_H
 
-#include "BreakableToken.h"
-#include 
-
 namespace clang {
 namespace format {
 namespace internal {

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index ee96d072b12059..c9022aba287187 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -19,8 +19,6 @@
 #include "clang/Basic/OperatorPrecedence.h"
 #include "clang/Format/Format.h"
 #include "clang/Lex/Lexer.h"
-#include 
-#include 
 #include 
 
 namespace clang {

diff  --git a/clang/lib/Format/FormatTokenLexer.h 
b/clang/lib/Format/FormatTokenLexer.h
index 65dd733bd53352..277cc0a2dfde66 100644
--- a/clang/lib/Format/FormatTokenLexer.h
+++ b/clang/lib/Format/FormatTokenLexer.h
@@ -17,14 

[clang] [Sema] Allow -Wno-main to suppress the arg wrong error (PR #85494)

2024-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Fangrui Song (MaskRay)


Changes

The diagnostic is a warning in GCC. We make it a DefaultError warning
under -Wmain.

There is a use case to pass customized arguments to main without using 
-ffreestanding.

Close #85491


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


3 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2-2) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+1-1) 
- (modified) clang/test/CXX/basic/basic.start/basic.start.main/p2.cpp (+11) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 8e97902564af08..6cf4e288af5f1f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -950,9 +950,9 @@ def err_main_surplus_args : Error<"too many parameters (%0) 
for 'main': "
 "must be 0, 2, or 3">;
 def warn_main_one_arg : Warning<"only one parameter on 'main' declaration">,
 InGroup;
-def err_main_arg_wrong : Error<"%select{first|second|third|fourth}0 "
+def warn_main_arg_wrong : Warning<"%select{first|second|third|fourth}0 "
 "parameter of 'main' (%select{argument count|argument array|environment|"
-"platform-specific data}0) must be of type %1">;
+"platform-specific data}0) must be of type %1">, DefaultError, 
InGroup;
 def warn_main_returns_bool_literal : Warning<"bool literal returned from "
 "'main'">, InGroup;
 def err_main_global_variable :
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5850cd0ab6b9aa..2718934609842b 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -12488,7 +12488,7 @@ void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& 
DS) {
 }
 
 if (mismatch) {
-  Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
+  Diag(FD->getLocation(), diag::warn_main_arg_wrong) << i << Expected[i];
   // TODO: suggest replacing given type with expected type
   FD->setInvalidDecl(true);
 }
diff --git a/clang/test/CXX/basic/basic.start/basic.start.main/p2.cpp 
b/clang/test/CXX/basic/basic.start/basic.start.main/p2.cpp
index 42e87e5431f2a5..135c828e7366a0 100644
--- a/clang/test/CXX/basic/basic.start/basic.start.main/p2.cpp
+++ b/clang/test/CXX/basic/basic.start/basic.start.main/p2.cpp
@@ -4,6 +4,7 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST4
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST5
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST6
+// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST6A -Wno-main
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST7
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST8
 
@@ -64,6 +65,16 @@ main( // expected-error {{first parameter of 'main' 
(argument count) must be of
 
 const int main(); // expected-error {{'main' must return 'int'}}
 
+#elif TEST6A
+
+void  // expected-error {{'main' must return 'int'}}
+main(
+ float a
+) {
+}
+
+const int main(); // expected-error {{'main' must return 'int'}}
+
 #elif TEST7
 
 // expected-no-diagnostics

``




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


[clang] [Sema] Allow -Wno-main to suppress the arg wrong error (PR #85494)

2024-03-15 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay created 
https://github.com/llvm/llvm-project/pull/85494

The diagnostic is a warning in GCC. We make it a DefaultError warning
under -Wmain.

There is a use case to pass customized arguments to main without using 
-ffreestanding.

Close #85491


>From 0fd3675447f41b033472f9269648e8e735bc543a Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Fri, 15 Mar 2024 20:26:52 -0700
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.5-bogner
---
 clang/include/clang/Basic/DiagnosticSemaKinds.td  |  4 ++--
 clang/lib/Sema/SemaDecl.cpp   |  2 +-
 .../CXX/basic/basic.start/basic.start.main/p2.cpp | 11 +++
 3 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 8e97902564af08..6cf4e288af5f1f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -950,9 +950,9 @@ def err_main_surplus_args : Error<"too many parameters (%0) 
for 'main': "
 "must be 0, 2, or 3">;
 def warn_main_one_arg : Warning<"only one parameter on 'main' declaration">,
 InGroup;
-def err_main_arg_wrong : Error<"%select{first|second|third|fourth}0 "
+def warn_main_arg_wrong : Warning<"%select{first|second|third|fourth}0 "
 "parameter of 'main' (%select{argument count|argument array|environment|"
-"platform-specific data}0) must be of type %1">;
+"platform-specific data}0) must be of type %1">, DefaultError, 
InGroup;
 def warn_main_returns_bool_literal : Warning<"bool literal returned from "
 "'main'">, InGroup;
 def err_main_global_variable :
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5850cd0ab6b9aa..2718934609842b 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -12488,7 +12488,7 @@ void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& 
DS) {
 }
 
 if (mismatch) {
-  Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
+  Diag(FD->getLocation(), diag::warn_main_arg_wrong) << i << Expected[i];
   // TODO: suggest replacing given type with expected type
   FD->setInvalidDecl(true);
 }
diff --git a/clang/test/CXX/basic/basic.start/basic.start.main/p2.cpp 
b/clang/test/CXX/basic/basic.start/basic.start.main/p2.cpp
index 42e87e5431f2a5..135c828e7366a0 100644
--- a/clang/test/CXX/basic/basic.start/basic.start.main/p2.cpp
+++ b/clang/test/CXX/basic/basic.start/basic.start.main/p2.cpp
@@ -4,6 +4,7 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST4
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST5
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST6
+// RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST6A -Wno-main
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST7
 // RUN: %clang_cc1 -fsyntax-only -verify %s -DTEST8
 
@@ -64,6 +65,16 @@ main( // expected-error {{first parameter of 'main' 
(argument count) must be of
 
 const int main(); // expected-error {{'main' must return 'int'}}
 
+#elif TEST6A
+
+void  // expected-error {{'main' must return 'int'}}
+main(
+ float a
+) {
+}
+
+const int main(); // expected-error {{'main' must return 'int'}}
+
 #elif TEST7
 
 // expected-no-diagnostics

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


[clang] [ObjC] Expand isClassLayoutKnownStatically to base classes as long as the implementation of it is known (PR #85465)

2024-03-15 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/85465

>From 274838e83e20d073b326387a1d319dd60ad32568 Mon Sep 17 00:00:00 2001
From: Rose 
Date: Fri, 15 Mar 2024 16:43:10 -0400
Subject: [PATCH] [ObjC] Expand isClassLayoutKnownStatically to base classes as
 long as the implementation of it is known

Only NSObject we can trust the layout of won't change even though we cannot 
directly see its @implementation
---
 clang/lib/CodeGen/CGObjCMac.cpp   |  9 +-
 .../constant-non-fragile-ivar-offset.m| 30 ++-
 2 files changed, 37 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index e815e097e1fb48..da47ef786cf816 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1595,6 +1595,11 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
 // Test a class by checking its superclasses up to
 // its base class if it has one.
+
+// Cannot check a null class
+if (!ID)
+  return false;
+
 for (; ID; ID = ID->getSuperClass()) {
   // The layout of base class NSObject
   // is guaranteed to be statically known
@@ -1606,7 +1611,9 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   if (!ID->getImplementation())
 return false;
 }
-return false;
+
+// We know the layout of all the intermediate classes and superclasses.
+return true;
   }
 
 public:
diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 8d55e6c7d23081..ee4034e4b7f205 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -8,6 +8,12 @@
 // CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
constant i64 48
 // CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = constant i64 56
 // CHECK: @"OBJC_IVAR_$_SubClass._subClassProperty" = hidden constant i64 64
+
+// CHECK: @"OBJC_IVAR_$_RootClass.these" = constant i64 0
+// CHECK: @"OBJC_IVAR_$_RootClass.dont" = constant i64 4
+// CHECK: @"OBJC_IVAR_$_RootClass.change" = constant i64 4
+// CHECK: @"OBJC_IVAR_$_StillStaticLayout.static_layout_ivar" = hidden global 
i32 12
+
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -120,7 +126,29 @@ -(void)intermediateSubclassVar {
 // CHECK: getelementptr inbounds i8, ptr %1, i64 64
 @end
 
-@interface NotNSObject {
+ __attribute((objc_root_class))  @interface RootClass {
+  int these, dont, change;
+}
+@end
+
+@implementation RootClass 
+@end
+
+@interface StillStaticLayout : RootClass
+@end
+
+@implementation StillStaticLayout {
+  int static_layout_ivar;
+}
+
+// CHECK-LABEL: define internal void @"\01-[StillStaticLayout meth]"
+-(void)meth {
+  static_layout_ivar = 0;
+  // CHECK-NOT: load i64, ptr @"OBJC_IVAR_$StillStaticLayout.static_layout_ivar
+}
+@end
+
+__attribute((objc_root_class))  @interface NotNSObject {
   int these, might, change;
 }
 @end

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-15 Thread YAMAMOTO Takashi via cfe-commits

yamt wrote:

@aheejin i updated the rest of comments

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


[clang] [C++20] [Modules] Introduce -fgen-reduced-bmi (PR #85050)

2024-03-15 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,53 @@
+// It is annoying to handle different slash direction
+// in Windows and Linux. So we disable the test on Windows
+// here.
+// REQUIRES: !system-windows

MaskRay wrote:

UNSUPPORTED is much more common

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


[clang] [C++20] [Modules] Introduce -fgen-reduced-bmi (PR #85050)

2024-03-15 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,53 @@
+// It is annoying to handle different slash direction
+// in Windows and Linux. So we disable the test on Windows
+// here.
+// REQUIRES: !system-windows
+// On AIX, the default output for `-c` may be `.s` instead of `.o`,
+// which makes the test fail. So disable the test on AIX.
+// REQUIRES: !system-aix
+//
+// RUN: rm -rf %t

MaskRay wrote:

redundant `mkdir`

`// RUN: rm -rf %t && split-file %s %t && cd %t`

If Windows backslashes feel annoying, you can add a `cd %t`

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


[clang] [X86_64] fix arg pass error in struct. (PR #85394)

2024-03-15 Thread Longsheng Mou via cfe-commits

https://github.com/CoTinker updated 
https://github.com/llvm/llvm-project/pull/85394

>From be6b4bdd75554b9287092ab42063a9d4e260dd9c Mon Sep 17 00:00:00 2001
From: Longsheng Mou 
Date: Fri, 15 Mar 2024 20:50:54 +0800
Subject: [PATCH] [X86_64] fix arg pass error in struct.

typedef long long alignll __attribute__((aligned (4)));
struct S {
  int a;
  alignll b;
};

When classify:
a: Lo = Integer, Hi = NoClass
b: Lo = Integer, Hi = NoClass
struct S: Lo = Integer, Hi = NoClass

In this case, only one i64 register is used when the structure
parameter is transferred, which is obviously incorrect.So we need
to treat the split case specially.
---
 clang/lib/CodeGen/Targets/X86.cpp |  6 ++
 clang/test/CodeGen/X86/x86_64-arguments.c | 18 ++
 2 files changed, 24 insertions(+)

diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 2291c991fb1107..c3e32e5ed63a97 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -1787,6 +1787,8 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t 
OffsetBase, Class &Lo,
   Lo = Hi = NoClass;
 
   Class &Current = OffsetBase < 64 ? Lo : Hi;
+  bool IsSplit =
+  OffsetBase < 64 && (OffsetBase + getContext().getTypeSize(Ty)) > 64;
   Current = Memory;
 
   if (const BuiltinType *BT = Ty->getAs()) {
@@ -1799,9 +1801,13 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t 
OffsetBase, Class &Lo,
   Hi = Integer;
 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
   Current = Integer;
+  if (IsSplit)
+Hi = Integer;
 } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
k == BuiltinType::Float16 || k == BuiltinType::BFloat16) {
   Current = SSE;
+  if (IsSplit)
+Hi = SSE;
 } else if (k == BuiltinType::Float128) {
   Lo = SSE;
   Hi = SSEUp;
diff --git a/clang/test/CodeGen/X86/x86_64-arguments.c 
b/clang/test/CodeGen/X86/x86_64-arguments.c
index cf5636cfd518b6..92b0192658a555 100644
--- a/clang/test/CodeGen/X86/x86_64-arguments.c
+++ b/clang/test/CodeGen/X86/x86_64-arguments.c
@@ -533,6 +533,24 @@ typedef float t66 __attribute__((__vector_size__(128), 
__aligned__(128)));
 void f66(t66 a0) {
 }
 
+typedef long long t67 __attribute__((aligned (4)));
+struct s67 {
+  int a;
+  t67 b;
+};
+// CHECK-LABEL: define{{.*}} void @f67(i64 %x.coerce0, i32 %x.coerce1)
+void f67(struct s67 x) {
+}
+
+typedef double t68 __attribute__((aligned (4)));
+struct s68 {
+  int a;
+  t68 b;
+};
+// CHECK-LABEL: define{{.*}} void @f68(i64 %x.coerce0, double %x.coerce1)
+void f68(struct s68 x) {
+}
+
 /// The synthesized __va_list_tag does not have file/line fields.
 // CHECK:  = distinct !DICompositeType(tag: DW_TAG_structure_type, name: 
"__va_list_tag",
 // CHECK-NOT:  file:

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


[clang] [clang-format] Fix a bug in annotating FunctionDeclarationName (PR #85361)

2024-03-15 Thread Owen Pan via cfe-commits

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


[clang] 7c460c6 - [clang-format] Fix a bug in annotating FunctionDeclarationName (#85361)

2024-03-15 Thread via cfe-commits

Author: Owen Pan
Date: 2024-03-15T19:25:41-07:00
New Revision: 7c460c6205eedaa24f77d5de272dfd94dc3e9a38

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

LOG: [clang-format] Fix a bug in annotating FunctionDeclarationName (#85361)

A name is not a FunctionDeclarationName if it's preceded by an
Objective-C keyword.

Fixes #84578.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e464c2b5731a35..1342d37a147915 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3595,6 +3595,13 @@ static bool isFunctionDeclarationName(const FormatToken 
&Current,
   if (!Current.Tok.getIdentifierInfo())
 return false;
 
+  const auto &Previous = *Current.Previous;
+
+  if (const auto *PrevPrev = Previous.Previous;
+  PrevPrev && PrevPrev->is(TT_ObjCDecl)) {
+return false;
+  }
+
   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
 for (; Next; Next = Next->Next) {
   if (Next->is(TT_OverloadedOperatorLParen))
@@ -3633,18 +3640,17 @@ static bool isFunctionDeclarationName(const FormatToken 
&Current,
   // Find parentheses of parameter list.
   const FormatToken *Next = Current.Next;
   if (Current.is(tok::kw_operator)) {
-const auto *Previous = Current.Previous;
-if (Previous->Tok.getIdentifierInfo() &&
-!Previous->isOneOf(tok::kw_return, tok::kw_co_return)) {
+if (Previous.Tok.getIdentifierInfo() &&
+!Previous.isOneOf(tok::kw_return, tok::kw_co_return)) {
   return true;
 }
-if (Previous->is(tok::r_paren) && Previous->is(TT_TypeDeclarationParen)) {
-  assert(Previous->MatchingParen);
-  assert(Previous->MatchingParen->is(tok::l_paren));
-  assert(Previous->MatchingParen->is(TT_TypeDeclarationParen));
+if (Previous.is(tok::r_paren) && Previous.is(TT_TypeDeclarationParen)) {
+  assert(Previous.MatchingParen);
+  assert(Previous.MatchingParen->is(tok::l_paren));
+  assert(Previous.MatchingParen->is(TT_TypeDeclarationParen));
   return true;
 }
-if (!Previous->isPointerOrReference() && 
Previous->isNot(TT_TemplateCloser))
+if (!Previous.isPointerOrReference() && Previous.isNot(TT_TemplateCloser))
   return false;
 Next = skipOperatorName(Next);
   } else {

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 21c18a03a4fc7f..b30ea64201bf8d 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2645,6 +2645,11 @@ TEST_F(TokenAnnotatorTest, StartOfName) {
   EXPECT_TOKEN(Tokens[2], tok::identifier, TT_Unknown);
   EXPECT_TOKEN(Tokens[3], tok::identifier, TT_Unknown);
   EXPECT_TOKEN(Tokens[4], tok::identifier, TT_StartOfName);
+
+  Tokens = annotate("@interface NSCoder (TestCoder)");
+  ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::at, TT_ObjCDecl);
+  EXPECT_TOKEN(Tokens[2], tok::identifier, TT_StartOfName);
 }
 
 TEST_F(TokenAnnotatorTest, BraceKind) {



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


[clang] [X86_64] fix arg pass error in struct. (PR #85394)

2024-03-15 Thread Longsheng Mou via cfe-commits

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


[clang] [X86_64] fix arg pass error in struct. (PR #85394)

2024-03-15 Thread Longsheng Mou via cfe-commits

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


[clang] [X86_64] fix arg pass error in struct. (PR #85394)

2024-03-15 Thread Longsheng Mou via cfe-commits

https://github.com/CoTinker updated 
https://github.com/llvm/llvm-project/pull/85394

>From b31780cba73ea39bf7f630a059a554914d804446 Mon Sep 17 00:00:00 2001
From: Longsheng Mou 
Date: Fri, 15 Mar 2024 20:50:54 +0800
Subject: [PATCH] [X86_64] fix arg pass error in struct.

typedef long long Alignll __attribute__((aligned (4)));
struct S {
  int a;
  Alignll b;
};

When classify:
a: Lo = Integer, Hi = NoClass
b: Lo = Integer, Hi = NoClass
struct S: Lo = Integer, Hi = NoClass

In this case, only one i64 register is used when the structure
parameter is transferred, which is obviously incorrect.So we need
to treat the split case specially.
---
 clang/lib/CodeGen/Targets/X86.cpp |  6 ++
 clang/test/CodeGen/X86/x86_64-arguments.c | 18 ++
 2 files changed, 24 insertions(+)

diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 2291c991fb1107..c3e32e5ed63a97 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -1787,6 +1787,8 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t 
OffsetBase, Class &Lo,
   Lo = Hi = NoClass;
 
   Class &Current = OffsetBase < 64 ? Lo : Hi;
+  bool IsSplit =
+  OffsetBase < 64 && (OffsetBase + getContext().getTypeSize(Ty)) > 64;
   Current = Memory;
 
   if (const BuiltinType *BT = Ty->getAs()) {
@@ -1799,9 +1801,13 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t 
OffsetBase, Class &Lo,
   Hi = Integer;
 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
   Current = Integer;
+  if (IsSplit)
+Hi = Integer;
 } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
k == BuiltinType::Float16 || k == BuiltinType::BFloat16) {
   Current = SSE;
+  if (IsSplit)
+Hi = SSE;
 } else if (k == BuiltinType::Float128) {
   Lo = SSE;
   Hi = SSEUp;
diff --git a/clang/test/CodeGen/X86/x86_64-arguments.c 
b/clang/test/CodeGen/X86/x86_64-arguments.c
index cf5636cfd518b6..92b0192658a555 100644
--- a/clang/test/CodeGen/X86/x86_64-arguments.c
+++ b/clang/test/CodeGen/X86/x86_64-arguments.c
@@ -533,6 +533,24 @@ typedef float t66 __attribute__((__vector_size__(128), 
__aligned__(128)));
 void f66(t66 a0) {
 }
 
+typedef long long t67 __attribute__((aligned (4)));
+struct s67 {
+  int a;
+  t67 b;
+};
+// CHECK-LABEL: define{{.*}} void @f67(i64 %x.coerce0, i32 %x.coerce1)
+void f67(struct s67 x) {
+}
+
+typedef double t68 __attribute__((aligned (4)));
+struct s68 {
+  int a;
+  t68 b;
+};
+// CHECK-LABEL: define{{.*}} void @f68(i64 %x.coerce0, double %x.coerce1)
+void f68(struct s68 x) {
+}
+
 /// The synthesized __va_list_tag does not have file/line fields.
 // CHECK:  = distinct !DICompositeType(tag: DW_TAG_structure_type, name: 
"__va_list_tag",
 // CHECK-NOT:  file:

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


[clang] [X86_64] fix arg pass error in struct. (PR #85394)

2024-03-15 Thread Longsheng Mou via cfe-commits

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


[clang] [llvm] [DXIL] `exp`, `any`, `lerp`, & `rcp` Intrinsic Lowering (PR #84526)

2024-03-15 Thread Farzon Lotfi via cfe-commits

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


[clang] [llvm] [DXIL] `exp`, `any`, `lerp`, & `rcp` Intrinsic Lowering (PR #84526)

2024-03-15 Thread Farzon Lotfi via cfe-commits

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


[clang] [llvm] [HLSL] implement `clamp` intrinsic (PR #85424)

2024-03-15 Thread Farzon Lotfi via cfe-commits

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


[clang] 8386a38 - [HLSL] implement `clamp` intrinsic (#85424)

2024-03-15 Thread via cfe-commits

Author: Farzon Lotfi
Date: 2024-03-15T20:57:08-04:00
New Revision: 8386a388bd4f144889401cc503b2c51bf4bb9275

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

LOG: [HLSL] implement `clamp` intrinsic (#85424)

closes #70071
- `CGBuiltin.cpp` - Add the unsigned\generic clamp intrinsic emitter.
- `IntrinsicsDirectX.td` - add the `dx.clamp` & `dx.uclamp` intrinsics
- `DXILIntrinsicExpansion.cpp` - add the `clamp` instruction expansion
while maintaining vector form.
- `SemaChecking.cpp` -  Add `clamp`  builtin Sema Checks.
- `Builtins.td` - add a `clamp` builtin
- `hlsl_intrinsics.h` - add the `clamp` api

Why `clamp` as instruction expansion  for DXIL?
1. SPIR-V has a GLSL `clamp` extension via:
-
[FClamp](https://registry.khronos.org/SPIR-V/specs/1.0/GLSL.std.450.html#FClamp)
-
[UClamp](https://registry.khronos.org/SPIR-V/specs/1.0/GLSL.std.450.html#UClamp)
-
[SClamp](https://registry.khronos.org/SPIR-V/specs/1.0/GLSL.std.450.html#SClamp)
2. Further Clamp lowers to `min(max( x, min_range ), max_range)` which
we have float, signed, & unsigned dixilOps.

Added: 
clang/test/CodeGenHLSL/builtins/clamp-builtin.hlsl
clang/test/CodeGenHLSL/builtins/clamp.hlsl
clang/test/SemaHLSL/BuiltIns/clamp-errors.hlsl
llvm/test/CodeGen/DirectX/clamp-vec.ll
llvm/test/CodeGen/DirectX/clamp.ll
llvm/test/CodeGen/DirectX/fmax.ll
llvm/test/CodeGen/DirectX/fmin.ll
llvm/test/CodeGen/DirectX/smax.ll
llvm/test/CodeGen/DirectX/smin.ll
llvm/test/CodeGen/DirectX/umin.ll

Modified: 
clang/include/clang/Basic/Builtins.td
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Headers/hlsl/hlsl_intrinsics.h
clang/lib/Sema/SemaChecking.cpp
clang/test/SemaHLSL/BuiltIns/mad-errors.hlsl
llvm/include/llvm/IR/IntrinsicsDirectX.td
llvm/lib/Target/DirectX/DXIL.td
llvm/lib/Target/DirectX/DXILIntrinsicExpansion.cpp
llvm/test/CodeGen/DirectX/umax.ll

Removed: 




diff  --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index eae41b5505a467..491c9d8954130f 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4591,6 +4591,12 @@ def HLSLWaveActiveCountBits : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "unsigned int(bool)";
 }
 
+def HLSLClamp : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_clamp"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "void(...)";
+}
+
 def HLSLCreateHandle : LangBuiltin<"HLSL_LANG"> {
   let Spellings = ["__builtin_hlsl_create_handle"];
   let Attributes = [NoThrow, Const];

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index e708bf3d6df1ed..e965df810add54 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -18048,6 +18048,21 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 /*ReturnType=*/llvm::Type::getInt1Ty(getLLVMContext()),
 Intrinsic::dx_any, ArrayRef{Op0}, nullptr, "dx.any");
   }
+  case Builtin::BI__builtin_hlsl_elementwise_clamp: {
+Value *OpX = EmitScalarExpr(E->getArg(0));
+Value *OpMin = EmitScalarExpr(E->getArg(1));
+Value *OpMax = EmitScalarExpr(E->getArg(2));
+
+QualType Ty = E->getArg(0)->getType();
+bool IsUnsigned = false;
+if (auto *VecTy = Ty->getAs())
+  Ty = VecTy->getElementType();
+IsUnsigned = Ty->isUnsignedIntegerType();
+return Builder.CreateIntrinsic(
+/*ReturnType=*/OpX->getType(),
+IsUnsigned ? Intrinsic::dx_uclamp : Intrinsic::dx_clamp,
+ArrayRef{OpX, OpMin, OpMax}, nullptr, "dx.clamp");
+  }
   case Builtin::BI__builtin_hlsl_dot: {
 Value *Op0 = EmitScalarExpr(E->getArg(0));
 Value *Op1 = EmitScalarExpr(E->getArg(1));

diff  --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index 718fb9a9b35c04..5e703772b7ee4f 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -252,6 +252,116 @@ double3 ceil(double3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_ceil)
 double4 ceil(double4);
 
+//===--===//
+// clamp builtins
+//===--===//
+
+/// \fn T clamp(T X, T Min, T Max)
+/// \brief Clamps the specified value \a X to the specified
+/// minimum ( \a Min) and maximum ( \a Max) range.
+/// \param X A value to clamp.
+/// \param Min The specified minimum range.
+/// \param Max The specified maximum range.
+///
+/// Returns The clamped value for the \a X parameter.
+/// For values of -INF or INF, clamp will behave as expected.
+/// However for values of NaN, the results are undefined.
+
+_HLSL_16BIT_AVAILABILITY(shade

[clang] [llvm] [HLSL] implement `clamp` intrinsic (PR #85424)

2024-03-15 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/85424

>From 681f4bbbc4aba08e285864ded62a7f01e178bf38 Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 14 Mar 2024 15:26:26 -0400
Subject: [PATCH 1/3] [HLSL] Implement the  intrinsic

---
 clang/include/clang/Basic/Builtins.td |   6 +
 clang/lib/CodeGen/CGBuiltin.cpp   |   8 ++
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  | 110 ++
 clang/lib/Sema/SemaChecking.cpp   |  15 +-
 .../CodeGenHLSL/builtins/clamp-builtin.hlsl   |   8 ++
 clang/test/CodeGenHLSL/builtins/clamp.hlsl| 134 ++
 .../test/SemaHLSL/BuiltIns/clamp-errors.hlsl  |  91 
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   2 +-
 llvm/lib/Target/DirectX/DXIL.td   |  10 ++
 .../Target/DirectX/DXILIntrinsicExpansion.cpp |  48 +++
 llvm/test/CodeGen/DirectX/clamp.ll|  64 +
 llvm/test/CodeGen/DirectX/fmax.ll |  31 
 llvm/test/CodeGen/DirectX/fmin.ll |  31 
 llvm/test/CodeGen/DirectX/smax.ll |  31 
 llvm/test/CodeGen/DirectX/smin.ll |  31 
 llvm/test/CodeGen/DirectX/umax.ll |  29 ++--
 llvm/test/CodeGen/DirectX/umin.ll |  31 
 17 files changed, 664 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/clamp-builtin.hlsl
 create mode 100644 clang/test/CodeGenHLSL/builtins/clamp.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/clamp-errors.hlsl
 create mode 100644 llvm/test/CodeGen/DirectX/clamp.ll
 create mode 100644 llvm/test/CodeGen/DirectX/fmax.ll
 create mode 100644 llvm/test/CodeGen/DirectX/fmin.ll
 create mode 100644 llvm/test/CodeGen/DirectX/smax.ll
 create mode 100644 llvm/test/CodeGen/DirectX/smin.ll
 create mode 100644 llvm/test/CodeGen/DirectX/umin.ll

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 58a2d22e7641fc..64599aaee0ced7 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4554,6 +4554,12 @@ def HLSLWaveActiveCountBits : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "unsigned int(bool)";
 }
 
+def HLSLClamp : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_clamp"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "void(...)";
+}
+
 def HLSLCreateHandle : LangBuiltin<"HLSL_LANG"> {
   let Spellings = ["__builtin_hlsl_create_handle"];
   let Attributes = [NoThrow, Const];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index b09bf563622089..f831694fe9bc23 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -17981,6 +17981,14 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 /*ReturnType=*/llvm::Type::getInt1Ty(getLLVMContext()),
 Intrinsic::dx_any, ArrayRef{Op0}, nullptr, "dx.any");
   }
+  case Builtin::BI__builtin_hlsl_elementwise_clamp: {
+Value *OpX = EmitScalarExpr(E->getArg(0));
+Value *OpMin = EmitScalarExpr(E->getArg(1));
+Value *OpMax = EmitScalarExpr(E->getArg(2));
+return Builder.CreateIntrinsic(
+/*ReturnType=*/OpX->getType(), Intrinsic::dx_clamp,
+ArrayRef{OpX, OpMin, OpMax}, nullptr, "dx.clamp");
+  }
   case Builtin::BI__builtin_hlsl_dot: {
 Value *Op0 = EmitScalarExpr(E->getArg(0));
 Value *Op1 = EmitScalarExpr(E->getArg(1));
diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index 718fb9a9b35c04..5e703772b7ee4f 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -252,6 +252,116 @@ double3 ceil(double3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_ceil)
 double4 ceil(double4);
 
+//===--===//
+// clamp builtins
+//===--===//
+
+/// \fn T clamp(T X, T Min, T Max)
+/// \brief Clamps the specified value \a X to the specified
+/// minimum ( \a Min) and maximum ( \a Max) range.
+/// \param X A value to clamp.
+/// \param Min The specified minimum range.
+/// \param Max The specified maximum range.
+///
+/// Returns The clamped value for the \a X parameter.
+/// For values of -INF or INF, clamp will behave as expected.
+/// However for values of NaN, the results are undefined.
+
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_clamp)
+half clamp(half, half, half);
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_clamp)
+half2 clamp(half2, half2, half2);
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_clamp)
+half3 clamp(half3, half3, half3);
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_clamp)
+half4 clamp(half4, half4, half4);
+
+#ifdef 

[clang] [ObjC] Add reserved field in 64-bit ABI mode (PR #85487)

2024-03-15 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/85487

>From 5ac1ba54a050029bde7baedbb32630cd6f8449e5 Mon Sep 17 00:00:00 2001
From: Rose 
Date: Fri, 15 Mar 2024 19:58:03 -0400
Subject: [PATCH] [ObjC] Add reserved field in 64-bit ABI mode

---
 clang/lib/CodeGen/CGObjCMac.cpp | 16 +++-
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index e815e097e1fb48..9f59a3a371ac33 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -6047,11 +6047,17 @@ 
ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul
   //   const struct _prop_list_t * const properties;
   // }
 
-  // FIXME. Add 'reserved' field in 64bit abi mode!
-  ClassRonfABITy = llvm::StructType::create(
-  "struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
-  MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
-  Int8PtrTy, PropertyListPtrTy);
+  if (CGM.getTarget().getTriple().isArch64Bit())
+ClassRonfABITy = llvm::StructType::create(
+// Extra reserved field in 64-bit ABI
+"struct._class_ro_t", IntTy, IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
+MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
+Int8PtrTy, PropertyListPtrTy);
+  else
+ClassRonfABITy = llvm::StructType::create(
+"struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
+MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
+Int8PtrTy, PropertyListPtrTy);
 
   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-15 Thread Heejin Ahn via cfe-commits

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-15 Thread Heejin Ahn via cfe-commits

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-15 Thread Heejin Ahn via cfe-commits


@@ -129,27 +129,21 @@
 ///
 /// If there are calls to setjmp()
 ///
-/// 2) In the function entry that calls setjmp, initialize setjmpTable and
-///sejmpTableSize as follows:
-///  setjmpTableSize = 4;
-///  setjmpTable = (int *) malloc(40);
-///  setjmpTable[0] = 0;
-///setjmpTable and setjmpTableSize are used to call saveSetjmp() function 
in
-///Emscripten compiler-rt.
+/// 2) In the function entry that calls setjmp, initialize
+///functionInvocationId as follows:
+///
+///functionInvocationId = alloca(4)
+///
+///Note: the alloca size is not important as this pointer is
+///merely used for pointer comparisions.
 ///
 /// 3) Lower
 ///  setjmp(env)
 ///into
-///  setjmpTable = saveSetjmp(env, label, setjmpTable, setjmpTableSize);
-///  setjmpTableSize = getTempRet0();
-///For each dynamic setjmp call, setjmpTable stores its ID (a number which
-///is incrementally assigned from 0) and its label (a unique number that
-///represents each callsite of setjmp). When we need more entries in
-///setjmpTable, it is reallocated in saveSetjmp() in Emscripten's
-///compiler-rt and it will return the new table address, and assign the new
-///table size in setTempRet0(). saveSetjmp also stores the setjmp's ID into
-///the buffer 'env'. A BB with setjmp is split into two after setjmp call 
in
-///order to make the post-setjmp BB the possible destination of longjmp BB.
+///  __wasm_setjmp(env, label, functionInvocationId)
+///
+///A BB with setjmp is split into two after setjmp call in order to
+///make the post-setjmp BB the possible destination of longjmp BB.

aheejin wrote:

I think it's helpful to mention what `__wasm_setjmp` does: It saves 
`functionInvocationId` and `label` into `env`.

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-15 Thread Heejin Ahn via cfe-commits


@@ -1268,42 +1259,21 @@ bool 
WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
   LLVMContext &C = F.getContext();
   IRBuilder<> IRB(C);
   SmallVector ToErase;
-  // Vector of %setjmpTable values
-  SmallVector SetjmpTableInsts;
-  // Vector of %setjmpTableSize values
-  SmallVector SetjmpTableSizeInsts;
 
   // Setjmp preparation
 
-  // This instruction effectively means %setjmpTableSize = 4.
-  // We create this as an instruction intentionally, and we don't want to fold
-  // this instruction to a constant 4, because this value will be used in
-  // SSAUpdater.AddAvailableValue(...) later.
   BasicBlock *Entry = &F.getEntryBlock();
   DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
   SplitBlock(Entry, &*Entry->getFirstInsertionPt());
 
-  BinaryOperator *SetjmpTableSize =
-  BinaryOperator::Create(Instruction::Add, IRB.getInt32(4), 
IRB.getInt32(0),
- "setjmpTableSize", Entry->getTerminator());
-  SetjmpTableSize->setDebugLoc(FirstDL);
-  // setjmpTable = (int *) malloc(40);
-  Type *IntPtrTy = getAddrIntType(&M);
-  Constant *size = ConstantInt::get(IntPtrTy, 40);
-  IRB.SetInsertPoint(SetjmpTableSize);
-  auto *SetjmpTable = IRB.CreateMalloc(IntPtrTy, IRB.getInt32Ty(), size,
-   nullptr, nullptr, "setjmpTable");
-  SetjmpTable->setDebugLoc(FirstDL);
-  // CallInst::CreateMalloc may return a bitcast instruction if the result 
types
-  // mismatch. We need to set the debug loc for the original call too.
-  auto *MallocCall = SetjmpTable->stripPointerCasts();
-  if (auto *MallocCallI = dyn_cast(MallocCall)) {
-MallocCallI->setDebugLoc(FirstDL);
-  }
-  // setjmpTable[0] = 0;
-  IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
-  SetjmpTableInsts.push_back(SetjmpTable);
-  SetjmpTableSizeInsts.push_back(SetjmpTableSize);
+  Instruction *FunctionInvocationId;
+  IRB.SetInsertPoint(Entry->getTerminator());
+  // This alloca'ed pointer is used by the runtime to identify function
+  // inovactions. It's just for pointer comparisons. It will never
+  // be dereferenced.

aheejin wrote:

```suggestion
  // invocations. It's just for pointer comparisons. It will never be
  // dereferenced.
```

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-15 Thread Heejin Ahn via cfe-commits

https://github.com/aheejin commented:

Nice simplification! Thank you for working on this.

Some minor nits about comments:
- You removed 
https://github.com/llvm/llvm-project/blob/43fc921795bd130a325c013d60f209b5c6128fc7/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp#L213-L215
 in https://github.com/emscripten-core/emscripten/pull/21502, so I think we 
should fix this explanation.
- There still seem to be mentions of `testSetjmp`, which should be changed to 
`__wasm_setjmp_test`.

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-15 Thread Heejin Ahn via cfe-commits


@@ -129,27 +129,21 @@
 ///
 /// If there are calls to setjmp()
 ///
-/// 2) In the function entry that calls setjmp, initialize setjmpTable and
-///sejmpTableSize as follows:
-///  setjmpTableSize = 4;
-///  setjmpTable = (int *) malloc(40);
-///  setjmpTable[0] = 0;
-///setjmpTable and setjmpTableSize are used to call saveSetjmp() function 
in
-///Emscripten compiler-rt.
+/// 2) In the function entry that calls setjmp, initialize
+///functionInvocationId as follows:
+///
+///functionInvocationId = alloca(4)
+///
+///Note: the alloca size is not important as this pointer is
+///merely used for pointer comparisions.
 ///
 /// 3) Lower
 ///  setjmp(env)
 ///into
-///  setjmpTable = saveSetjmp(env, label, setjmpTable, setjmpTableSize);
-///  setjmpTableSize = getTempRet0();
-///For each dynamic setjmp call, setjmpTable stores its ID (a number which
-///is incrementally assigned from 0) and its label (a unique number that
-///represents each callsite of setjmp). When we need more entries in
-///setjmpTable, it is reallocated in saveSetjmp() in Emscripten's
-///compiler-rt and it will return the new table address, and assign the new
-///table size in setTempRet0(). saveSetjmp also stores the setjmp's ID into
-///the buffer 'env'. A BB with setjmp is split into two after setjmp call 
in
-///order to make the post-setjmp BB the possible destination of longjmp BB.
+///  __wasm_setjmp(env, label, functionInvocationId)
+///
+///A BB with setjmp is split into two after setjmp call in order to
+///make the post-setjmp BB the possible destination of longjmp BB.
 ///
 /// 4) Lower every call that might longjmp into

aheejin wrote:

I think we should fix the explanation in here (4) as well about `testSetjmp` 
and `setjmpTable` as well Also the new `__wasm_setjmp_test` takes a different 
sets of arguments so the example code should change too.

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


[clang] [ObjC] Add reserved field in 64-bit ABI mode (PR #85487)

2024-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: AtariDreams (AtariDreams)


Changes



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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGObjCMac.cpp (+11-5) 


``diff
diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index e815e097e1fb48..9f59a3a371ac33 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -6047,11 +6047,17 @@ 
ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul
   //   const struct _prop_list_t * const properties;
   // }
 
-  // FIXME. Add 'reserved' field in 64bit abi mode!
-  ClassRonfABITy = llvm::StructType::create(
-  "struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
-  MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
-  Int8PtrTy, PropertyListPtrTy);
+  if (CGM.getTarget().getTriple().isArch64Bit())
+ClassRonfABITy = llvm::StructType::create(
+// Extra reserved field in 64-bit ABI
+"struct._class_ro_t", IntTy, IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
+MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
+Int8PtrTy, PropertyListPtrTy);
+  else
+ClassRonfABITy = llvm::StructType::create(
+"struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
+MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
+Int8PtrTy, PropertyListPtrTy);
 
   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };

``




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


[clang] [ObjC] Add reserved field in 64-bit ABI mode (PR #85487)

2024-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: AtariDreams (AtariDreams)


Changes



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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGObjCMac.cpp (+11-5) 


``diff
diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index e815e097e1fb48..9f59a3a371ac33 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -6047,11 +6047,17 @@ 
ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul
   //   const struct _prop_list_t * const properties;
   // }
 
-  // FIXME. Add 'reserved' field in 64bit abi mode!
-  ClassRonfABITy = llvm::StructType::create(
-  "struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
-  MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
-  Int8PtrTy, PropertyListPtrTy);
+  if (CGM.getTarget().getTriple().isArch64Bit())
+ClassRonfABITy = llvm::StructType::create(
+// Extra reserved field in 64-bit ABI
+"struct._class_ro_t", IntTy, IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
+MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
+Int8PtrTy, PropertyListPtrTy);
+  else
+ClassRonfABITy = llvm::StructType::create(
+"struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
+MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
+Int8PtrTy, PropertyListPtrTy);
 
   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };

``




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


[clang] [ObjC] Add reserved field in 64-bit ABI mode (PR #85487)

2024-03-15 Thread via cfe-commits

https://github.com/AtariDreams created 
https://github.com/llvm/llvm-project/pull/85487

None

>From 58648e62bbecb5e79d039a54ba74099f59262582 Mon Sep 17 00:00:00 2001
From: Rose 
Date: Fri, 15 Mar 2024 19:58:03 -0400
Subject: [PATCH] [ObjC] Add reserved field in 64-bit ABI mode

---
 clang/lib/CodeGen/CGObjCMac.cpp | 16 +++-
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index e815e097e1fb48..9f59a3a371ac33 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -6047,11 +6047,17 @@ 
ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul
   //   const struct _prop_list_t * const properties;
   // }
 
-  // FIXME. Add 'reserved' field in 64bit abi mode!
-  ClassRonfABITy = llvm::StructType::create(
-  "struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
-  MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
-  Int8PtrTy, PropertyListPtrTy);
+  if (CGM.getTarget().getTriple().isArch64Bit())
+ClassRonfABITy = llvm::StructType::create(
+// Extra reserved field in 64-bit ABI
+"struct._class_ro_t", IntTy, IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
+MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
+Int8PtrTy, PropertyListPtrTy);
+  else
+ClassRonfABITy = llvm::StructType::create(
+"struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,
+MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,
+Int8PtrTy, PropertyListPtrTy);
 
   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };

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


[clang] [ObjC] Fix jmp_buf sizing for ObjC exceptions (PR #85481)

2024-03-15 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/85481

>From 65f867c70dc3e2c4adf78628c7db8103506c2101 Mon Sep 17 00:00:00 2001
From: Rose 
Date: Fri, 15 Mar 2024 18:45:48 -0400
Subject: [PATCH] [ObjC] Fix jmp_buf sizing for ObjC exceptions

The size of 18 only works for x86, but does not work for the other 
architectures. This works for Darwin and was retrieved via reading the setjmp.h 
header. It would be nice if we could do the equivalent of sizeof() that would 
obtain the size as though it were being run on the target, not the host, but 
this is the best I could do for now.
---
 clang/lib/CodeGen/CGObjCMac.cpp | 33 +++--
 1 file changed, 27 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index e815e097e1fb48..0f43c19ca8fb07 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -587,9 +587,9 @@ class ObjCTypesHelper : public ObjCCommonTypesHelper {
   /// SetJmpFn - LLVM _setjmp function.
   llvm::FunctionCallee getSetJmpFn() {
 // This is specifically the prototype for x86.
-llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
+llvm::Type *params[] = {IntTy->getPointerTo()};
 return CGM.CreateRuntimeFunction(
-llvm::FunctionType::get(CGM.Int32Ty, params, false), "_setjmp",
+llvm::FunctionType::get(IntTy, params, false), "_setjmp",
 llvm::AttributeList::get(CGM.getLLVMContext(),
  llvm::AttributeList::FunctionIndex,
  llvm::Attribute::NonLazyBind));
@@ -5946,16 +5946,37 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule 
&cgm)
   ModuleTy = llvm::StructType::create("struct._objc_module", LongTy, LongTy,
   Int8PtrTy, SymtabPtrTy);
 
-  // FIXME: This is the size of the setjmp buffer and should be target
-  // specific. 18 is what's used on 32-bit X86.
-  uint64_t SetJmpBufferSize = 18;
+  // FIXME: Not a perfect solution, but one that better fits the other
+  // architectures Values are derived from setjmp.h on Darwin
+  uint64_t SetJmpBufferSize = 0;
+  switch (CGM.getTarget().getTriple().getArch()) {
+  case llvm::Triple::arm:
+if (CGM.getTarget().getTriple().getSubArch() !=
+llvm::Triple::ARMSubArch_v7k) {
+  SetJmpBufferSize = (10 + 16 + 2);
+  break;
+}
+[[fallthrough]];
+  case llvm::Triple::aarch64:
+SetJmpBufferSize = ((14 + 8 + 2) * 2);
+break;
+  case llvm::Triple::x86_64:
+SetJmpBufferSize = ((9 * 2) + 3 + 16);
+break;
+  case llvm::Triple::x86:
+  default:
+// 18 is what's used on 32-bit X86 and on all architectures on prior
+// versions of clang.
+SetJmpBufferSize = 18;
+break;
+  }
 
   // Exceptions
   llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
 
   ExceptionDataTy = llvm::StructType::create(
   "struct._objc_exception_data",
-  llvm::ArrayType::get(CGM.Int32Ty, SetJmpBufferSize), StackPtrTy);
+  llvm::ArrayType::get(CGM.IntTy, SetJmpBufferSize), StackPtrTy);
 }
 
 
ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule
 &cgm)

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


[clang] [llvm] [CMAKE] Enable FatLTO as a build option for LLVM (PR #80480)

2024-03-15 Thread Paul Kirth via cfe-commits

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


[clang] 43fc921 - [CMAKE] Enable FatLTO as a build option for LLVM (#80480)

2024-03-15 Thread via cfe-commits

Author: Paul Kirth
Date: 2024-03-15T16:35:06-07:00
New Revision: 43fc921795bd130a325c013d60f209b5c6128fc7

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

LOG: [CMAKE] Enable FatLTO as a build option for LLVM (#80480)

Since LLVM supports `-ffat-lto-objects` we should enable this as an
option in the LLVM build. FatLTO should improve the time it takes to
build tests for LTO enabled builds of the compiler by not linking w/ the
bitcode portion of the object files, which should speed up build times
for LTO builds without disabling optimizations.

Added: 


Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake
llvm/cmake/modules/AddLLVM.cmake
llvm/cmake/modules/HandleLLVMOptions.cmake

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index db7430b3344c3e..d5546e20873b3c 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -11,6 +11,7 @@ set(LLVM_ENABLE_RUNTIMES 
"compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING "
 
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
 set(LLVM_ENABLE_DIA_SDK OFF CACHE BOOL "")
+set(LLVM_ENABLE_FATLTO ON CACHE BOOL "")
 set(LLVM_ENABLE_HTTPLIB ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBCXX ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBEDIT OFF CACHE BOOL "")

diff  --git a/llvm/cmake/modules/AddLLVM.cmake 
b/llvm/cmake/modules/AddLLVM.cmake
index 5610880da71079..d84d9d7cca68cf 100644
--- a/llvm/cmake/modules/AddLLVM.cmake
+++ b/llvm/cmake/modules/AddLLVM.cmake
@@ -1637,8 +1637,14 @@ function(add_unittest test_suite test_name)
   # The runtime benefits of LTO don't outweight the compile time costs for 
tests.
   if(LLVM_ENABLE_LTO)
 if((UNIX OR MINGW) AND LINKER_IS_LLD)
-  set_property(TARGET ${test_name} APPEND_STRING PROPERTY
-LINK_FLAGS " -Wl,--lto-O0")
+  if(LLVM_ENABLE_FATLTO)
+# When using FatLTO, just use relocatable linking.
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,--no-fat-lto-objects")
+  else()
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,--lto-O0")
+  endif()
 elseif(LINKER_IS_LLD_LINK)
   set_property(TARGET ${test_name} APPEND_STRING PROPERTY
 LINK_FLAGS " /opt:lldlto=0")

diff  --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index 745a8354f11896..92fa9839db652d 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -32,6 +32,8 @@ endif()
 set(LLVM_ENABLE_LTO OFF CACHE STRING "Build LLVM with LTO. May be specified as 
Thin or Full to use a particular kind of LTO")
 string(TOUPPER "${LLVM_ENABLE_LTO}" uppercase_LLVM_ENABLE_LTO)
 
+option(LLVM_ENABLE_FATLTO "Build LLVM with -ffat-lto-objects." OFF)
+
 # Ninja Job Pool support
 # The following only works with the Ninja generator in CMake >= 3.0.
 set(LLVM_PARALLEL_COMPILE_JOBS "" CACHE STRING
@@ -1280,6 +1282,13 @@ elseif(LLVM_ENABLE_LTO)
   endif()
 endif()
 
+if(LLVM_ENABLE_FATLTO AND (FUCHSIA OR UNIX))
+  append("-ffat-lto-objects" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
+  if(NOT LINKER_IS_LLD_LINK)
+append("-ffat-lto-objects" CMAKE_EXE_LINKER_FLAGS 
CMAKE_SHARED_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS)
+  endif()
+endif()
+
 # Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we 
are
 # doing dynamic linking (see below).
 set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default OFF)



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


[clang] [llvm] [AArch64][PAC] Support ptrauth builtins and -fptrauth-intrinsics. (PR #65996)

2024-03-15 Thread John McCall via cfe-commits


@@ -0,0 +1,265 @@
+Pointer Authentication
+==
+
+.. contents::
+   :local:
+
+Introduction
+
+
+Pointer authentication is a technology which offers strong probabilistic 
protection against exploiting a broad class of memory bugs to take control of 
program execution.  When adopted consistently in a language ABI, it provides a 
form of relatively fine-grained control flow integrity (CFI) check that resists 
both return-oriented programming (ROP) and jump-oriented programming (JOP) 
attacks.
+
+While pointer authentication can be implemented purely in software, direct 
hardware support (e.g. as provided by ARMv8.3 PAuth) can dramatically lower the 
execution speed and code size costs.  Similarly, while pointer authentication 
can be implemented on any architecture, taking advantage of the (typically) 
excess addressing range of a target with 64-bit pointers minimizes the impact 
on memory performance and can allow interoperation with existing code (by 
disabling pointer authentication dynamically).  This document will generally 
attempt to present the pointer authentication feature independent of any 
hardware implementation or ABI.  Considerations that are 
implementation-specific are clearly identified throughout.
+
+Note that there are several different terms in use:
+
+- **Pointer authentication** is a target-independent language technology.
+
+- **PAuth** (sometimes referred to as **PAC**, for Pointer Authentication 
Codes) is an AArch64 architecture extension that provides hardware support for 
pointer authentication.
+
+- **ARMv8.3** is an AArch64 architecture revision that makes PAuth mandatory.  
It is implemented on several shipping processors, including the Apple A12 and 
later.
+
+* **arm64e** is a specific ABI (not yet fully stable) for implementing pointer 
authentication using PAuth on certain Apple operating systems.
+
+This document serves four purposes:
+
+- It describes the basic ideas of pointer authentication.
+
+- It documents several language extensions that are useful on targets using 
pointer authentication.
+
+- It will eventually present a theory of operation for the security 
mitigation, describing the basic requirements for correctness, various 
weaknesses in the mechanism, and ways in which programmers can strengthen its 
protections (including recommendations for language implementors).
+
+- It will eventually document the language ABIs currently used for C, C++, 
Objective-C, and Swift on arm64e, although these are not yet stable on any 
target.
+
+Basic Concepts
+--
+
+The simple address of an object or function is a **raw pointer**.  A raw 
pointer can be **signed** to produce a **signed pointer**.  A signed pointer 
can be then **authenticated** in order to verify that it was **validly signed** 
and extract the original raw pointer.  These terms reflect the most likely 
implementation technique: computing and storing a cryptographic signature along 
with the pointer.  The security of pointer authentication does not rely on 
attackers not being able to separately overwrite the signature.
+
+An **abstract signing key** is a name which refers to a secret key which can 
used to sign and authenticate pointers.  The key value for a particular name is 
consistent throughout a process.
+
+A **discriminator** is an arbitrary value used to **diversify** signed 
pointers so that one validly-signed pointer cannot simply be copied over 
another.  A discriminator is simply opaque data of some implementation-defined 
size that is included in the signature as a salt.
+
+Nearly all aspects of pointer authentication use just these two primary 
operations:
+
+- ``sign(raw_pointer, key, discriminator)`` produces a signed pointer given a 
raw pointer, an abstract signing key, and a discriminator.
+
+- ``auth(signed_pointer, key, discriminator)`` produces a raw pointer given a 
signed pointer, an abstract signing key, and a discriminator.
+
+``auth(sign(raw_pointer, key, discriminator), key, discriminator)`` must 
succeed and produce ``raw_pointer``.  ``auth`` applied to a value that was 
ultimately produced in any other way is expected to immediately halt the 
program.  However, it is permitted for ``auth`` to fail to detect that a signed 
pointer was not produced in this way, in which case it may return anything; 
this is what makes pointer authentication a probabilistic mitigation rather 
than a perfect one.
+
+There are two secondary operations which are required only to implement 
certain intrinsics in :
+
+- ``strip(signed_pointer, key)`` produces a raw pointer given a signed pointer 
and a key it was presumptively signed with.  This is useful for certain kinds 
of tooling, such as crash backtraces; it should generally not be used in the 
basic language ABI except in very careful ways.
+
+- ``sign_generic(value)`` produces a cryptographic signature for arbitrary 
data, not necessarily a pointer.  This is useful for efficient

[clang] [llvm] [CMAKE] Enable FatLTO as a build option for LLVM (PR #80480)

2024-03-15 Thread Paul Kirth via cfe-commits

https://github.com/ilovepi updated 
https://github.com/llvm/llvm-project/pull/80480

>From c0f09d9efd3836a83e72c329d17b32f7a87764b7 Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Tue, 22 Aug 2023 15:24:03 +
Subject: [PATCH 1/4] [CMAKE] Enable FatLTO as a build option for LLVM

---
 clang/cmake/caches/Fuchsia-stage2.cmake|  1 +
 llvm/cmake/modules/AddLLVM.cmake   | 11 +--
 llvm/cmake/modules/HandleLLVMOptions.cmake |  6 ++
 3 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index db7430b3344c3e..d5546e20873b3c 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -11,6 +11,7 @@ set(LLVM_ENABLE_RUNTIMES 
"compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING "
 
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
 set(LLVM_ENABLE_DIA_SDK OFF CACHE BOOL "")
+set(LLVM_ENABLE_FATLTO ON CACHE BOOL "")
 set(LLVM_ENABLE_HTTPLIB ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBCXX ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBEDIT OFF CACHE BOOL "")
diff --git a/llvm/cmake/modules/AddLLVM.cmake b/llvm/cmake/modules/AddLLVM.cmake
index 5610880da71079..6fc02c993a924c 100644
--- a/llvm/cmake/modules/AddLLVM.cmake
+++ b/llvm/cmake/modules/AddLLVM.cmake
@@ -1637,8 +1637,15 @@ function(add_unittest test_suite test_name)
   # The runtime benefits of LTO don't outweight the compile time costs for 
tests.
   if(LLVM_ENABLE_LTO)
 if((UNIX OR MINGW) AND LINKER_IS_LLD)
-  set_property(TARGET ${test_name} APPEND_STRING PROPERTY
-LINK_FLAGS " -Wl,--lto-O0")
+  if(LLVM_ENABLE_FATLTO)
+# When using FatLTO, just use relocatable linking.
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,--no-fat-lto-objects")
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY COMPILE_FLAGS 
" -fno-lto")
+  else()
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,--lto-O0")
+  endif()
 elseif(LINKER_IS_LLD_LINK)
   set_property(TARGET ${test_name} APPEND_STRING PROPERTY
 LINK_FLAGS " /opt:lldlto=0")
diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index 745a8354f11896..a03a92b70ac300 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -32,6 +32,8 @@ endif()
 set(LLVM_ENABLE_LTO OFF CACHE STRING "Build LLVM with LTO. May be specified as 
Thin or Full to use a particular kind of LTO")
 string(TOUPPER "${LLVM_ENABLE_LTO}" uppercase_LLVM_ENABLE_LTO)
 
+option(LLVM_ENABLE_FATLTO "Build LLVM with -ffat-lto-objects." OFF)
+
 # Ninja Job Pool support
 # The following only works with the Ninja generator in CMake >= 3.0.
 set(LLVM_PARALLEL_COMPILE_JOBS "" CACHE STRING
@@ -1280,6 +1282,10 @@ elseif(LLVM_ENABLE_LTO)
   endif()
 endif()
 
+if(LLVM_ENABLE_FATLTO AND (FUCHSIA OR UNIX))
+append("-ffat-lto-objects" CMAKE_EXE_LINKER_FLAGS 
CMAKE_SHARED_LINKER_FLAGS)
+endif()
+
 # Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we 
are
 # doing dynamic linking (see below).
 set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default OFF)

>From a2005ed11bd353a0db1fc5eaf0b69282287113b7 Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Fri, 2 Feb 2024 13:09:18 -0800
Subject: [PATCH 2/4] Add -ffat-lto-objects to CMAKE_C_FLAGS and
 CMAKE_CXX_FLAGS

---
 llvm/cmake/modules/HandleLLVMOptions.cmake | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index a03a92b70ac300..cec45365462044 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -1283,7 +1283,10 @@ elseif(LLVM_ENABLE_LTO)
 endif()
 
 if(LLVM_ENABLE_FATLTO AND (FUCHSIA OR UNIX))
+  append("-ffat-lto-objects" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
+  if(NOT LINKER_IS_LLD_LINK)
 append("-ffat-lto-objects" CMAKE_EXE_LINKER_FLAGS 
CMAKE_SHARED_LINKER_FLAGS)
+  endif()
 endif()
 
 # Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we 
are

>From bce52e38cd9f53a9f82838238db9c19354ff5d0d Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Tue, 5 Mar 2024 10:08:26 -0800
Subject: [PATCH 3/4] [cmake] Append -ffat-lto-objects to
 CMAKE_MODULE_LINKER_FLAGS

---
 llvm/cmake/modules/HandleLLVMOptions.cmake | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index cec45365462044..92fa9839db652d 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -1285,7 +1285,7 @@ endif()
 if(LLVM_ENABLE_FATLTO AND (FUCHSIA OR UNIX))
   append("-ffat-lto-objects" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
   if(NOT LINKER_IS_LLD_LINK)
-append("-ffat-lto-objects" CMAKE_EXE_LI

[clang] [llvm] [CMAKE] Enable FatLTO as a build option for LLVM (PR #80480)

2024-03-15 Thread Paul Kirth via cfe-commits

ilovepi wrote:

Not sure what I've managed to do here w/ basic rebase ... Will remove  
unrelated folks and triage the commits

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


[clang] [llvm] [CMAKE] Enable FatLTO as a build option for LLVM (PR #80480)

2024-03-15 Thread Paul Kirth via cfe-commits

https://github.com/ilovepi updated 
https://github.com/llvm/llvm-project/pull/80480

>From 043e8a33f10905d456e42b71801f0ab1b24a8b36 Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Tue, 22 Aug 2023 15:24:03 +
Subject: [PATCH 1/6] [CMAKE] Enable FatLTO as a build option for LLVM

---
 clang/cmake/caches/Fuchsia-stage2.cmake|  1 +
 llvm/cmake/modules/AddLLVM.cmake   | 11 +--
 llvm/cmake/modules/HandleLLVMOptions.cmake |  6 ++
 3 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index db7430b3344c3e..d5546e20873b3c 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -11,6 +11,7 @@ set(LLVM_ENABLE_RUNTIMES 
"compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING "
 
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
 set(LLVM_ENABLE_DIA_SDK OFF CACHE BOOL "")
+set(LLVM_ENABLE_FATLTO ON CACHE BOOL "")
 set(LLVM_ENABLE_HTTPLIB ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBCXX ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBEDIT OFF CACHE BOOL "")
diff --git a/llvm/cmake/modules/AddLLVM.cmake b/llvm/cmake/modules/AddLLVM.cmake
index 5610880da71079..6fc02c993a924c 100644
--- a/llvm/cmake/modules/AddLLVM.cmake
+++ b/llvm/cmake/modules/AddLLVM.cmake
@@ -1637,8 +1637,15 @@ function(add_unittest test_suite test_name)
   # The runtime benefits of LTO don't outweight the compile time costs for 
tests.
   if(LLVM_ENABLE_LTO)
 if((UNIX OR MINGW) AND LINKER_IS_LLD)
-  set_property(TARGET ${test_name} APPEND_STRING PROPERTY
-LINK_FLAGS " -Wl,--lto-O0")
+  if(LLVM_ENABLE_FATLTO)
+# When using FatLTO, just use relocatable linking.
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,--no-fat-lto-objects")
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY COMPILE_FLAGS 
" -fno-lto")
+  else()
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,--lto-O0")
+  endif()
 elseif(LINKER_IS_LLD_LINK)
   set_property(TARGET ${test_name} APPEND_STRING PROPERTY
 LINK_FLAGS " /opt:lldlto=0")
diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index 745a8354f11896..a03a92b70ac300 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -32,6 +32,8 @@ endif()
 set(LLVM_ENABLE_LTO OFF CACHE STRING "Build LLVM with LTO. May be specified as 
Thin or Full to use a particular kind of LTO")
 string(TOUPPER "${LLVM_ENABLE_LTO}" uppercase_LLVM_ENABLE_LTO)
 
+option(LLVM_ENABLE_FATLTO "Build LLVM with -ffat-lto-objects." OFF)
+
 # Ninja Job Pool support
 # The following only works with the Ninja generator in CMake >= 3.0.
 set(LLVM_PARALLEL_COMPILE_JOBS "" CACHE STRING
@@ -1280,6 +1282,10 @@ elseif(LLVM_ENABLE_LTO)
   endif()
 endif()
 
+if(LLVM_ENABLE_FATLTO AND (FUCHSIA OR UNIX))
+append("-ffat-lto-objects" CMAKE_EXE_LINKER_FLAGS 
CMAKE_SHARED_LINKER_FLAGS)
+endif()
+
 # Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we 
are
 # doing dynamic linking (see below).
 set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default OFF)

>From fcec28e7b2352a9a1d92e16b4dbf1952d83049ec Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Fri, 2 Feb 2024 13:09:18 -0800
Subject: [PATCH 2/6] Add -ffat-lto-objects to CMAKE_C_FLAGS and
 CMAKE_CXX_FLAGS

---
 llvm/cmake/modules/HandleLLVMOptions.cmake | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index a03a92b70ac300..cec45365462044 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -1283,7 +1283,10 @@ elseif(LLVM_ENABLE_LTO)
 endif()
 
 if(LLVM_ENABLE_FATLTO AND (FUCHSIA OR UNIX))
+  append("-ffat-lto-objects" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
+  if(NOT LINKER_IS_LLD_LINK)
 append("-ffat-lto-objects" CMAKE_EXE_LINKER_FLAGS 
CMAKE_SHARED_LINKER_FLAGS)
+  endif()
 endif()
 
 # Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we 
are

>From e273686a4b127fa844af2423b4fb1c17e6552621 Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Tue, 5 Mar 2024 10:08:26 -0800
Subject: [PATCH 3/6] [cmake] Append -ffat-lto-objects to
 CMAKE_MODULE_LINKER_FLAGS

---
 llvm/cmake/modules/HandleLLVMOptions.cmake | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index cec45365462044..92fa9839db652d 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -1285,7 +1285,7 @@ endif()
 if(LLVM_ENABLE_FATLTO AND (FUCHSIA OR UNIX))
   append("-ffat-lto-objects" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
   if(NOT LINKER_IS_LLD_LINK)
-append("-ffat-lto-objects" CMAKE_EXE_LI

[clang] [clang][MSVC] Correct mangling of thread-safe static initialization variables. (PR #85300)

2024-03-15 Thread Tom Honermann via cfe-commits

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


[clang] f128607 - [clang][MSVC] Correct mangling of thread-safe static initialization variables. (#85300)

2024-03-15 Thread via cfe-commits

Author: Tom Honermann
Date: 2024-03-15T19:12:19-04:00
New Revision: f128607b89b4818a2265f5ebd09313408277d975

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

LOG: [clang][MSVC] Correct mangling of thread-safe static initialization 
variables. (#85300)

Static local variables with dynamic initializers depend on implicitly defined
guard variables to synchronize thread-safe initialization.  These guard
variables may have external linkage and therefore require a stable name for
linkage purposes.  The Microsoft ABI assigns these variables a local name of
'$TSS' followed by a discriminator and mangles them as a static local variable
of type 'int'.  Previously, the '$TSS' portion of the name was
not registered as a back reference candidate and this resulted in incorrect
back references for enclosing class and/or namespace scopes that might be
referenced in the signature of the enclosing function.  This change adds the
previously missing back reference registration.  This matches the mangling
performed by MSVC and resolves incompatibilities when inline functions with
static local variables are inlined across DLL boundaries.

This is an ABI change and has the potential to cause backward compatibility
issues with previous Clang releases.

Fixes #83616

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/MicrosoftMangle.cpp
clang/test/CodeGenCXX/mangle-ms-back-references.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 623a4b3c18bb1a..1ae35e6881d2f8 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -47,6 +47,12 @@ C++ Specific Potentially Breaking Changes
 
 ABI Changes in This Version
 ---
+- Fixed Microsoft name mangling of implicitly defined variables used for thread
+  safe static initialization of static local variables. This change resolves
+  incompatibilities with code compiled by MSVC but might introduce
+  incompatibilities with code compiled by earlier versions of Clang when an
+  inline member function that contains a static local variable with a dynamic
+  initializer is declared with ``__declspec(dllimport)``. (#GH83616).
 
 AST Dumping Potentially Breaking Changes
 

diff  --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index b272a546573a31..aa26bb7ed46f48 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -390,6 +390,7 @@ class MicrosoftCXXNameMangler {
   const FunctionDecl *D = nullptr,
   bool ForceThisQuals = false,
   bool MangleExceptionSpec = true);
+  void mangleSourceName(StringRef Name);
   void mangleNestedName(GlobalDecl GD);
 
 private:
@@ -408,7 +409,6 @@ class MicrosoftCXXNameMangler {
 mangleUnqualifiedName(GD, cast(GD.getDecl())->getDeclName());
   }
   void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name);
-  void mangleSourceName(StringRef Name);
   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
   void mangleCXXDtorType(CXXDtorType T);
   void mangleQualifiers(Qualifiers Quals, bool IsMember);
@@ -3920,7 +3920,8 @@ void 
MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
   msvc_hashing_ostream MHO(Out);
   MicrosoftCXXNameMangler Mangler(*this, MHO);
 
-  Mangler.getStream() << "?$TSS" << GuardNum << '@';
+  Mangler.getStream() << "?";
+  Mangler.mangleSourceName("$TSS" + llvm::utostr(GuardNum));
   Mangler.mangleNestedName(VD);
   Mangler.getStream() << "@4HA";
 }

diff  --git a/clang/test/CodeGenCXX/mangle-ms-back-references.cpp 
b/clang/test/CodeGenCXX/mangle-ms-back-references.cpp
index cb95c100b3d22e..b27a9c5acacb77 100644
--- a/clang/test/CodeGenCXX/mangle-ms-back-references.cpp
+++ b/clang/test/CodeGenCXX/mangle-ms-back-references.cpp
@@ -83,3 +83,20 @@ class H;
 
 void ManyParams(T01 &, T02 &, T03 &, T04 &, T05 &, T06 &, T07 &, T08 &, T09 &, 
T10 &, H &, H &) {}
 // CHECK: 
"?ManyParams@@YAXAAVT01@@AAVT02@@AAVT03@@AAVT04@@AAVT05@@AAVT06@@AAVT07@@AAVT08@@AAVT09@@AAVT10@@AAV?$H@VT11AAV?$H@VT11@Z"
+
+namespace NS {
+// The name "TSS0" for the name of the class below has been specifically
+// chosen to ensure that back reference lookup does not match against the
+// implicitly generated "$TSS0" name of the thread safe static initialization
+// variable.
+struct __declspec(dllexport) TSS0 {
+  static TSS0& get();
+  __forceinline static TSS0& singleton() {
+static TSS0& lsv = get();
+return lsv;
+  }
+};
+}
+// CHECK: "?singleton@TSS0@NS@@SAAAU12@XZ"
+// CHECK: "?lsv@?1??singleton@TSS0@NS@@SAAAU23@XZ@4AAU23@A"
+// CHECK: "?$TSS0@?1??singleton@TSS0@NS@@SAAAU23@XZ@4HA"



___

[clang] [clang] Move CCC_OVERRIDE_OPTIONS implementation to Driver (PR #85425)

2024-03-15 Thread Dave Lee via cfe-commits

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


[clang] 8d7ee46 - [clang] Move CCC_OVERRIDE_OPTIONS implementation to Driver (#85425)

2024-03-15 Thread via cfe-commits

Author: Dave Lee
Date: 2024-03-15T16:09:56-07:00
New Revision: 8d7ee4691dadd3a9d831108f77d1f4e511191a44

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

LOG: [clang] Move CCC_OVERRIDE_OPTIONS implementation to Driver (#85425)

Move CCC_OVERRIDE_OPTIONS support to clangDriver so that it may be used outside 
of the 
clang driver binary.

The override functionality will be used in LLDB, to apply adjustments to 
ClangImporter 
flags. This will be useful as an escape hatch when there are issues that can be 
fixed 
by adding or removing clang flags.

The only thing changed is the name, from `ApplyQAOverride` to 
`applyOverrideOptions`.

Added: 


Modified: 
clang/include/clang/Driver/Driver.h
clang/lib/Driver/Driver.cpp
clang/tools/driver/driver.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index c4cab360bab3bb..8e27f75012ee72 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -28,8 +28,8 @@
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/StringSaver.h"
 
-#include 
 #include 
+#include 
 #include 
 #include 
 
@@ -839,6 +839,13 @@ llvm::Error expandResponseFiles(SmallVectorImpl &Args,
 bool ClangCLMode, llvm::BumpPtrAllocator 
&Alloc,
 llvm::vfs::FileSystem *FS = nullptr);
 
+/// Apply a space separated list of edits to the input argument lists.
+/// See applyOneOverrideOption.
+void applyOverrideOptions(SmallVectorImpl &Args,
+  const char *OverrideOpts,
+  llvm::StringSet<> &SavedStrings,
+  raw_ostream *OS = nullptr);
+
 } // end namespace driver
 } // end namespace clang
 

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 190782a79a2456..e3f5f5905a72cb 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -87,6 +87,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/RISCVISAInfo.h"
+#include "llvm/Support/Regex.h"
 #include "llvm/Support/StringSaver.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
@@ -6677,3 +6678,131 @@ llvm::Error 
driver::expandResponseFiles(SmallVectorImpl &Args,
 
   return llvm::Error::success();
 }
+
+static const char *GetStableCStr(llvm::StringSet<> &SavedStrings, StringRef S) 
{
+  return SavedStrings.insert(S).first->getKeyData();
+}
+
+/// Apply a list of edits to the input argument lists.
+///
+/// The input string is a space separated list of edits to perform,
+/// they are applied in order to the input argument lists. Edits
+/// should be one of the following forms:
+///
+///  '#': Silence information about the changes to the command line arguments.
+///
+///  '^': Add FOO as a new argument at the beginning of the command line.
+///
+///  '+': Add FOO as a new argument at the end of the command line.
+///
+///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the 
command
+///  line.
+///
+///  'xOPTION': Removes all instances of the literal argument OPTION.
+///
+///  'XOPTION': Removes all instances of the literal argument OPTION,
+///  and the following argument.
+///
+///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
+///  at the end of the command line.
+///
+/// \param OS - The stream to write edit information to.
+/// \param Args - The vector of command line arguments.
+/// \param Edit - The override command to perform.
+/// \param SavedStrings - Set to use for storing string representations.
+static void applyOneOverrideOption(raw_ostream &OS,
+   SmallVectorImpl &Args,
+   StringRef Edit,
+   llvm::StringSet<> &SavedStrings) {
+  // This does not need to be efficient.
+
+  if (Edit[0] == '^') {
+const char *Str = GetStableCStr(SavedStrings, Edit.substr(1));
+OS << "### Adding argument " << Str << " at beginning\n";
+Args.insert(Args.begin() + 1, Str);
+  } else if (Edit[0] == '+') {
+const char *Str = GetStableCStr(SavedStrings, Edit.substr(1));
+OS << "### Adding argument " << Str << " at end\n";
+Args.push_back(Str);
+  } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.ends_with("/") &&
+ Edit.slice(2, Edit.size() - 1).contains('/')) {
+StringRef MatchPattern = Edit.substr(2).split('/').first;
+StringRef ReplPattern = Edit.substr(2).split('/').second;
+ReplPattern = ReplPattern.slice(0, ReplPattern.size() - 1);
+
+for (unsigned i = 1, e = Args.size(); i != e; ++i) {
+  // Ignore end-of-line response file markers
+  if (Args[i] == nullptr)
+continue;

[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #81545)

2024-03-15 Thread David Li via cfe-commits

david-xl wrote:

> So the additional debug info for pointer type should be generated when 
> -fdebug-info-for-profiling is enabled?

yes, it is extra debug info for profiling (can be used for samplePGO).

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


[clang] [llvm] [CMAKE] Enable FatLTO as a build option for LLVM (PR #80480)

2024-03-15 Thread Petr Hosek via cfe-commits

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


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


[clang] [llvm] [CMAKE] Enable FatLTO as a build option for LLVM (PR #80480)

2024-03-15 Thread Petr Hosek via cfe-commits


@@ -1621,8 +1621,15 @@ function(add_unittest test_suite test_name)
   # The runtime benefits of LTO don't outweight the compile time costs for 
tests.
   if(LLVM_ENABLE_LTO)
 if((UNIX OR MINGW) AND LINKER_IS_LLD)
-  set_property(TARGET ${test_name} APPEND_STRING PROPERTY
-LINK_FLAGS " -Wl,--lto-O0")
+  if(LLVM_ENABLE_FATLTO)
+# When using FatLTO, just use relocatable linking.
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,--no-fat-lto-objects")
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY COMPILE_FLAGS 
" -fno-lto")

petrhosek wrote:

I'd omit it since it shouldn't be necessary.

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


[clang] [C++20] [Modules] Introduce -fgen-reduced-bmi (PR #85050)

2024-03-15 Thread Fangrui Song via cfe-commits


@@ -3031,6 +3032,11 @@ defm skip_odr_check_in_gmf : BoolOption<"f", 
"skip-odr-check-in-gmf",
   "Perform ODR checks for decls in the global module fragment.">>,
   Group;
 
+def gen_reduced_bmi : Flag<["-"], "fgen-reduced-bmi">,
+  Group, Visibility<[ClangOption, CC1Option]>,

MaskRay wrote:

should be f_Group

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


[clang] [clang-tools-extra] [CLANGD] Do not crash on designator initialization of union (PR #83369)

2024-03-15 Thread Nathan Ridge via cfe-commits

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

LGTM

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


[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #81545)

2024-03-15 Thread William Junda Huang via cfe-commits

huangjd wrote:

So the additional debug info for pointer type should be generated when 
-fdebug-info-for-profiling is enabled? 

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


[clang] [ObjC] Fix jmp_buf sizing for ObjC exceptions (PR #85481)

2024-03-15 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/85481

>From c85838773496d54c41fd10c13e461f0f7c03ac40 Mon Sep 17 00:00:00 2001
From: Rose 
Date: Fri, 15 Mar 2024 18:45:48 -0400
Subject: [PATCH] [ObjC] Fix jmp_buf sizing for ObjC exceptions

The size of 18 only works for x86, but does not work for the other 
architectures. This works for Darwin and was retrieved via reading the setjmp.h 
header. It would be nice if we could do the equivalent of sizeof() that would 
obtain the size as though it were being run on the target, not the host, but 
this is the best I could do for now.
---
 clang/lib/CodeGen/CGObjCMac.cpp | 33 +++--
 1 file changed, 27 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index e815e097e1fb48..05dc7b15495304 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -587,9 +587,9 @@ class ObjCTypesHelper : public ObjCCommonTypesHelper {
   /// SetJmpFn - LLVM _setjmp function.
   llvm::FunctionCallee getSetJmpFn() {
 // This is specifically the prototype for x86.
-llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
+llvm::Type *params[] = {CGM.IntTy->getPointerTo()};
 return CGM.CreateRuntimeFunction(
-llvm::FunctionType::get(CGM.Int32Ty, params, false), "_setjmp",
+llvm::FunctionType::get(CGM.IntTy, params, false), "_setjmp",
 llvm::AttributeList::get(CGM.getLLVMContext(),
  llvm::AttributeList::FunctionIndex,
  llvm::Attribute::NonLazyBind));
@@ -5946,16 +5946,37 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule 
&cgm)
   ModuleTy = llvm::StructType::create("struct._objc_module", LongTy, LongTy,
   Int8PtrTy, SymtabPtrTy);
 
-  // FIXME: This is the size of the setjmp buffer and should be target
-  // specific. 18 is what's used on 32-bit X86.
-  uint64_t SetJmpBufferSize = 18;
+  // FIXME: Not a perfect solution, but one that better fits the other
+  // architectures Values are derived from setjmp.h on Darwin
+  uint64_t SetJmpBufferSize = 0;
+  switch (CGM.getTarget().getTriple().getArch()) {
+  case llvm::Triple::arm:
+if (CGM.getTarget().getTriple().getSubArch() !=
+llvm::Triple::ARMSubArch_v7k) {
+  SetJmpBufferSize = (10 + 16 + 2);
+  break;
+}
+[[fallthrough]];
+  case llvm::Triple::aarch64:
+SetJmpBufferSize = ((14 + 8 + 2) * 2);
+break;
+  case llvm::Triple::x86_64:
+SetJmpBufferSize = ((9 * 2) + 3 + 16);
+break;
+  case llvm::Triple::x86:
+  default:
+// 18 is what's used on 32-bit X86 and on all architectures on prior
+// versions of clang.
+SetJmpBufferSize = 18;
+break;
+  }
 
   // Exceptions
   llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
 
   ExceptionDataTy = llvm::StructType::create(
   "struct._objc_exception_data",
-  llvm::ArrayType::get(CGM.Int32Ty, SetJmpBufferSize), StackPtrTy);
+  llvm::ArrayType::get(CGM.IntTy, SetJmpBufferSize), StackPtrTy);
 }
 
 
ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule
 &cgm)

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


[clang] [llvm] [SpecialCaseList] Use glob by default (PR #74809)

2024-03-15 Thread Fangrui Song via cfe-commits

MaskRay wrote:

> CC @llvm/clang-vendors
> 
> > I [announced this change on 
> > discourse](https://discourse.llvm.org/t/use-glob-instead-of-regex-for-specialcaselists/71666?u=ellishg)
> >  last year.
> 
> "Use glob instead of regex for SpecialCaseLists" doesn't mean anything for 
> anyone not actively working on the relevant code. An announcement would be 
> titled something like "Syntax change for -fsanitize-ignorelist"... and it 
> would be posted when the change actually happened.

Apologies. This could have been better handled. I've also seen a report of 
`[cfi-vcall|cfi-nvcall|cfi-icall]` from Chromium. Now I re-checked, 
https://reviews.llvm.org/D154014 did mention `[cfi-vcall|cfi-icall]`. Grepping 
`\|` (and `^\[.*\|` for section names) in `*san_ignorelist.txt` files is 
probably good enough to know whether you affected.

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


[clang] [ObjC] Fix jmp_buf sizing for ObjC exceptions (PR #85481)

2024-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: AtariDreams (AtariDreams)


Changes

The size of 18 only works for x86, but does not work for the other 
architectures. This works for Darwin and was retrieved via reading the setjmp.h 
header. It would be nice if we could do the equivalent of sizeof() that would 
obtain the size as though it were being run on the target, not the host, but 
this is the best I could do for now.

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGObjCMac.cpp (+27-6) 


``diff
diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index e815e097e1fb48..340e99ab5b94c4 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -587,9 +587,9 @@ class ObjCTypesHelper : public ObjCCommonTypesHelper {
   /// SetJmpFn - LLVM _setjmp function.
   llvm::FunctionCallee getSetJmpFn() {
 // This is specifically the prototype for x86.
-llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
+llvm::Type *params[] = {CGM.IntTy->getPointerTo()};
 return CGM.CreateRuntimeFunction(
-llvm::FunctionType::get(CGM.Int32Ty, params, false), "_setjmp",
+llvm::FunctionType::get(CGM.IntTy, params, false), "_setjmp",
 llvm::AttributeList::get(CGM.getLLVMContext(),
  llvm::AttributeList::FunctionIndex,
  llvm::Attribute::NonLazyBind));
@@ -5946,16 +5946,37 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule 
&cgm)
   ModuleTy = llvm::StructType::create("struct._objc_module", LongTy, LongTy,
   Int8PtrTy, SymtabPtrTy);
 
-  // FIXME: This is the size of the setjmp buffer and should be target
-  // specific. 18 is what's used on 32-bit X86.
-  uint64_t SetJmpBufferSize = 18;
+  // FIXME: Not a perfect solution, but one that better fits the other
+  // architectures Values are derived from setjmp.h on Darwin
+  uint64_t SetJmpBufferSize = 0;
+  switch (CGM.getTarget().getTriple().getArch()) {
+  case llvm::Triple::arm:
+if (CGM.getTarget().getTriple().getSubArch() !=
+llvm::Triple::ARMSubArch_v7k) {
+  SetJmpBufferSize = (10 + 16 + 2);
+  break;
+}
+[[fallthrough]];
+  case llvm::Triple::aarch64:
+SetJmpBufferSize = ((14 + 8 + 2) * 2);
+break;
+  case llvm::Triple::x86_64:
+SetJmpBufferSize = ((9 * 2) + 3 + 16); // Obtained from macOS's setjmp.h
+break;
+  case llvm::Triple::x86:
+  default:
+// 18 is what's used on 32-bit X86 and on all architectures on prior
+// versions of clang.
+SetJmpBufferSize = 18;
+break;
+  }
 
   // Exceptions
   llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
 
   ExceptionDataTy = llvm::StructType::create(
   "struct._objc_exception_data",
-  llvm::ArrayType::get(CGM.Int32Ty, SetJmpBufferSize), StackPtrTy);
+  llvm::ArrayType::get(CGM.IntTy, SetJmpBufferSize), StackPtrTy);
 }
 
 
ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule
 &cgm)

``




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


[clang] [clang] Better bitfield access units (PR #65742)

2024-03-15 Thread John McCall via cfe-commits

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


[clang] [ObjC] Fix jmp_buf sizing for ObjC exceptions (PR #85481)

2024-03-15 Thread via cfe-commits

https://github.com/AtariDreams created 
https://github.com/llvm/llvm-project/pull/85481

The size of 18 only works for x86, but does not work for the other 
architectures. This works for Darwin and was retrieved via reading the setjmp.h 
header. It would be nice if we could do the equivalent of sizeof() that would 
obtain the size as though it were being run on the target, not the host, but 
this is the best I could do for now.

>From 0e5f8c332649c2dd6e9eacb6d058aafebf5141d9 Mon Sep 17 00:00:00 2001
From: Rose 
Date: Fri, 15 Mar 2024 18:45:48 -0400
Subject: [PATCH] [ObjC] Fix jmp_buf sizing for ObjC exceptions

The size of 18 only works for x86, but does not work for the other 
architectures. This works for Darwin and was retrieved via reading the setjmp.h 
header. It would be nice if we could do the equivalent of sizeof() that would 
obtain the size as though it were being run on the target, not the host, but 
this is the best I could do for now.
---
 clang/lib/CodeGen/CGObjCMac.cpp | 33 +++--
 1 file changed, 27 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index e815e097e1fb48..340e99ab5b94c4 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -587,9 +587,9 @@ class ObjCTypesHelper : public ObjCCommonTypesHelper {
   /// SetJmpFn - LLVM _setjmp function.
   llvm::FunctionCallee getSetJmpFn() {
 // This is specifically the prototype for x86.
-llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
+llvm::Type *params[] = {CGM.IntTy->getPointerTo()};
 return CGM.CreateRuntimeFunction(
-llvm::FunctionType::get(CGM.Int32Ty, params, false), "_setjmp",
+llvm::FunctionType::get(CGM.IntTy, params, false), "_setjmp",
 llvm::AttributeList::get(CGM.getLLVMContext(),
  llvm::AttributeList::FunctionIndex,
  llvm::Attribute::NonLazyBind));
@@ -5946,16 +5946,37 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule 
&cgm)
   ModuleTy = llvm::StructType::create("struct._objc_module", LongTy, LongTy,
   Int8PtrTy, SymtabPtrTy);
 
-  // FIXME: This is the size of the setjmp buffer and should be target
-  // specific. 18 is what's used on 32-bit X86.
-  uint64_t SetJmpBufferSize = 18;
+  // FIXME: Not a perfect solution, but one that better fits the other
+  // architectures Values are derived from setjmp.h on Darwin
+  uint64_t SetJmpBufferSize = 0;
+  switch (CGM.getTarget().getTriple().getArch()) {
+  case llvm::Triple::arm:
+if (CGM.getTarget().getTriple().getSubArch() !=
+llvm::Triple::ARMSubArch_v7k) {
+  SetJmpBufferSize = (10 + 16 + 2);
+  break;
+}
+[[fallthrough]];
+  case llvm::Triple::aarch64:
+SetJmpBufferSize = ((14 + 8 + 2) * 2);
+break;
+  case llvm::Triple::x86_64:
+SetJmpBufferSize = ((9 * 2) + 3 + 16); // Obtained from macOS's setjmp.h
+break;
+  case llvm::Triple::x86:
+  default:
+// 18 is what's used on 32-bit X86 and on all architectures on prior
+// versions of clang.
+SetJmpBufferSize = 18;
+break;
+  }
 
   // Exceptions
   llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
 
   ExceptionDataTy = llvm::StructType::create(
   "struct._objc_exception_data",
-  llvm::ArrayType::get(CGM.Int32Ty, SetJmpBufferSize), StackPtrTy);
+  llvm::ArrayType::get(CGM.IntTy, SetJmpBufferSize), StackPtrTy);
 }
 
 
ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule
 &cgm)

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


[clang] [clang-tools-extra] [CLANGD] Do not crash on designator initialization of union (PR #83369)

2024-03-15 Thread via cfe-commits

https://github.com/alirezamoshtaghi updated 
https://github.com/llvm/llvm-project/pull/83369

>From 3d6afe011221ac239bb668b375ed3f6c356fc47d Mon Sep 17 00:00:00 2001
From: alirezamoshtaghi 
Date: Wed, 28 Feb 2024 13:55:11 -0800
Subject: [PATCH 1/5] [CLANGD] Do not crash on designator initialization of
 union

---
 .../clangd/test/designator_init.test  | 31 +++
 clang/lib/AST/Expr.cpp| 14 +++--
 2 files changed, 43 insertions(+), 2 deletions(-)
 create mode 100644 clang-tools-extra/clangd/test/designator_init.test

diff --git a/clang-tools-extra/clangd/test/designator_init.test 
b/clang-tools-extra/clangd/test/designator_init.test
new file mode 100644
index 00..739f2bfab54bcf
--- /dev/null
+++ b/clang-tools-extra/clangd/test/designator_init.test
@@ -0,0 +1,31 @@
+//# RUN: rm -rf %t.dir/* && mkdir -p %t.dir
+//# RUN: echo '[{"directory": "%/t.dir", "command": "clang -x c -c %s", 
"file": "%s"}]' > %t.dir/compile_commands.json
+//# RUN: clangd --compile-commands-dir=%t.dir --check=%s 2>&1 | FileCheck %s
+
+typedef struct S {
+  unsigned char id;
+  union {
+unsigned int mask;
+struct {
+  unsigned int unused:10;
+  unsigned int reserved:3;
+  unsigned int rest:19;
+};
+  };
+} __attribute__((packed)) S_t;
+
+typedef struct H {
+  unsigned char hid;
+  unsigned int val;
+} handler_t;
+
+struct S
+get_foo (handler_t *h)
+{
+  S_t retval =
+{.id=h->hid,
+ .mask=h->val};
+  return retval;
+}
+
+// CHECK: All checks completed, 0 errors
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index b4de2155adcebd..33eeeda89fe7a5 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -4601,11 +4601,21 @@ SourceRange 
DesignatedInitExpr::getDesignatorsSourceRange() const {
 SourceLocation DesignatedInitExpr::getBeginLoc() const {
   auto *DIE = const_cast(this);
   Designator &First = *DIE->getDesignator(0);
-  if (First.isFieldDesignator())
-return GNUSyntax ? First.getFieldLoc() : First.getDotLoc();
+  if (First.isFieldDesignator()) {
+/* search all designators in case the first one is not
+   initialized */
+for (unsigned int i=0; isize(); i++) {
+  Designator &Des = *DIE->getDesignator(i);
+  SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc();
+  if (!retval.isValid ())
+   continue;
+  return retval;
+}
+  }
   return First.getLBracketLoc();
 }
 
+
 SourceLocation DesignatedInitExpr::getEndLoc() const {
   return getInit()->getEndLoc();
 }

>From 397f6cd893a6a07426d39f1dabd7ad27282435af Mon Sep 17 00:00:00 2001
From: alirezamoshtaghi 
Date: Mon, 4 Mar 2024 11:54:56 -0800
Subject: [PATCH 2/5] fix formatting errors

---
 clang/lib/AST/Expr.cpp | 9 +++--
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 33eeeda89fe7a5..2e7170ecac0618 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -4602,20 +4602,17 @@ SourceLocation DesignatedInitExpr::getBeginLoc() const {
   auto *DIE = const_cast(this);
   Designator &First = *DIE->getDesignator(0);
   if (First.isFieldDesignator()) {
-/* search all designators in case the first one is not
-   initialized */
-for (unsigned int i=0; isize(); i++) {
+for (unsigned int i = 0; i < DIE->size(); i++) {
   Designator &Des = *DIE->getDesignator(i);
   SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc();
-  if (!retval.isValid ())
-   continue;
+  if (!retval.isValid())
+continue;
   return retval;
 }
   }
   return First.getLBracketLoc();
 }
 
-
 SourceLocation DesignatedInitExpr::getEndLoc() const {
   return getInit()->getEndLoc();
 }

>From d1d1458809e0b27dc05c70ef449ebbe6896437d4 Mon Sep 17 00:00:00 2001
From: alirezamoshtaghi 
Date: Tue, 5 Mar 2024 00:04:52 -0800
Subject: [PATCH 3/5] dont test designator on Windows

---
 clang-tools-extra/clangd/test/designator_init.test | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/test/designator_init.test 
b/clang-tools-extra/clangd/test/designator_init.test
index 739f2bfab54bcf..4009945ed81fd4 100644
--- a/clang-tools-extra/clangd/test/designator_init.test
+++ b/clang-tools-extra/clangd/test/designator_init.test
@@ -1,7 +1,7 @@
 //# RUN: rm -rf %t.dir/* && mkdir -p %t.dir
 //# RUN: echo '[{"directory": "%/t.dir", "command": "clang -x c -c %s", 
"file": "%s"}]' > %t.dir/compile_commands.json
 //# RUN: clangd --compile-commands-dir=%t.dir --check=%s 2>&1 | FileCheck %s
-
+//# UNSUPPORTED: system-windows
 typedef struct S {
   unsigned char id;
   union {

>From a792acd4eec0f549bdbf9779dce14aca5357c2db Mon Sep 17 00:00:00 2001
From: alirezamoshtaghi 
Date: Wed, 13 Mar 2024 18:51:38 -0700
Subject: [PATCH 4/5] Move the test to clangd unit tests

---
 .../clangd/test/designator_init.test  | 31 ---
 .../unittests/tweaks/ExtractVariableTests.cpp | 16 

[clang] [clang] Move CCC_OVERRIDE_OPTIONS implementation to Driver (PR #85425)

2024-03-15 Thread Fangrui Song via cfe-commits

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


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


[clang] [NVPTX] Add `-march=general` option to mirror default configuration (PR #85222)

2024-03-15 Thread via cfe-commits

github-actions[bot] wrote:



@oraluben Congratulations on having your first Pull Request (PR) merged into 
the LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested
by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with 
a build, you may recieve a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as
the builds can include changes from many authors. It is not uncommon for your
change to be included in a build that fails due to someone else's changes, or
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself.
This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang] [NVPTX] Add `-march=general` option to mirror default configuration (PR #85222)

2024-03-15 Thread Joseph Huber via cfe-commits

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


[clang] 047b2b2 - [NVPTX] Add `-march=general` option to mirror default configuration (#85222)

2024-03-15 Thread via cfe-commits

Author: Yichen Yan
Date: 2024-03-15T17:16:10-05:00
New Revision: 047b2b241defcad79a6ac0fec9cda092bac0a922

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

LOG: [NVPTX] Add `-march=general` option to mirror default configuration 
(#85222)

This PR adds `-march=generic` support for the NVPTX backend. This
fulfills a TODO introduced in #79873.

With this PR, users can explicitly request the "default" CUDA
architecture, which makes sure that no specific architecture is
specified.

This PR does not address any compatibility issues between different CUDA
versions.

-

Co-authored-by: Joseph Huber 

Added: 


Modified: 
clang/lib/Driver/ToolChains/Cuda.cpp
clang/test/Driver/cuda-cross-compiling.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index c6007d3cfab864..5f0b516e1a1a08 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -750,10 +750,12 @@ NVPTXToolChain::TranslateArgs(const 
llvm::opt::DerivedArgList &Args,
 if (!llvm::is_contained(*DAL, A))
   DAL->append(A);
 
-  // TODO: We should accept 'generic' as a valid architecture.
   if (!DAL->hasArg(options::OPT_march_EQ) && OffloadKind != Action::OFK_None) {
 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
   CudaArchToString(CudaArch::CudaDefault));
+  } else if (DAL->getLastArgValue(options::OPT_march_EQ) == "generic" &&
+ OffloadKind == Action::OFK_None) {
+DAL->eraseArg(options::OPT_march_EQ);
   } else if (DAL->getLastArgValue(options::OPT_march_EQ) == "native") {
 auto GPUsOrErr = getSystemGPUArchs(Args);
 if (!GPUsOrErr) {

diff  --git a/clang/test/Driver/cuda-cross-compiling.c 
b/clang/test/Driver/cuda-cross-compiling.c
index 086840accebe7f..a1719a6fbe042b 100644
--- a/clang/test/Driver/cuda-cross-compiling.c
+++ b/clang/test/Driver/cuda-cross-compiling.c
@@ -80,11 +80,15 @@
 //
 // RUN: not %clang -target nvptx64-nvidia-cuda %s -### 2>&1 \
 // RUN:   | FileCheck -check-prefix=MISSING %s
+// RUN: not %clang -target nvptx64-nvidia-cuda -march=generic %s -### 2>&1 \
+// RUN:   | FileCheck -check-prefix=MISSING %s
 
 // MISSING: error: Must pass in an explicit nvptx64 gpu architecture to 'ptxas'
 // MISSING: error: Must pass in an explicit nvptx64 gpu architecture to 
'nvlink'
 
 // RUN: %clang -target nvptx64-nvidia-cuda -flto -c %s -### 2>&1 \
 // RUN:   | FileCheck -check-prefix=GENERIC %s
+// RUN: %clang -target nvptx64-nvidia-cuda -march=sm_52 -march=generic -flto 
-c %s -### 2>&1 \
+// RUN:   | FileCheck -check-prefix=GENERIC %s
 
 // GENERIC-NOT: -cc1" "-triple" "nvptx64-nvidia-cuda" {{.*}} "-target-cpu"



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


[clang-tools-extra] [clang-tidy][NFC] Remove unnecessary nullptr check on cast subexpr (PR #85473)

2024-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Mike Rice (mikerice1969)


Changes

The value of SubExpr is not null since getSubExpr would assert in that case. 
Remove the nullptr check. This avoids confusion since SubExpr is used without 
check later in the function.

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


1 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp (+1-2) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 4f02950e7794cb..74152c6034510b 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -81,8 +81,7 @@ void fixGenericExprCastToBool(DiagnosticBuilder &Diag,
 
   const Expr *SubExpr = Cast->getSubExpr();
 
-  bool NeedInnerParens =
-  SubExpr != nullptr && 
utils::fixit::areParensNeededForStatement(*SubExpr);
+  bool NeedInnerParens = utils::fixit::areParensNeededForStatement(*SubExpr);
   bool NeedOuterParens =
   Parent != nullptr && utils::fixit::areParensNeededForStatement(*Parent);
 

``




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


[clang-tools-extra] [clang-tidy][NFC] Remove unnecessary nullptr check on cast subexpr (PR #85473)

2024-03-15 Thread Mike Rice via cfe-commits

https://github.com/mikerice1969 created 
https://github.com/llvm/llvm-project/pull/85473

The value of SubExpr is not null since getSubExpr would assert in that case. 
Remove the nullptr check. This avoids confusion since SubExpr is used without 
check later in the function.

>From 56c3ca2e2cfac7b6c9b9029d14151fd80d705c2c Mon Sep 17 00:00:00 2001
From: Mike Rice 
Date: Fri, 15 Mar 2024 13:37:32 -0700
Subject: [PATCH] [clang-tidy][NFC] Remove unnecessary nullptr check on cast
 subexpr

The value of SubExpr is not null since getSubExpr would assert in that
case. Remove the nullptr check. This avoids confusion since SubExpr is
used without check later in the function.
---
 .../clang-tidy/readability/ImplicitBoolConversionCheck.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 4f02950e7794cb..74152c6034510b 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -81,8 +81,7 @@ void fixGenericExprCastToBool(DiagnosticBuilder &Diag,
 
   const Expr *SubExpr = Cast->getSubExpr();
 
-  bool NeedInnerParens =
-  SubExpr != nullptr && 
utils::fixit::areParensNeededForStatement(*SubExpr);
+  bool NeedInnerParens = utils::fixit::areParensNeededForStatement(*SubExpr);
   bool NeedOuterParens =
   Parent != nullptr && utils::fixit::areParensNeededForStatement(*Parent);
 

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


[clang] [clang] Better bitfield access units (PR #65742)

2024-03-15 Thread John McCall via cfe-commits

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


[clang] [clang-format] Fix clang-format issue with 'new' and 'delete' keywords in C files (PR #85470)

2024-03-15 Thread via cfe-commits

https://github.com/scythris updated 
https://github.com/llvm/llvm-project/pull/85470

>From 451a664dc3d325deff54ff7d582b0063569f54cd Mon Sep 17 00:00:00 2001
From: Trym Strand 
Date: Fri, 15 Mar 2024 21:56:22 +0100
Subject: [PATCH] Fix clang-format issue with 'new' and 'delete' keywords in C
 files

This patch resolves an issue in clang-format where 'new' and 'delete' were 
incorrectly recognized as keywords in C files. The fix modifies the 
TokenAnnotator::spaceRequiredBetween to correctly handle 'new' and 'delete' as 
an identifier in C code, preventing incorrect formatting.
---
 clang/lib/Format/TokenAnnotator.cpp   | 2 +-
 clang/unittests/Format/FormatTest.cpp | 5 +
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e464c2b5731a35..c58204ce33ae52 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4607,7 +4607,7 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
   return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
  spaceRequiredBeforeParens(Right);
 }
-if (!Left.Previous || Left.Previous->isNot(tok::period)) {
+if (!Left.Previous || !Left.Previous->isOneOf(tok::period, tok::arrow)) {
   if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) {
 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index fc367a7a5a8981..a6f9a0941cb040 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11450,6 +11450,11 @@ TEST_F(FormatTest, UnderstandsNewAndDelete) {
"void new (link p);\n"
"void delete (link p);");
 
+  verifyFormat("{ p->delete(); }\n"
+   "{ p->new(); }",
+   "{ p->delete (); }\n"
+   "{ p->new (); }");
+
   FormatStyle AfterPlacementOperator = getLLVMStyle();
   AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
   EXPECT_TRUE(

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


[clang] [clang] Better bitfield access units (PR #65742)

2024-03-15 Thread John McCall via cfe-commits


@@ -439,82 +444,194 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // We do this in two phases, processing a sequential run of bitfield
+  // declarations.
+
+  // a) Bitfields that share parts of a single byte are, of necessity, placed 
in
+  // the same access unit. That unit will encompass a consecutive
+  // run where adjacent bitfields share parts of a byte. (The first bitfield of
+  // such an access unit will start at the beginning of a byte.)
+
+  // b) Accumulate adjacent access units when the combined unit is naturally
+  // sized, no larger than a register, and on a strict alignment ISA,
+  // aligned. Note that this requires lookahead to one or more subsequent 
access
+  // units. For instance, consider a 2-byte access-unit followed by 2 1-byte
+  // units. We can merge that into a 4-byte access-unit, but we would not want
+  // to merge a 2-byte followed by a single 1-byte (and no available tail
+  // padding).
+
+  // This accumulation is prevented when:
+  // *) it would cross a zero-width bitfield (ABI-dependent), or
+  // *) one of the candidate access units contains a volatile bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  RecordDecl::field_iterator Begin = FieldEnd;
+  CharUnits StartOffset;
+  uint64_t BitSize;
+  CharUnits BestEndOffset;
+  RecordDecl::field_iterator BestEnd = B

[clang] [clang] Move CCC_OVERRIDE_OPTIONS implementation to Driver (PR #85425)

2024-03-15 Thread Dave Lee via cfe-commits


@@ -839,6 +839,13 @@ llvm::Error expandResponseFiles(SmallVectorImpl &Args,
 bool ClangCLMode, llvm::BumpPtrAllocator 
&Alloc,
 llvm::vfs::FileSystem *FS = nullptr);
 
+/// Apply a space separated list of edits to the input argument lists.
+/// See applyOneOverrideOption.
+void applyOverrideOptions(SmallVectorImpl &Args,
+  const char *OverrideOpts,
+  std::set &SavedStrings,

kastiglione wrote:

thanks, replaced.

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


[clang] [clang] Move CCC_OVERRIDE_OPTIONS implementation to Driver (PR #85425)

2024-03-15 Thread Dave Lee via cfe-commits


@@ -6677,3 +6678,134 @@ llvm::Error 
driver::expandResponseFiles(SmallVectorImpl &Args,
 
   return llvm::Error::success();
 }
+
+namespace {
+
+const char *GetStableCStr(std::set &SavedStrings, StringRef S) {

kastiglione wrote:

fixed

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


[clang] [clang] Move CCC_OVERRIDE_OPTIONS implementation to Driver (PR #85425)

2024-03-15 Thread Dave Lee via cfe-commits

https://github.com/kastiglione updated 
https://github.com/llvm/llvm-project/pull/85425

>From c9a98ad15aa63c445e68b56621f5a1c8f0fc4219 Mon Sep 17 00:00:00 2001
From: Dave Lee 
Date: Thu, 14 Mar 2024 18:44:17 -0700
Subject: [PATCH 1/6] [clang] Move CCC_OVERRIDE_OPTIONS implementation to
 Driver

Move CCC_OVERRIDE_OPTIONS support to clangDriver so that it may be used outside
of the clang driver binary.

The override functionality will be used in LLDB, to apply adjustments to
ClangImporter flags. This will be useful as an escape hatch when there are
issues that can be fixed by adding or removing clang flags.
---
 clang/include/clang/Driver/Driver.h |   7 +-
 clang/lib/Driver/Driver.cpp | 134 
 clang/tools/driver/driver.cpp   | 130 +--
 3 files changed, 142 insertions(+), 129 deletions(-)

diff --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index c4cab360bab3bb..d408907efb86b5 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -28,8 +28,8 @@
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/StringSaver.h"
 
-#include 
 #include 
+#include 
 #include 
 #include 
 
@@ -839,6 +839,11 @@ llvm::Error expandResponseFiles(SmallVectorImpl &Args,
 bool ClangCLMode, llvm::BumpPtrAllocator 
&Alloc,
 llvm::vfs::FileSystem *FS = nullptr);
 
+void applyOverrideOptions(SmallVectorImpl &Args,
+  const char *OverrideOpts,
+  std::set &SavedStrings,
+  raw_ostream *OS = nullptr);
+
 } // end namespace driver
 } // end namespace clang
 
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 190782a79a2456..43173ad3996fa3 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -87,6 +87,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/RISCVISAInfo.h"
+#include "llvm/Support/Regex.h"
 #include "llvm/Support/StringSaver.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
@@ -6677,3 +6678,136 @@ llvm::Error 
driver::expandResponseFiles(SmallVectorImpl &Args,
 
   return llvm::Error::success();
 }
+
+namespace {
+
+const char *GetStableCStr(std::set &SavedStrings, StringRef S) {
+  return SavedStrings.insert(std::string(S)).first->c_str();
+}
+
+/// ApplyOneQAOverride - Apply a list of edits to the input argument lists.
+///
+/// The input string is a space separated list of edits to perform,
+/// they are applied in order to the input argument lists. Edits
+/// should be one of the following forms:
+///
+///  '#': Silence information about the changes to the command line arguments.
+///
+///  '^': Add FOO as a new argument at the beginning of the command line.
+///
+///  '+': Add FOO as a new argument at the end of the command line.
+///
+///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the 
command
+///  line.
+///
+///  'xOPTION': Removes all instances of the literal argument OPTION.
+///
+///  'XOPTION': Removes all instances of the literal argument OPTION,
+///  and the following argument.
+///
+///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
+///  at the end of the command line.
+///
+/// \param OS - The stream to write edit information to.
+/// \param Args - The vector of command line arguments.
+/// \param Edit - The override command to perform.
+/// \param SavedStrings - Set to use for storing string representations.
+void applyOneOverrideOption(raw_ostream &OS,
+SmallVectorImpl &Args, StringRef 
Edit,
+std::set &SavedStrings) {
+  // This does not need to be efficient.
+
+  if (Edit[0] == '^') {
+const char *Str = GetStableCStr(SavedStrings, Edit.substr(1));
+OS << "### Adding argument " << Str << " at beginning\n";
+Args.insert(Args.begin() + 1, Str);
+  } else if (Edit[0] == '+') {
+const char *Str = GetStableCStr(SavedStrings, Edit.substr(1));
+OS << "### Adding argument " << Str << " at end\n";
+Args.push_back(Str);
+  } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.ends_with("/") &&
+ Edit.slice(2, Edit.size() - 1).contains('/')) {
+StringRef MatchPattern = Edit.substr(2).split('/').first;
+StringRef ReplPattern = Edit.substr(2).split('/').second;
+ReplPattern = ReplPattern.slice(0, ReplPattern.size() - 1);
+
+for (unsigned i = 1, e = Args.size(); i != e; ++i) {
+  // Ignore end-of-line response file markers
+  if (Args[i] == nullptr)
+continue;
+  std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
+
+  if (Repl != Args[i]) {
+OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
+Args[i] = GetStableCStr(SavedStrings, Repl);
+  }
+}
+  } else if (Edit[0] == 'x' || Edit[0] == 'X

[clang] [CLANG] Full support of complex multiplication and division. (PR #81514)

2024-03-15 Thread Andy Kaylor via cfe-commits




andykaylor wrote:

Can you add test cases for targets that will have problems with promotion. 
Something like this?

```
// RUN: %clang_cc1 -triple x86_64-windows-pc \
// RUN: -complex-range=promoted -emit-llvm -o - %s \
// RUN: | FileCheck %s --check-prefix=X86WINPRMTD

// RUN: %clang_cc1 -triple=avr-unknown-unknown -mdouble=32 \
// RUN: -complex-range=promoted -emit-llvm -o - %s \
// RUN: | FileCheck %s --check-prefix=AVRFP32

// RUN: %clang_cc1 -triple=avr-unknown-unknown -mdouble=64 \
// RUN: -complex-range=promoted -emit-llvm -o - %s \
// RUN: | FileCheck %s --check-prefix=AVRFP64
```

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


[clang] [CLANG] Full support of complex multiplication and division. (PR #81514)

2024-03-15 Thread Andy Kaylor via cfe-commits


@@ -287,9 +288,47 @@ class ComplexExprEmitter
   ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,
 const BinOpInfo &Op);
 
-  QualType getPromotionType(QualType Ty) {
+  QualType GetHigherPrecisionFPType(QualType ElementType) {
+const auto *CurrentBT = dyn_cast(ElementType);
+switch (CurrentBT->getKind()) {
+case BuiltinType::Kind::Float16:
+  return CGF.getContext().FloatTy;
+case BuiltinType::Kind::Float:
+case BuiltinType::Kind::BFloat16:
+  return CGF.getContext().DoubleTy;
+case BuiltinType::Kind::Double:
+  return CGF.getContext().LongDoubleTy;
+default:
+  return ElementType;
+}
+  }
+
+  QualType HigherPrecisionTypeForComplexArithmetic(QualType ElementType,
+   bool IsDivOpCode) {
+QualType HigherElementType = GetHigherPrecisionFPType(ElementType);
+const llvm::fltSemantics &ElementTypeSemantics =
+CGF.getContext().getFloatTypeSemantics(ElementType);
+const llvm::fltSemantics &HigherElementTypeSemantics =
+CGF.getContext().getFloatTypeSemantics(HigherElementType);
+if (llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 <=
+llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) {
+  return CGF.getContext().getComplexType(HigherElementType);
+} else {
+  FPHasBeenPromoted = LangOptions::ComplexRangeKind::CX_Improved;

andykaylor wrote:

Can you add a test for this case?

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


[clang] [CLANG] Full support of complex multiplication and division. (PR #81514)

2024-03-15 Thread Andy Kaylor via cfe-commits

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


[clang] [CLANG] Full support of complex multiplication and division. (PR #81514)

2024-03-15 Thread Andy Kaylor via cfe-commits

https://github.com/andykaylor commented:

Except for lacking a couple of tests, I think this looks good. @jcranmer-intel 
do you agree?

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


[clang] [clang-format] Fix clang-format issue with 'new' and 'delete' keywords in C files (PR #85470)

2024-03-15 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 60fa2b0670b874b702ddb9f81d098af692ea6875 
1e815bb2090f7747da027a04f69906063db7b02a -- clang/lib/Format/TokenAnnotator.cpp 
clang/unittests/Format/FormatTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 410e08ea58..a6f9a0941c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11449,7 +11449,7 @@ TEST_F(FormatTest, UnderstandsNewAndDelete) {
"void delete(link p);",
"void new (link p);\n"
"void delete (link p);");
-  
+
   verifyFormat("{ p->delete(); }\n"
"{ p->new(); }",
"{ p->delete (); }\n"

``




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


[clang] [clang-format] Fix clang-format issue with 'new' and 'delete' keywords in C files (PR #85470)

2024-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: None (scythris)


Changes

This resolves an issue in clang-format where `new` and `delete` were 
incorrectly formatted as keywords in C files. The fix modifies 
`TokenAnnotator::spaceRequiredBetween` to handle `new` and `delete` when used 
as identifiers for function pointers in structs in C code.

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


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+1-1) 
- (modified) clang/unittests/Format/FormatTest.cpp (+5) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e464c2b5731a35..c58204ce33ae52 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4607,7 +4607,7 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
   return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
  spaceRequiredBeforeParens(Right);
 }
-if (!Left.Previous || Left.Previous->isNot(tok::period)) {
+if (!Left.Previous || !Left.Previous->isOneOf(tok::period, tok::arrow)) {
   if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) {
 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index fc367a7a5a8981..410e08ea589692 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11449,6 +11449,11 @@ TEST_F(FormatTest, UnderstandsNewAndDelete) {
"void delete(link p);",
"void new (link p);\n"
"void delete (link p);");
+  
+  verifyFormat("{ p->delete(); }\n"
+   "{ p->new(); }",
+   "{ p->delete (); }\n"
+   "{ p->new (); }");
 
   FormatStyle AfterPlacementOperator = getLLVMStyle();
   AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;

``




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


[clang] [clang-format] Fix clang-format issue with 'new' and 'delete' keywords in C files (PR #85470)

2024-03-15 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] [clang-format] Fix clang-format issue with 'new' and 'delete' keywords in C files (PR #85470)

2024-03-15 Thread via cfe-commits

https://github.com/scythris created 
https://github.com/llvm/llvm-project/pull/85470

This resolves an issue in clang-format where `new` and `delete` were 
incorrectly formatted as keywords in C files. The fix modifies 
`TokenAnnotator::spaceRequiredBetween` to handle `new` and `delete` when used 
as identifiers for function pointers in structs in C code.

>From 1e815bb2090f7747da027a04f69906063db7b02a Mon Sep 17 00:00:00 2001
From: Trym Strand 
Date: Fri, 15 Mar 2024 21:56:22 +0100
Subject: [PATCH] Fix clang-format issue with 'delete' keyword in C files

This patch resolves an issue in clang-format where 'delete' was incorrectly 
recognized as a keyword in C files. The fix modifies the TokenAnnotator rules 
to correctly handle 'delete' as an identifier in C code, preventing incorrect 
formatting.
---
 clang/lib/Format/TokenAnnotator.cpp   | 2 +-
 clang/unittests/Format/FormatTest.cpp | 5 +
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e464c2b5731a35..c58204ce33ae52 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4607,7 +4607,7 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
   return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
  spaceRequiredBeforeParens(Right);
 }
-if (!Left.Previous || Left.Previous->isNot(tok::period)) {
+if (!Left.Previous || !Left.Previous->isOneOf(tok::period, tok::arrow)) {
   if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) {
 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index fc367a7a5a8981..410e08ea589692 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11449,6 +11449,11 @@ TEST_F(FormatTest, UnderstandsNewAndDelete) {
"void delete(link p);",
"void new (link p);\n"
"void delete (link p);");
+  
+  verifyFormat("{ p->delete(); }\n"
+   "{ p->new(); }",
+   "{ p->delete (); }\n"
+   "{ p->new (); }");
 
   FormatStyle AfterPlacementOperator = getLLVMStyle();
   AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;

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


[clang] [clang] Better bitfield access units (PR #65742)

2024-03-15 Thread Nathan Sidwell via cfe-commits


@@ -439,82 +444,194 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // We do this in two phases, processing a sequential run of bitfield
+  // declarations.
+
+  // a) Bitfields that share parts of a single byte are, of necessity, placed 
in
+  // the same access unit. That unit will encompass a consecutive
+  // run where adjacent bitfields share parts of a byte. (The first bitfield of
+  // such an access unit will start at the beginning of a byte.)
+
+  // b) Accumulate adjacent access units when the combined unit is naturally
+  // sized, no larger than a register, and on a strict alignment ISA,
+  // aligned. Note that this requires lookahead to one or more subsequent 
access
+  // units. For instance, consider a 2-byte access-unit followed by 2 1-byte
+  // units. We can merge that into a 4-byte access-unit, but we would not want
+  // to merge a 2-byte followed by a single 1-byte (and no available tail
+  // padding).
+
+  // This accumulation is prevented when:
+  // *) it would cross a zero-width bitfield (ABI-dependent), or
+  // *) one of the candidate access units contains a volatile bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  RecordDecl::field_iterator Begin = FieldEnd;
+  CharUnits StartOffset;
+  uint64_t BitSize;
+  CharUnits BestEndOffset;
+  RecordDecl::field_iterator BestEnd = B

[clang] [llvm] [CodeGen][AArch64][FMV] PAC the stub_helper's frame on arm64e (PR #84704)

2024-03-15 Thread Ahmed Bougacha via cfe-commits


@@ -2085,6 +2099,37 @@ void 
AArch64AsmPrinter::emitMachOIFuncStubHelperBody(Module &M,
.addImm(2),
*STI);
 
+  if (TM.getTargetTriple().isArm64e()) {
+//   autibsp

ahmedbougacha wrote:

There is not, but send me your patch and I'll tack it onto the relevant commit 
(and split the tail-call check emission into a helper)

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


[clang] [llvm] [CodeGen][AArch64][FMV] PAC the stub_helper's frame on arm64e (PR #84704)

2024-03-15 Thread Jon Roelofs via cfe-commits


@@ -2085,6 +2099,37 @@ void 
AArch64AsmPrinter::emitMachOIFuncStubHelperBody(Module &M,
.addImm(2),
*STI);
 
+  if (TM.getTargetTriple().isArm64e()) {
+//   autibsp

jroelofs wrote:

Is there a PR up for that that I should tack this bit onto the end of?

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


[clang] [llvm] [HLSL] implement `clamp` intrinsic (PR #85424)

2024-03-15 Thread Chris B via cfe-commits

https://github.com/llvm-beanz approved this pull request.


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


[clang] [llvm] [AArch64][PAC] Support ptrauth builtins and -fptrauth-intrinsics. (PR #65996)

2024-03-15 Thread Ahmed Bougacha via cfe-commits

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


[clang] 0481f04 - [AArch64][PAC] Support ptrauth builtins and -fptrauth-intrinsics. (#65996)

2024-03-15 Thread via cfe-commits

Author: Ahmed Bougacha
Date: 2024-03-15T14:17:21-07:00
New Revision: 0481f049c37029d829dbc0c0cc5d1ee71c6d1c9a

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

LOG: [AArch64][PAC] Support ptrauth builtins and -fptrauth-intrinsics. (#65996)

This defines the basic set of pointer authentication clang builtins
(provided in a new header, ptrauth.h), with diagnostics and IRGen
support.  The availability of the builtins is gated on a new flag,
`-fptrauth-intrinsics`.

Note that this only includes the basic intrinsics, and notably excludes
`ptrauth_sign_constant`, `ptrauth_type_discriminator`, and
`ptrauth_string_discriminator`, which need extra logic to be fully
supported.

This also introduces clang/docs/PointerAuthentication.rst, which
describes the ptrauth model in general, in addition to these builtins.

Co-Authored-By: Akira Hatanaka 
Co-Authored-By: John McCall 

Added: 
clang/docs/PointerAuthentication.rst
clang/lib/Headers/ptrauth.h
clang/test/CodeGen/ptrauth-intrinsics.c
clang/test/Preprocessor/ptrauth_feature.c
clang/test/Sema/ptrauth-intrinsics-macro.c
clang/test/Sema/ptrauth.c

Modified: 
clang/docs/LanguageExtensions.rst
clang/include/clang/Basic/Builtins.td
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Basic/Features.def
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Basic/TargetInfo.h
clang/include/clang/Driver/Options.td
clang/include/clang/Sema/Sema.h
clang/lib/Basic/TargetInfo.cpp
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Basic/Targets/AArch64.h
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/Headers/CMakeLists.txt
clang/lib/Headers/module.modulemap
clang/lib/Sema/SemaChecking.cpp
llvm/docs/PointerAuth.md

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 225736009d4869..13d7261d83d7f1 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -13,6 +13,7 @@ Clang Language Extensions
BlockLanguageSpec
Block-ABI-Apple
AutomaticReferenceCounting
+   PointerAuthentication
MatrixTypes
 
 Introduction
@@ -4318,6 +4319,10 @@ reordering of memory accesses and side effect 
instructions. Other instructions
 like simple arithmetic may be reordered around the intrinsic. If you expect to
 have no reordering at all, use inline assembly instead.
 
+Pointer Authentication
+^^
+See :doc:`PointerAuthentication`.
+
 X86/X86-64 Language Extensions
 --
 

diff  --git a/clang/docs/PointerAuthentication.rst 
b/clang/docs/PointerAuthentication.rst
new file mode 100644
index 00..19b3384293aede
--- /dev/null
+++ b/clang/docs/PointerAuthentication.rst
@@ -0,0 +1,485 @@
+Pointer Authentication
+==
+
+.. contents::
+   :local:
+
+Introduction
+
+
+Pointer authentication is a technology which offers strong probabilistic
+protection against exploiting a broad class of memory bugs to take control of
+program execution.  When adopted consistently in a language ABI, it provides
+a form of relatively fine-grained control flow integrity (CFI) check that
+resists both return-oriented programming (ROP) and jump-oriented programming
+(JOP) attacks.
+
+While pointer authentication can be implemented purely in software, direct
+hardware support (e.g. as provided by Armv8.3 PAuth) can dramatically improve
+performance and code size.  Similarly, while pointer authentication
+can be implemented on any architecture, taking advantage of the (typically)
+excess addressing range of a target with 64-bit pointers minimizes the impact
+on memory performance and can allow interoperation with existing code (by
+disabling pointer authentication dynamically).  This document will generally
+attempt to present the pointer authentication feature independent of any
+hardware implementation or ABI.  Considerations that are
+implementation-specific are clearly identified throughout.
+
+Note that there are several 
diff erent terms in use:
+
+- **Pointer authentication** is a target-independent language technology.
+
+- **PAuth** (sometimes referred to as **PAC**, for Pointer Authentication
+  Codes) is an AArch64 architecture extension that provides hardware support
+  for pointer authentication.  Additional extensions either modify some of the
+  PAuth instruction behavior (notably FPAC), or provide new instruction
+  variants (PAuth_LR).
+
+- **Armv8.3** is an AArch64 architecture revision that makes PAuth mandatory.
+
+- **arm64e** is a specific ABI (not yet fully stable) for implem

[clang] [llvm] [AArch64][PAC] Support ptrauth builtins and -fptrauth-intrinsics. (PR #65996)

2024-03-15 Thread Ahmed Bougacha via cfe-commits

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


[clang] [llvm] [AArch64][PAC] Support ptrauth builtins and -fptrauth-intrinsics. (PR #65996)

2024-03-15 Thread Ahmed Bougacha via cfe-commits

https://github.com/ahmedbougacha updated 
https://github.com/llvm/llvm-project/pull/65996

>From 1492d6362a1a4f6d65fb7001bdefb5250f30754e Mon Sep 17 00:00:00 2001
From: Ahmed Bougacha 
Date: Wed, 16 Aug 2023 09:17:12 -0700
Subject: [PATCH] [AArch64][PAC] Support and document ptrauth builtins and
 -fptrauth-intrinsics.

This defines the basic set of pointer authentication clang builtins
(provided in a new header, ptrauth.h), with diagnostics and IRGen
support.  The availability of the builtins is gated on a new flag,
`-fptrauth-intrinsics`.

Note that this only includes the basic intrinsics, and notably excludes
`ptrauth_sign_constant`, `ptrauth_type_discriminator`, and
`ptrauth_string_discriminator`, which need extra logic to be fully
supported.

This also introduces clang/docs/PointerAuthentication.rst, which
describes the ptrauth model in general, in addition to these builtins.

Co-Authored-By: Akira Hatanaka 
Co-Authored-By: John McCall 
---
 clang/docs/LanguageExtensions.rst |   5 +
 clang/docs/PointerAuthentication.rst  | 485 ++
 clang/include/clang/Basic/Builtins.td |  37 ++
 clang/include/clang/Basic/DiagnosticGroups.td |   1 +
 .../clang/Basic/DiagnosticSemaKinds.td|  16 +
 clang/include/clang/Basic/Features.def|   1 +
 clang/include/clang/Basic/LangOptions.def |   2 +
 clang/include/clang/Basic/TargetInfo.h|   6 +
 clang/include/clang/Driver/Options.td |   8 +
 clang/include/clang/Sema/Sema.h   |   2 +
 clang/lib/Basic/TargetInfo.cpp|   4 +
 clang/lib/Basic/Targets/AArch64.cpp   |   6 +
 clang/lib/Basic/Targets/AArch64.h |   2 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  67 +++
 clang/lib/Driver/ToolChains/Clang.cpp |   4 +
 clang/lib/Frontend/CompilerInvocation.cpp |  14 +
 clang/lib/Headers/CMakeLists.txt  |   1 +
 clang/lib/Headers/module.modulemap|   5 +
 clang/lib/Headers/ptrauth.h   | 185 +++
 clang/lib/Sema/SemaChecking.cpp   | 197 +++
 clang/test/CodeGen/ptrauth-intrinsics.c   |  73 +++
 clang/test/Preprocessor/ptrauth_feature.c |  10 +
 clang/test/Sema/ptrauth-intrinsics-macro.c|  34 ++
 clang/test/Sema/ptrauth.c | 126 +
 llvm/docs/PointerAuth.md  |   3 +
 25 files changed, 1294 insertions(+)
 create mode 100644 clang/docs/PointerAuthentication.rst
 create mode 100644 clang/lib/Headers/ptrauth.h
 create mode 100644 clang/test/CodeGen/ptrauth-intrinsics.c
 create mode 100644 clang/test/Preprocessor/ptrauth_feature.c
 create mode 100644 clang/test/Sema/ptrauth-intrinsics-macro.c
 create mode 100644 clang/test/Sema/ptrauth.c

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 225736009d4869..13d7261d83d7f1 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -13,6 +13,7 @@ Clang Language Extensions
BlockLanguageSpec
Block-ABI-Apple
AutomaticReferenceCounting
+   PointerAuthentication
MatrixTypes
 
 Introduction
@@ -4318,6 +4319,10 @@ reordering of memory accesses and side effect 
instructions. Other instructions
 like simple arithmetic may be reordered around the intrinsic. If you expect to
 have no reordering at all, use inline assembly instead.
 
+Pointer Authentication
+^^
+See :doc:`PointerAuthentication`.
+
 X86/X86-64 Language Extensions
 --
 
diff --git a/clang/docs/PointerAuthentication.rst 
b/clang/docs/PointerAuthentication.rst
new file mode 100644
index 00..19b3384293aede
--- /dev/null
+++ b/clang/docs/PointerAuthentication.rst
@@ -0,0 +1,485 @@
+Pointer Authentication
+==
+
+.. contents::
+   :local:
+
+Introduction
+
+
+Pointer authentication is a technology which offers strong probabilistic
+protection against exploiting a broad class of memory bugs to take control of
+program execution.  When adopted consistently in a language ABI, it provides
+a form of relatively fine-grained control flow integrity (CFI) check that
+resists both return-oriented programming (ROP) and jump-oriented programming
+(JOP) attacks.
+
+While pointer authentication can be implemented purely in software, direct
+hardware support (e.g. as provided by Armv8.3 PAuth) can dramatically improve
+performance and code size.  Similarly, while pointer authentication
+can be implemented on any architecture, taking advantage of the (typically)
+excess addressing range of a target with 64-bit pointers minimizes the impact
+on memory performance and can allow interoperation with existing code (by
+disabling pointer authentication dynamically).  This document will generally
+attempt to present the pointer authentication feature independent of any
+hardware implementation or ABI.  Considerations that are
+implementation-specific are clearly identified throughout.
+
+Note that th

  1   2   3   4   >