[clang] [Clang] Implement CWG2351 `void{}` (PR #78060)

2024-12-30 Thread A. Jiang via cfe-commits

https://github.com/frederick-vs-ja edited 
https://github.com/llvm/llvm-project/pull/78060
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] implement views::concat (PR #120920)

2024-12-30 Thread Nhat Nguyen via cfe-commits

https://github.com/changkhothuychung updated 
https://github.com/llvm/llvm-project/pull/120920

error: too big or took too long to generate
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] implement views::concat (PR #120920)

2024-12-30 Thread Nhat Nguyen via cfe-commits

https://github.com/changkhothuychung updated 
https://github.com/llvm/llvm-project/pull/120920

error: too big or took too long to generate
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Fix issue #117960 (PR #121039)

2024-12-30 Thread via cfe-commits

cor3ntin wrote:

Thanks for the PR. Can you update the commit message to be more descriptive?

I'm not sure the fix is sufficient.
I think most of the checks done in `ActOnEnumBody` should be (re) performed on 
instantiation.

Maybe we should instead

- Add a new `BuildEnumBody` function, move most (all?) the implementation of  
`ActOnEnumBody` to that
- call `BuildEnumBody` from both `ActOnEnumBody` and `RebuildEnumType`

That would not only fix the crash but also the fact that we are seemingly 
missing a lot of diagnostics
https://godbolt.org/z/17dTW4dEe


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


[clang] [Clang] Add GCC's __builtin_stack_address() to Clang (#82632). (PR #121332)

2024-12-30 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/121332
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Add GCC's __builtin_stack_address() to Clang (#82632). (PR #121332)

2024-12-30 Thread via cfe-commits

https://github.com/aalhwc created 
https://github.com/llvm/llvm-project/pull/121332

This new builtin returns the value of the stack pointer register, mirroring 
GCC's __builtin_stack_address(). This implementation initially supports only 
the x86 and x86_64 architectures. Support for other architectures can be added 
in future patches.

>From 7c4f49391753b22dd2e2ce96e9ad6a6cd6c9ae40 Mon Sep 17 00:00:00 2001
From: aalhwc 
Date: Mon, 30 Dec 2024 05:03:59 -0500
Subject: [PATCH] [Clang] Add GCC's __builtin_stack_address() to Clang
 (#82632).

This new builtin returns the value of the stack pointer register,
mirroring GCC's __builtin_stack_address(). This implementation initially
supports only the x86 and x86_64 architectures. Support for other
architectures can be added in future patches.
---
 clang/include/clang/Basic/Builtins.td |  6 ++
 clang/lib/CodeGen/CGBuiltin.cpp   | 24 +++
 clang/test/CodeGen/builtin-stackaddress.c | 13 
 3 files changed, 43 insertions(+)
 create mode 100644 clang/test/CodeGen/builtin-stackaddress.c

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index b5b47ae2746011..69aed2e6b2f0ca 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -899,6 +899,12 @@ def FrameAddress : Builtin {
   let Prototype = "void*(_Constant unsigned int)";
 }
 
+def StackAddress : Builtin {
+  let Spellings = ["__builtin_stack_address"];
+  let Attributes = [NoThrow];
+  let Prototype = "void*()";
+}
+
 def ClearCache : Builtin {
   let Spellings = ["__builtin___clear_cache"];
   let Attributes = [NoThrow];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 4d4b7428abd505..d691958852699e 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4782,6 +4782,30 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
 return RValue::get(Builder.CreateCall(F, Depth));
   }
+  case Builtin::BI__builtin_stack_address: {
+IntegerType *SPRegType;
+StringRef SPRegName;
+switch (getTarget().getTriple().getArch()) {
+case Triple::x86:
+  SPRegType = Int32Ty;
+  SPRegName = "esp";
+  break;
+case Triple::x86_64:
+  SPRegType = Int64Ty;
+  SPRegName = "rsp";
+  break;
+default:
+  llvm_unreachable("Intrinsic __builtin_stack_address is not supported for 
"
+   "the target architecture");
+}
+Function *F = CGM.getIntrinsic(Intrinsic::read_register, {SPRegType});
+Value *SPRegValue = MetadataAsValue::get(
+getLLVMContext(),
+MDNode::get(getLLVMContext(),
+{MDString::get(getLLVMContext(), SPRegName)}));
+Value *Call = Builder.CreateCall(F, SPRegValue);
+return RValue::get(Builder.CreateIntToPtr(Call, Int8PtrTy));
+  }
   case Builtin::BI__builtin_extract_return_addr: {
 Value *Address = EmitScalarExpr(E->getArg(0));
 Value *Result = getTargetHooks().decodeReturnAddress(*this, Address);
diff --git a/clang/test/CodeGen/builtin-stackaddress.c 
b/clang/test/CodeGen/builtin-stackaddress.c
new file mode 100644
index 00..5b1ddad45f21a1
--- /dev/null
+++ b/clang/test/CodeGen/builtin-stackaddress.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -triple i686-unknown-unknown -emit-llvm -o - %s | FileCheck 
-check-prefix=X86 %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s | 
FileCheck -check-prefix=X86_64 %s
+
+void* a() {
+  // X86_64: [[INT_SP:%.*]] = call i64 @llvm.read_register.i64(metadata 
[[SPREG:![0-9]+]])
+  // X86_64: inttoptr i64 [[INT_SP]] 
+  // X86_64: [[SPREG]] = !{!"rsp"}
+  //
+  // X86: [[INT_SP:%.*]] = call i32 @llvm.read_register.i32(metadata 
[[SPREG:![0-9]+]])
+  // X86: inttoptr i32 [[INT_SP]] 
+  // X86: [[SPREG]] = !{!"esp"}
+  return __builtin_stack_address();
+}

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


[clang] [Clang] Diagnose unexpanded packs for NTTP type constraints (PR #121296)

2024-12-30 Thread via cfe-commits


@@ -305,3 +305,45 @@ 
static_assert(__is_same_as(_Three_way_comparison_result_with_tuple_like,
 0>::type, long));
 
 }
+
+namespace GH88866 {
+
+template  struct index_by;
+
+template 
+concept InitFunc = true;
+
+namespace Invalid {
+
+template  auto... init>
+struct LazyLitMatrix;
+
+template <
+typename...Indices,
+InitFunc> auto... init
+// expected-error@-1 {{type constraint contains unexpanded parameter pack 
'Indices'}}

cor3ntin wrote:

Why do you think this is invalid?
https://eel.is/c++draft/temp.variadic#6.4.1

I expect it to be equivalent to

```cpp
template <
typename...Indices,
InitFunc> auto init,
InitFunc> auto init1
>
struct LazyLitMatrix, init, init1>
```
(GCC accepts this code)


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


[clang] [Clang] Add GCC's __builtin_stack_address() to Clang (#82632). (PR #121332)

2024-12-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (aalhwc)


Changes

This new builtin returns the value of the stack pointer register, mirroring 
GCC's __builtin_stack_address(). This implementation initially supports only 
the x86 and x86_64 architectures. Support for other architectures can be added 
in future patches.

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


3 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.td (+6) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+24) 
- (added) clang/test/CodeGen/builtin-stackaddress.c (+13) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index b5b47ae2746011..69aed2e6b2f0ca 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -899,6 +899,12 @@ def FrameAddress : Builtin {
   let Prototype = "void*(_Constant unsigned int)";
 }
 
+def StackAddress : Builtin {
+  let Spellings = ["__builtin_stack_address"];
+  let Attributes = [NoThrow];
+  let Prototype = "void*()";
+}
+
 def ClearCache : Builtin {
   let Spellings = ["__builtin___clear_cache"];
   let Attributes = [NoThrow];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 4d4b7428abd505..d691958852699e 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4782,6 +4782,30 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
 return RValue::get(Builder.CreateCall(F, Depth));
   }
+  case Builtin::BI__builtin_stack_address: {
+IntegerType *SPRegType;
+StringRef SPRegName;
+switch (getTarget().getTriple().getArch()) {
+case Triple::x86:
+  SPRegType = Int32Ty;
+  SPRegName = "esp";
+  break;
+case Triple::x86_64:
+  SPRegType = Int64Ty;
+  SPRegName = "rsp";
+  break;
+default:
+  llvm_unreachable("Intrinsic __builtin_stack_address is not supported for 
"
+   "the target architecture");
+}
+Function *F = CGM.getIntrinsic(Intrinsic::read_register, {SPRegType});
+Value *SPRegValue = MetadataAsValue::get(
+getLLVMContext(),
+MDNode::get(getLLVMContext(),
+{MDString::get(getLLVMContext(), SPRegName)}));
+Value *Call = Builder.CreateCall(F, SPRegValue);
+return RValue::get(Builder.CreateIntToPtr(Call, Int8PtrTy));
+  }
   case Builtin::BI__builtin_extract_return_addr: {
 Value *Address = EmitScalarExpr(E->getArg(0));
 Value *Result = getTargetHooks().decodeReturnAddress(*this, Address);
diff --git a/clang/test/CodeGen/builtin-stackaddress.c 
b/clang/test/CodeGen/builtin-stackaddress.c
new file mode 100644
index 00..5b1ddad45f21a1
--- /dev/null
+++ b/clang/test/CodeGen/builtin-stackaddress.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -triple i686-unknown-unknown -emit-llvm -o - %s | FileCheck 
-check-prefix=X86 %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s | 
FileCheck -check-prefix=X86_64 %s
+
+void* a() {
+  // X86_64: [[INT_SP:%.*]] = call i64 @llvm.read_register.i64(metadata 
[[SPREG:![0-9]+]])
+  // X86_64: inttoptr i64 [[INT_SP]] 
+  // X86_64: [[SPREG]] = !{!"rsp"}
+  //
+  // X86: [[INT_SP:%.*]] = call i32 @llvm.read_register.i32(metadata 
[[SPREG:![0-9]+]])
+  // X86: inttoptr i32 [[INT_SP]] 
+  // X86: [[SPREG]] = !{!"esp"}
+  return __builtin_stack_address();
+}

``




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


[clang] [Clang] Add GCC's __builtin_stack_address() to Clang. (PR #121332)

2024-12-30 Thread via cfe-commits

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


[clang] [Clang] Add GCC's __builtin_stack_address() to Clang. (PR #121332)

2024-12-30 Thread via cfe-commits

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


[clang] Delay marking pending incomplete decl chains until the end of `finishPendingActions`. (PR #121245)

2024-12-30 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

+1. It is best to have more test case. Generally I reduce it by hand in this 
case.

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits


@@ -1520,15 +1520,72 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'00101'1,  ; LLo
+///  10'1'0]  ; LHi
+///   RHS = [10'1'0,  ; RLo
+///  10'1'1]  ; RHi
+///
+/// we know that the higher 2 bits of the result is always 10; and we also
+/// notice that RHS[1:6] are always 1, so the result[1:6] cannot be less than
+/// LHS[1:6] (i.e., 00101). Thus, the lower bound is 10'00101'0.
+///
+/// The algorithm is as follows,
+/// 1. we first calculate a mask to find the higher common bits by
+///   Mask = ~((LLo ^ LHi) | (LLo ^ LHi) | (LLo ^ RLo));
+///   Mask = clear all non-leading-ones bits in Mask;
+///in the example, the Mask is set to 11'0'0;
+/// 2. calculate a new mask by setting all common leading bits to 1 in RHS, and
+///keeping the longest leading ones (i.e., 11'1'0 in the example).
+/// 3. return (LLo & new mask) as the lower bound;
+/// 4. repeat the step 2 and 3 with LHS and RHS swapped, and update the lower
+///bound with the larger one.
+static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS,

zsrkmyn wrote:

> I happened to analyze the problem in Oct and made a comment to 
> https://stackoverflow.com/questions/2620388/bitwise-interval-arithmetic
> 
> Do the two algorithms return the same result? If yes, my code seems simpler?

Aha, I saw your answer on SO before, but I don't think they are same. E.g., 
given

```
a.lo = 0b110101;
a.hi = 0b111000;  // inclusive
b.lo = 0b11;
b.hi = 0b11;
```

your algorithm gives the lower bound as `0b11`, while mine gives `0b110101`.

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


[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2024-12-30 Thread Owen Pan via cfe-commits

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

>From abbe00e409219bcc3ce08c21548d809c9d5bea39 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 29 Dec 2024 20:17:46 -0800
Subject: [PATCH] [clang-format] Add VariableTemplate option

Closes #120148.
---
 clang/docs/ClangFormatStyleOptions.rst| 13 +++--
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Format/Format.h   | 15 ---
 clang/lib/Format/Format.cpp   |  1 +
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/FormatTokenLexer.cpp |  4 
 clang/lib/Format/FormatTokenLexer.h   |  3 ++-
 clang/lib/Format/TokenAnnotator.cpp   | 19 +++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 13 +
 9 files changed, 60 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..df0b68d7c401d1 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -6725,8 +6725,8 @@ the configuration (without a prefix: ``Auto``).
 .. _TemplateNames:
 
 **TemplateNames** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
-  A vector of non-keyword identifiers that should be interpreted as
-  template names.
+  A vector of non-keyword identifiers that should be interpreted as template
+  names.
 
   A ``<`` after a template name is annotated as a template opener instead of
   a binary operator.
@@ -6793,6 +6793,15 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+.. _VariableTemplates:
+
+**VariableTemplates** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
+  A vector of non-keyword identifiers that should be interpreted as variable
+  template names.
+
+  A ``)`` after a variable template instantiation is *not* annotated as the
+  closing parenthesis of C-style cast operator.
+
 .. _VerilogBreakBetweenInstancePorts:
 
 **VerilogBreakBetweenInstancePorts** (``Boolean``) :versionbadge:`clang-format 
17` :ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9b0cb815a15db..f05a95e31dc255 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1118,6 +1118,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``VariableTemplates`` option.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..98f99627ee0beb 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5038,8 +5038,8 @@ struct FormatStyle {
   /// \version 3.7
   unsigned TabWidth;
 
-  /// A vector of non-keyword identifiers that should be interpreted as
-  /// template names.
+  /// A vector of non-keyword identifiers that should be interpreted as 
template
+  /// names.
   ///
   /// A ``<`` after a template name is annotated as a template opener instead 
of
   /// a binary operator.
@@ -5099,6 +5099,15 @@ struct FormatStyle {
   /// \version 3.7
   UseTabStyle UseTab;
 
+  /// A vector of non-keyword identifiers that should be interpreted as 
variable
+  /// template names.
+  ///
+  /// A ``)`` after a variable template instantiation is *not* annotated as the
+  /// closing parenthesis of C-style cast operator.
+  ///
+  /// \version 20
+  std::vector VariableTemplates;
+
   /// For Verilog, put each port on its own line in module instantiations.
   /// \code
   ///true:
@@ -5308,7 +5317,7 @@ struct FormatStyle {
TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
-   UseTab == R.UseTab &&
+   UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
VerilogBreakBetweenInstancePorts ==
R.VerilogBreakBetweenInstancePorts &&
WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros;
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..fe5465ce7b09de 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1164,6 +1164,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
 IO.mapOptional("UseTab", Style.UseTab);
+IO.mapOptional("VariableTemplates", Style.VariableTemplates);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
 IO.mapOptional("WhitespaceSensitiveMacros",
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f6bb860a1fea31..8917049cefb865 100644
--- a/

[clang] [Clang][Sema] Expose static inline functions from GMF (PR #104701)

2024-12-30 Thread Chuanqi Xu via cfe-commits
Jan =?utf-8?q?Kokem=C3=BCller?= ,
Jan =?utf-8?q?Kokem=C3=BCller?= ,
Jan =?utf-8?q?Kokem=C3=BCller?= ,
Jan =?utf-8?q?Kokem=C3=BCller?= 
Message-ID:
In-Reply-To: 


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

LGTM. Thanks

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


[clang] [Clang][Sema] Expose static inline functions from GMF (PR #104701)

2024-12-30 Thread Chuanqi Xu via cfe-commits
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= 
Message-ID:
In-Reply-To: 


ChuanqiXu9 wrote:

You may want to add a note in ReleaseNotes too. And if you want to write a 
paper to WG21, please CC me or I'd love to be a co-author with you.

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


[clang] e50ec3e - [Clang][Sema] Expose static inline functions from GMF (#104701)

2024-12-30 Thread via cfe-commits

Author: Jan Kokemüller
Date: 2024-12-31T09:53:29+08:00
New Revision: e50ec3e46bea819a1d7aea1cee2d7e11197bbdd2

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

LOG: [Clang][Sema] Expose static inline functions from GMF (#104701)

In C, it is a common pattern to have `static inline` functions in
headers to avoid ODR issues. Currently, when those headers are included
in a GMF, the names are not found when two-phase name lookup and ADL is
involved. Those names are removed by `Sema::AddOverloadCandidate`.

Similarly, in C++, sometimes people use templates with internal linkage
in headers.

As the GMF was designed to be a transitional mechanism for headers,
special case those functions in `Sema::AddOverloadCandidate`.

This fixes .

Added: 
clang/test/Modules/expose-static-inline-from-gmf-1.cppm
clang/test/Modules/expose-static-inline-from-gmf-2.cppm
clang/test/Modules/expose-static-inline-from-gmf-3.cppm
clang/test/Modules/expose-static-inline-from-gmf-4.cppm
clang/test/Modules/expose-static-inline-from-gmf-5.cppm

Modified: 
clang/lib/Sema/SemaOverload.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index fff49b759c935e..7589701fb81de9 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -6977,11 +6977,26 @@ void Sema::AddOverloadCandidate(
 /// have linkage. So that all entities of the same should share one
 /// linkage. But in clang, 
diff erent entities of the same could have
 /// 
diff erent linkage.
-NamedDecl *ND = Function;
-if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
+const NamedDecl *ND = Function;
+bool IsImplicitlyInstantiated = false;
+if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
   ND = SpecInfo->getTemplate();
-
-if (ND->getFormalLinkage() == Linkage::Internal) {
+  IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
+ TSK_ImplicitInstantiation;
+}
+
+/// Don't remove inline functions with internal linkage from the overload
+/// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
+/// However:
+/// - Inline functions with internal linkage are a common pattern in
+///   headers to avoid ODR issues.
+/// - The global module is meant to be a transition mechanism for C and C++
+///   headers, and the current rules as written work against that goal.
+const bool IsInlineFunctionInGMF =
+Function->isFromGlobalModule() &&
+(IsImplicitlyInstantiated || Function->isInlined());
+
+if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) 
{
   Candidate.Viable = false;
   Candidate.FailureKind = ovl_fail_module_mismatched;
   return;

diff  --git a/clang/test/Modules/expose-static-inline-from-gmf-1.cppm 
b/clang/test/Modules/expose-static-inline-from-gmf-1.cppm
new file mode 100644
index 00..4de9b583dac8da
--- /dev/null
+++ b/clang/test/Modules/expose-static-inline-from-gmf-1.cppm
@@ -0,0 +1,37 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+//
+// RUN: %clang -std=c++20 %t/a.cppm --precompile -o %t/a.pcm \
+// RUN:   -DTEST_INLINE
+// RUN: %clang -std=c++20 %t/test.cc -fprebuilt-module-path=%t -fsyntax-only 
-Xclang -verify \
+// RUN:   -DTEST_INLINE
+//
+// RUN: %clang -std=c++20 %t/a.cppm --precompile -o %t/a.pcm
+// RUN: %clang -std=c++20 %t/test.cc -fprebuilt-module-path=%t -fsyntax-only 
-Xclang -verify
+
+//--- a.h
+#ifdef TEST_INLINE
+#define INLINE inline
+#else
+#define INLINE
+#endif
+static INLINE void func(long) {}
+template  void a() { func(T{}); }
+
+//--- a.cppm
+module;
+#include "a.h"
+export module a;
+export using ::a;
+
+//--- test.cc
+import a;
+auto m = (a(), 0);
+
+#ifdef TEST_INLINE
+// expected-no-diagnostics
+#else
+// expected-error@a.h:7 {{no matching function for call to 'func'}}
+// expected-n...@test.cc:2 {{in instantiation of function template 
specialization 'a' requested here}}
+#endif

diff  --git a/clang/test/Modules/expose-static-inline-from-gmf-2.cppm 
b/clang/test/Modules/expose-static-inline-from-gmf-2.cppm
new file mode 100644
index 00..c89b613f5074b1
--- /dev/null
+++ b/clang/test/Modules/expose-static-inline-from-gmf-2.cppm
@@ -0,0 +1,22 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+//
+// RUN: %clang -std=c++20 %t/a.cppm --precompile -o %t/a.pcm
+// RUN: %clang -std=c++20 %t/test.cc -fprebuilt-module-path=%t -fsyntax-only 
-Xclang -verify
+
+//--- a.h
+template  static inline void func() {}
+template  void a() { func(); }
+
+//--- a.cppm
+module;
+#include "a.h"
+export module a;

[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2024-12-30 Thread Owen Pan via cfe-commits

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

>From abbe00e409219bcc3ce08c21548d809c9d5bea39 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 29 Dec 2024 20:17:46 -0800
Subject: [PATCH] [clang-format] Add VariableTemplate option

Closes #120148.
---
 clang/docs/ClangFormatStyleOptions.rst| 13 +++--
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Format/Format.h   | 15 ---
 clang/lib/Format/Format.cpp   |  1 +
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/FormatTokenLexer.cpp |  4 
 clang/lib/Format/FormatTokenLexer.h   |  3 ++-
 clang/lib/Format/TokenAnnotator.cpp   | 19 +++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 13 +
 9 files changed, 60 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..df0b68d7c401d1 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -6725,8 +6725,8 @@ the configuration (without a prefix: ``Auto``).
 .. _TemplateNames:
 
 **TemplateNames** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
-  A vector of non-keyword identifiers that should be interpreted as
-  template names.
+  A vector of non-keyword identifiers that should be interpreted as template
+  names.
 
   A ``<`` after a template name is annotated as a template opener instead of
   a binary operator.
@@ -6793,6 +6793,15 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+.. _VariableTemplates:
+
+**VariableTemplates** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
+  A vector of non-keyword identifiers that should be interpreted as variable
+  template names.
+
+  A ``)`` after a variable template instantiation is *not* annotated as the
+  closing parenthesis of C-style cast operator.
+
 .. _VerilogBreakBetweenInstancePorts:
 
 **VerilogBreakBetweenInstancePorts** (``Boolean``) :versionbadge:`clang-format 
17` :ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9b0cb815a15db..f05a95e31dc255 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1118,6 +1118,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``VariableTemplates`` option.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..98f99627ee0beb 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5038,8 +5038,8 @@ struct FormatStyle {
   /// \version 3.7
   unsigned TabWidth;
 
-  /// A vector of non-keyword identifiers that should be interpreted as
-  /// template names.
+  /// A vector of non-keyword identifiers that should be interpreted as 
template
+  /// names.
   ///
   /// A ``<`` after a template name is annotated as a template opener instead 
of
   /// a binary operator.
@@ -5099,6 +5099,15 @@ struct FormatStyle {
   /// \version 3.7
   UseTabStyle UseTab;
 
+  /// A vector of non-keyword identifiers that should be interpreted as 
variable
+  /// template names.
+  ///
+  /// A ``)`` after a variable template instantiation is *not* annotated as the
+  /// closing parenthesis of C-style cast operator.
+  ///
+  /// \version 20
+  std::vector VariableTemplates;
+
   /// For Verilog, put each port on its own line in module instantiations.
   /// \code
   ///true:
@@ -5308,7 +5317,7 @@ struct FormatStyle {
TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
-   UseTab == R.UseTab &&
+   UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
VerilogBreakBetweenInstancePorts ==
R.VerilogBreakBetweenInstancePorts &&
WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros;
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..fe5465ce7b09de 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1164,6 +1164,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
 IO.mapOptional("UseTab", Style.UseTab);
+IO.mapOptional("VariableTemplates", Style.VariableTemplates);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
 IO.mapOptional("WhitespaceSensitiveMacros",
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f6bb860a1fea31..8917049cefb865 100644
--- a/

[clang-tools-extra] [clangd] Make EnableFunctionArgSnippets option string-typed (PR #121178)

2024-12-30 Thread Nathan Ridge via cfe-commits


@@ -242,13 +242,13 @@ opt FallbackStyle{
 init(clang::format::DefaultFallbackStyle),
 };
 
-opt EnableFunctionArgSnippets{
+opt EnableFunctionArgSnippets{

HighCommander4 wrote:

Thanks for the suggestion. I tried this briefly, but I think it makes the 
`--help` output too noisy because it prints a separate line for each spelling 
of `"true"`, `"True"`, etc.

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


[clang] [Clang][Sema] Expose static inline functions from GMF (PR #104701)

2024-12-30 Thread Chuanqi Xu via cfe-commits
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= 
Message-ID:
In-Reply-To: 


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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits


@@ -2720,6 +2720,22 @@ TEST_F(ConstantRangeTest, binaryAnd) {
   EXPECT_EQ(R16_32.binaryAnd(R0_99), R0_32);
   EXPECT_EQ(R0_99.binaryAnd(R16_32), R0_32);
 
+  // 'And' with leading bits are masked (with common leading bits stripped)

zsrkmyn wrote:

'And' op is tricky, since it operates regardless of the signedness and all 
ranges can be treated as unsigned. E.g., a range (with bitwidth=8) `[1, -10)` 
can be treated as `[1, 246)` because of the nature of 2's complement; 
similarly, range `[-3, -1)` can be treated as `[253, 255)`; and results won't 
be affected. And I think it's how `ConstantRange` designed.

I'll add a test anyway.

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


[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2024-12-30 Thread Owen Pan via cfe-commits

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

>From 8f61998f9a5339a9c1c04176bf3d74331532eb75 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 29 Dec 2024 20:17:46 -0800
Subject: [PATCH] [clang-format] Add VariableTemplate option

Closes #120148.
---
 clang/docs/ClangFormatStyleOptions.rst| 13 +++--
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Format/Format.h   | 15 ---
 clang/lib/Format/Format.cpp   |  1 +
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/FormatTokenLexer.cpp |  4 
 clang/lib/Format/FormatTokenLexer.h   |  3 ++-
 clang/lib/Format/TokenAnnotator.cpp   | 19 +++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 13 +
 9 files changed, 60 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..d7456fb701563d 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -6725,8 +6725,8 @@ the configuration (without a prefix: ``Auto``).
 .. _TemplateNames:
 
 **TemplateNames** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
-  A vector of non-keyword identifiers that should be interpreted as
-  template names.
+  A vector of non-keyword identifiers that should be interpreted as template
+  names.
 
   A ``<`` after a template name is annotated as a template opener instead of
   a binary operator.
@@ -6793,6 +6793,15 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+.. _VariableTemplates:
+
+**VariableTemplates** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
+  A vector of non-keyword identifiers that should be interpreted as variable
+  template names.
+
+  A ``)`` after a non-variable template instantiation may be annotated as
+  the closing parenthesis of the C-style cast operator.
+
 .. _VerilogBreakBetweenInstancePorts:
 
 **VerilogBreakBetweenInstancePorts** (``Boolean``) :versionbadge:`clang-format 
17` :ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9b0cb815a15db..f05a95e31dc255 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1118,6 +1118,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``VariableTemplates`` option.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..b245b753624980 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5038,8 +5038,8 @@ struct FormatStyle {
   /// \version 3.7
   unsigned TabWidth;
 
-  /// A vector of non-keyword identifiers that should be interpreted as
-  /// template names.
+  /// A vector of non-keyword identifiers that should be interpreted as 
template
+  /// names.
   ///
   /// A ``<`` after a template name is annotated as a template opener instead 
of
   /// a binary operator.
@@ -5099,6 +5099,15 @@ struct FormatStyle {
   /// \version 3.7
   UseTabStyle UseTab;
 
+  /// A vector of non-keyword identifiers that should be interpreted as 
variable
+  /// template names.
+  ///
+  /// A ``)`` after a non-variable template instantiation may be annotated as
+  /// the closing parenthesis of the C-style cast operator.
+  ///
+  /// \version 20
+  std::vector VariableTemplates;
+
   /// For Verilog, put each port on its own line in module instantiations.
   /// \code
   ///true:
@@ -5308,7 +5317,7 @@ struct FormatStyle {
TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
-   UseTab == R.UseTab &&
+   UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
VerilogBreakBetweenInstancePorts ==
R.VerilogBreakBetweenInstancePorts &&
WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros;
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..fe5465ce7b09de 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1164,6 +1164,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
 IO.mapOptional("UseTab", Style.UseTab);
+IO.mapOptional("VariableTemplates", Style.VariableTemplates);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
 IO.mapOptional("WhitespaceSensitiveMacros",
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f6bb860a1fea31..8917049cefb865 1

[clang] [C++20] [Modules] [Serialization] Delay marking pending incomplete decl chains until the end of `finishPendingActions`. (PR #121245)

2024-12-30 Thread Chuanqi Xu via cfe-commits

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


[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2024-12-30 Thread Owen Pan via cfe-commits

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

>From 8f61998f9a5339a9c1c04176bf3d74331532eb75 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 29 Dec 2024 20:17:46 -0800
Subject: [PATCH] [clang-format] Add VariableTemplate option

Closes #120148.
---
 clang/docs/ClangFormatStyleOptions.rst| 13 +++--
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Format/Format.h   | 15 ---
 clang/lib/Format/Format.cpp   |  1 +
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/FormatTokenLexer.cpp |  4 
 clang/lib/Format/FormatTokenLexer.h   |  3 ++-
 clang/lib/Format/TokenAnnotator.cpp   | 19 +++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 13 +
 9 files changed, 60 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..d7456fb701563d 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -6725,8 +6725,8 @@ the configuration (without a prefix: ``Auto``).
 .. _TemplateNames:
 
 **TemplateNames** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
-  A vector of non-keyword identifiers that should be interpreted as
-  template names.
+  A vector of non-keyword identifiers that should be interpreted as template
+  names.
 
   A ``<`` after a template name is annotated as a template opener instead of
   a binary operator.
@@ -6793,6 +6793,15 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+.. _VariableTemplates:
+
+**VariableTemplates** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
+  A vector of non-keyword identifiers that should be interpreted as variable
+  template names.
+
+  A ``)`` after a non-variable template instantiation may be annotated as
+  the closing parenthesis of the C-style cast operator.
+
 .. _VerilogBreakBetweenInstancePorts:
 
 **VerilogBreakBetweenInstancePorts** (``Boolean``) :versionbadge:`clang-format 
17` :ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9b0cb815a15db..f05a95e31dc255 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1118,6 +1118,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``VariableTemplates`` option.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..b245b753624980 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5038,8 +5038,8 @@ struct FormatStyle {
   /// \version 3.7
   unsigned TabWidth;
 
-  /// A vector of non-keyword identifiers that should be interpreted as
-  /// template names.
+  /// A vector of non-keyword identifiers that should be interpreted as 
template
+  /// names.
   ///
   /// A ``<`` after a template name is annotated as a template opener instead 
of
   /// a binary operator.
@@ -5099,6 +5099,15 @@ struct FormatStyle {
   /// \version 3.7
   UseTabStyle UseTab;
 
+  /// A vector of non-keyword identifiers that should be interpreted as 
variable
+  /// template names.
+  ///
+  /// A ``)`` after a non-variable template instantiation may be annotated as
+  /// the closing parenthesis of the C-style cast operator.
+  ///
+  /// \version 20
+  std::vector VariableTemplates;
+
   /// For Verilog, put each port on its own line in module instantiations.
   /// \code
   ///true:
@@ -5308,7 +5317,7 @@ struct FormatStyle {
TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
-   UseTab == R.UseTab &&
+   UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
VerilogBreakBetweenInstancePorts ==
R.VerilogBreakBetweenInstancePorts &&
WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros;
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..fe5465ce7b09de 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1164,6 +1164,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
 IO.mapOptional("UseTab", Style.UseTab);
+IO.mapOptional("VariableTemplates", Style.VariableTemplates);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
 IO.mapOptional("WhitespaceSensitiveMacros",
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f6bb860a1fea31..8917049cefb865 1

[clang-tools-extra] fe1f64e - [clangd] Make EnableFunctionArgSnippets option string-typed (#121178)

2024-12-30 Thread via cfe-commits

Author: Nathan Ridge
Date: 2024-12-30T20:49:26-05:00
New Revision: fe1f64e7e935c9905a115842183ea29dd1312dfe

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

LOG: [clangd] Make EnableFunctionArgSnippets option string-typed (#121178)

Fixes https://github.com/clangd/clangd/issues/2232

Added: 


Modified: 
clang-tools-extra/clangd/tool/ClangdMain.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp 
b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index 80a0653f8f7404..714891703b6f31 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -242,13 +242,13 @@ opt FallbackStyle{
 init(clang::format::DefaultFallbackStyle),
 };
 
-opt EnableFunctionArgSnippets{
+opt EnableFunctionArgSnippets{
 "function-arg-placeholders",
 cat(Features),
 desc("When disabled (0), completions contain only parentheses for "
  "function calls. When enabled (1), completions also contain "
  "placeholders for method parameters"),
-init(-1),
+init("-1"),
 };
 
 opt HeaderInsertion{
@@ -636,6 +636,22 @@ loadExternalIndex(const Config::ExternalIndexSpec 
&External,
   llvm_unreachable("Invalid ExternalIndexKind.");
 }
 
+std::optional shouldEnableFunctionArgSnippets() {
+  std::string Val = EnableFunctionArgSnippets;
+  // Accept the same values that a bool option parser would, but also accept
+  // -1 to indicate "unspecified", in which case the ArgumentListsPolicy
+  // config option will be respected.
+  if (Val == "1" || Val == "true" || Val == "True" || Val == "TRUE")
+return true;
+  if (Val == "0" || Val == "false" || Val == "False" || Val == "FALSE")
+return false;
+  if (Val != "-1")
+elog("Value specified by --function-arg-placeholders is invalid. Provide a 
"
+ "boolean value or leave unspecified to use ArgumentListsPolicy from "
+ "config instead.");
+  return std::nullopt;
+}
+
 class FlagsConfigProvider : public config::Provider {
 private:
   config::CompiledFragment Frag;
@@ -696,10 +712,9 @@ class FlagsConfigProvider : public config::Provider {
   BGPolicy = Config::BackgroundPolicy::Skip;
 }
 
-if (EnableFunctionArgSnippets >= 0) {
-  ArgumentLists = EnableFunctionArgSnippets
-  ? Config::ArgumentListsPolicy::FullPlaceholders
-  : Config::ArgumentListsPolicy::Delimiters;
+if (std::optional Enable = shouldEnableFunctionArgSnippets()) {
+  ArgumentLists = *Enable ? Config::ArgumentListsPolicy::FullPlaceholders
+  : Config::ArgumentListsPolicy::Delimiters;
 }
 
 Frag = [=](const config::Params &, Config &C) {



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


[clang-tools-extra] [clangd] Make EnableFunctionArgSnippets option string-typed (PR #121178)

2024-12-30 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> I think we need to add the new `ArgumentLists` config in the clangd config 
> doc https://clangd.llvm.org/config#completion.

Definitely. I'll send out a patch documenting this and other options new in 
clangd 20 in the near future. (We have an entry about this on the [Release 
checklist](https://github.com/clangd/clangd/wiki/Release-checklist) now, so we 
don't forget.)

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


[clang-tools-extra] [clangd] Make EnableFunctionArgSnippets option string-typed (PR #121178)

2024-12-30 Thread Nathan Ridge via cfe-commits

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits


@@ -2720,6 +2720,22 @@ TEST_F(ConstantRangeTest, binaryAnd) {
   EXPECT_EQ(R16_32.binaryAnd(R0_99), R0_32);
   EXPECT_EQ(R0_99.binaryAnd(R16_32), R0_32);
 
+  // 'And' with leading bits are masked (with common leading bits stripped)
+  ConstantRange RMaskedL(APInt(8, 0b10'00101'1), APInt(8, 0b10'1'0 + 1));
+  ConstantRange RMaskedR(APInt(8, 0b10'1'0), APInt(8, 0b10'1'1 + 1));
+  EXPECT_EQ(RMaskedL.binaryAnd(RMaskedR).getLower(), APInt(8, 0b10'00101'0));
+  EXPECT_EQ(RMaskedR.binaryAnd(RMaskedL).getLower(), APInt(8, 0b10'00101'0));
+
+  ConstantRange RMaskedL1(APInt(8, 0b00'011'010), APInt(8, 0b00'100'100 + 1));
+  ConstantRange RMaskedR1(APInt(8, 0b00'111'010), APInt(8, 0b00'111'110 + 1));
+  EXPECT_EQ(RMaskedL1.binaryAnd(RMaskedR1).getLower(), APInt(8, 0b00'011'000));
+  EXPECT_EQ(RMaskedR1.binaryAnd(RMaskedL1).getLower(), APInt(8, 0b00'011'000));
+
+  ConstantRange RMaskedL2(APInt(8, 0b'0111u), APInt(8, 0b'1101u + 1u));
+  ConstantRange RMaskedR2(APInt(8, 0xff), APInt(8, 0));
+  EXPECT_EQ(RMaskedL2.binaryAnd(RMaskedR2), RMaskedL2);
+  EXPECT_EQ(RMaskedR2.binaryAnd(RMaskedL2), RMaskedL2);

zsrkmyn wrote:

So, should I `EXPECT_GE(lower, 0)` or `EXPECT_EQ(lower, 0)`? I prefer the 
former, because tests won't fail if the algorithm is further optimized.

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


[clang] [Clang][C++23] Core language changes from P1467R9 extended floating-point types and standard names. (PR #78503)

2024-12-30 Thread M. Zeeshan Siddiqui via cfe-commits

https://github.com/codemzs updated 
https://github.com/llvm/llvm-project/pull/78503

>From c6b9ceaff9551e931ee3284d9e855d8df07a41bb Mon Sep 17 00:00:00 2001
From: "M. Zeeshan Siddiqui" 
Date: Mon, 13 Nov 2023 17:37:36 +
Subject: [PATCH] [Clang][C++23] Implement core language changes from P1467R9
 extended floating-point types and standard names.

This commit implements Core language changes based on P1467R9 Extended
floating-point types and standard names.

As per the proposal's definition the following two types are marked as
extended floating point: Float16 (aka _Float16) and
Bfloat16 (aka decltype (0.0bf16) or __bf16). Future work can extend this
to support other floating-point types such as Float32, Float64, and
Float128.

RFC: 
https://discourse.llvm.org/t/rfc-c-23-p1467r9-extended-floating-point-types-and-standard-names/70033

Differential Revision: https://reviews.llvm.org/D149573
---
 clang/docs/ReleaseNotes.rst   |   5 +
 clang/include/clang/AST/ASTContext.h  |  54 +-
 clang/include/clang/AST/BuiltinTypes.def  |   4 +-
 clang/include/clang/AST/Type.h|   7 +
 .../clang/Basic/DiagnosticSemaKinds.td|   2 +
 clang/include/clang/Lex/LiteralSupport.h  |   1 +
 .../Core/PathSensitive/SMTConv.h  |  19 +-
 clang/lib/AST/ASTContext.cpp  | 147 -
 clang/lib/AST/StmtPrinter.cpp |   1 +
 clang/lib/AST/Type.cpp|  27 +
 clang/lib/Frontend/InitPreprocessor.cpp   |   6 +-
 clang/lib/Lex/LiteralSupport.cpp  |  17 +
 clang/lib/Sema/Sema.cpp   |  16 +
 clang/lib/Sema/SemaCast.cpp   |  13 +
 clang/lib/Sema/SemaChecking.cpp   |  23 +-
 clang/lib/Sema/SemaExpr.cpp   |  60 ++-
 clang/lib/Sema/SemaOverload.cpp   |  80 ++-
 .../cxx23-fp-ext-std-names-p1467r9.cpp| 499 +
 .../test/CodeGenCXX/cxx23-vector-bfloat16.cpp |  67 +++
 .../Sema/cxx23-fp-ext-std-names-p1467r9.cpp   | 505 ++
 20 files changed, 1507 insertions(+), 46 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/cxx23-fp-ext-std-names-p1467r9.cpp
 create mode 100644 clang/test/CodeGenCXX/cxx23-vector-bfloat16.cpp
 create mode 100644 clang/test/Sema/cxx23-fp-ext-std-names-p1467r9.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b7da12bcf65818..f5b10d1bc776ad 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -248,6 +248,11 @@ C++ Language Changes
 - The builtin type alias ``__builtin_common_type`` has been added to improve 
the
   performance of ``std::common_type``.
 
+- Implemented `P1467R9: Extended floating-point types and standard names 
`_. Enables
+  extended floating-point types beyond the three standard ones, establishing 
rules for their interactions and
+  conversions with each other and other types, while ensuring no alteration in 
the behavior of existing
+  standard types. The current implementation enables support for 
`std::float16_t` and `std::bfloat16_t` types.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 1e89a6805ce9c6..440848bb44e0cd 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -55,6 +55,16 @@ template  class SmallPtrSet;
 
 namespace clang {
 
+// Conversion ranks introduced in C++23 6.8.6p2 [conv.rank]
+enum FloatConvRankCompareResult {
+  FRCR_Unordered,
+  FRCR_Lesser,
+  FRCR_Greater,
+  FRCR_Equal,
+  FRCR_Equal_Lesser_Subrank,
+  FRCR_Equal_Greater_Subrank,
+};
+
 class APValue;
 class ASTMutationListener;
 class ASTRecordLayout;
@@ -1182,8 +1192,8 @@ class ASTContext : public RefCountedBase {
   CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
   SatUnsignedLongFractTy;
   CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
-  CanQualType BFloat16Ty;
-  CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
+  CanQualType BFloat16Ty; // [C++23 6.8.3p5][basic.extended.fp]
+  CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3 and [C++23 
6.8.3p1][basic.extended.fp]
   CanQualType VoidPtrTy, NullPtrTy;
   CanQualType DependentTy, OverloadTy, BoundMemberTy, UnresolvedTemplateTy,
   UnknownAnyTy;
@@ -2563,6 +2573,9 @@ class ASTContext : public RefCountedBase {
   /// More type predicates useful for type checking/promotion
   bool isPromotableIntegerType(QualType T) const; // C99 6.3.1.1p2
 
+  /// Determine if a floating type can be promoted to another floating type.
+  bool isPromotableFloatingType(QualType T) const;
+
   /// Return the "preferred" alignment of the specified type \p T for
   /// the current target, in bits.
   ///
@@ -2970,6 +2983,9 @@ class ASTContext : public RefCountedBase {
   /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
   QualType getPromotedIntegerType(QualType Pr

[clang] Add an off-by-default warning to complain about MSVC bitfield padding (PR #117428)

2024-12-30 Thread Oliver Hunt via cfe-commits

https://github.com/ojhunt updated 
https://github.com/llvm/llvm-project/pull/117428

>From 3e25d7ef2e223942298078dace8979905956d05c Mon Sep 17 00:00:00 2001
From: Oliver Hunt 
Date: Fri, 22 Nov 2024 17:53:24 +0100
Subject: [PATCH 1/7] Add an off-by-default warning to complain about MSVC
 bitfield padding

---
 clang/include/clang/Basic/DiagnosticGroups.td |   1 +
 .../clang/Basic/DiagnosticSemaKinds.td|   6 +
 clang/lib/Sema/SemaDecl.cpp   |  27 ++-
 .../SemaCXX/ms_struct-bitfield-padding.cpp| 180 ++
 4 files changed, 212 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaCXX/ms_struct-bitfield-padding.cpp

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index df9bf94b5d0398..57bdda4b8f8b47 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -631,6 +631,7 @@ def Packed : DiagGroup<"packed", [PackedNonPod]>;
 def PaddedBitField : DiagGroup<"padded-bitfield">;
 def Padded : DiagGroup<"padded", [PaddedBitField]>;
 def UnalignedAccess : DiagGroup<"unaligned-access">;
+def MSBitfieldCompatibility : DiagGroup<"ms-bitfield-packing-compatibility">;
 
 def PessimizingMove : DiagGroup<"pessimizing-move">;
 def ReturnStdMove : DiagGroup<"return-std-move">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index eb05a6a77978af..aa13e3438d3739 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6418,6 +6418,12 @@ def warn_signed_bitfield_enum_conversion : Warning<
   InGroup, DefaultIgnore;
 def note_change_bitfield_sign : Note<
   "consider making the bitfield type %select{unsigned|signed}0">;
+def warn_ms_bitfield_mismatched_storage_packing : Warning<
+  "bit-field %0 of type %1 has a different storage size (%2 vs %3 bytes) than 
the "
+  "preceding bit-field and may not be packed under MSVC ABI">,
+  InGroup, DefaultIgnore;
+def note_ms_bitfield_mismatched_storage_size_previous : Note<
+  "preceding bit-field %0 declared here with type %1">;
 
 def warn_missing_braces : Warning<
   "suggest braces around initialization of subobject">,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 74b0e5ad23bd48..18aeca3b34f659 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19001,9 +19001,9 @@ void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, 
Decl *EnclosingDecl,
 
   // Verify that all the fields are okay.
   SmallVector RecFields;
-
+  std::optional PreviousField;
   for (ArrayRef::iterator i = Fields.begin(), end = Fields.end();
-   i != end; ++i) {
+   i != end; PreviousField = cast(*i), ++i) {
 FieldDecl *FD = cast(*i);
 
 // Get the type for the field.
@@ -19213,6 +19213,29 @@ void Sema::ActOnFields(Scope *S, SourceLocation 
RecLoc, Decl *EnclosingDecl,
 
 if (Record && FD->getType().isVolatileQualified())
   Record->setHasVolatileMember(true);
+auto IsNonDependentBitField = [](const FieldDecl *FD) {
+  if (!FD->isBitField())
+return false;
+  if (FD->getType()->isDependentType())
+return false;
+  return true;
+};
+
+if (Record && PreviousField && IsNonDependentBitField(FD) &&
+IsNonDependentBitField(*PreviousField)) {
+  unsigned FDStorageSize =
+  Context.getTypeSizeInChars(FD->getType()).getQuantity();
+  unsigned PreviousFieldStorageSize =
+  
Context.getTypeSizeInChars((*PreviousField)->getType()).getQuantity();
+  if (FDStorageSize != PreviousFieldStorageSize) {
+Diag(FD->getLocation(),
+ diag::warn_ms_bitfield_mismatched_storage_packing)
+<< FD << FD->getType() << FDStorageSize << 
PreviousFieldStorageSize;
+Diag((*PreviousField)->getLocation(),
+ diag::note_ms_bitfield_mismatched_storage_size_previous)
+<< *PreviousField << (*PreviousField)->getType();
+  }
+}
 // Keep track of the number of named members.
 if (FD->getIdentifier())
   ++NumNamedMembers;
diff --git a/clang/test/SemaCXX/ms_struct-bitfield-padding.cpp 
b/clang/test/SemaCXX/ms_struct-bitfield-padding.cpp
new file mode 100644
index 00..001086de5bbd10
--- /dev/null
+++ b/clang/test/SemaCXX/ms_struct-bitfield-padding.cpp
@@ -0,0 +1,180 @@
+
+// RUN: %clang_cc1 -fsyntax-only -Wms-bitfield-packing-compatibility -verify 
-triple armv8 -std=c++23 %s
+// RUN: %clang_cc1 -fsyntax-only -DMS_BITFIELDS -mms-bitfields 
-verify=msbitfields -triple armv8-apple-macos10.15 -std=c++23 %s
+
+// msbitfields-no-diagnostics
+
+enum Enum1 { Enum1_A, Enum1_B };
+enum Enum2 { Enum2_A, Enum2_B };
+
+enum class EnumU32_1 : unsigned { A, B };
+enum class EnumU32_2 : unsigned { A, B };
+enum class EnumU64 : unsigned long long { A, B };
+enum class EnumI32 : int { A, B };
+enum class EnumU8 : unsigned char { A, B };

[clang] [Clang][Sema] Expose static inline functions from GMF (PR #104701)

2024-12-30 Thread LLVM Continuous Integration via cfe-commits
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= 
Message-ID:
In-Reply-To: 


llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`sanitizer-aarch64-linux-bootstrap-msan` running on `sanitizer-buildbot9` while 
building `clang` at step 2 "annotate".

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


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

```
Step 2 (annotate) failure: 'python 
../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py'
 (failure)
...
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using lld-link: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/lld-link
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld64.lld: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/ld64.lld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using wasm-ld: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/wasm-ld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld.lld: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/ld.lld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using lld-link: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/lld-link
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld64.lld: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/ld64.lld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using wasm-ld: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/wasm-ld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/utils/lit/lit/main.py:72:
 note: The test suite configuration requested an individual test timeout of 0 
seconds but a timeout of 900 seconds was requested on the command line. Forcing 
timeout to be 900 seconds.
-- Testing: 85660 tests, 72 workers --
Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90.
FAIL: lld :: ELF/icf-comdat.s (83938 of 85660)
 TEST 'lld :: ELF/icf-comdat.s' FAILED 
Exit Code: 1

Command Output (stderr):
--
RUN: at line 3: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/llvm-mc
 -filetype=obj -triple=x86_64-unknown-linux 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/lld/test/ELF/icf-comdat.s
 -o 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/tools/lld/test/ELF/Output/icf-comdat.s.tmp
+ 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/llvm-mc
 -filetype=obj -triple=x86_64-unknown-linux 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/lld/test/ELF/icf-comdat.s
 -o 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/tools/lld/test/ELF/Output/icf-comdat.s.tmp
RUN: at line 4: 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/ld.lld 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/tools/lld/test/ELF/Output/icf-comdat.s.tmp
 -o /dev/null --icf=all --print-icf-sections | 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/FileCheck
 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/lld/test/ELF/icf-comdat.s
+ 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/ld.lld 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/tools/lld/test/ELF/Output/icf-comdat.s.tmp
 -o /dev/null --icf=all --print-icf-sections
+ 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm_build_msan/bin/FileCheck
 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/lld/test/ELF/icf-comdat.s
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and 
include the crash backtrace.
 #0 0xacaf403e5a00 ___interceptor_backtrace 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/compiler-rt/lib/msan/../sanitizer_common/sanitizer_common_interceptors.inc:4497:13
 #1 0xacaf405d2220 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/lib/Support/Unix/Signals.inc:727:7
 #2 0xacaf405ccc20 llvm::sys::RunSignalHandlers() 
/home/b/sanitizer-aarch64-linux-bootstrap-msan/build/llvm-project/llvm/lib/Support/Signals.cpp:106:18
 #3 0xacaf405d332c SignalHandler(int) 
/home/b/sanitizer-aarch64-l

[clang] [clang][analyzer] Stabilize path-constraint order by using alloc IDs (PR #121347)

2024-12-30 Thread Arseniy Zaostrovnykh via cfe-commits

necto wrote:

Hey, @steakhal, @NagyDonat 
I am working caching Z3 refutation query outcomes to reduce the number of flaky 
issues, and constraint order is important to maximize the cache-hit rate. Turns 
out, global constraint order is beneficial regardless query cache. Would you 
take a look?

BTW, a couple of points on the design of the change:
- I considered using simple incremental ids instead of allocator offsets, but 
found no advantage. Do you see any?
- Would it make sense to unify `SymbolData::Sym` and `SymExpr::AllocID`, and 
maybe get rid of the intermediary `SymbolData`?


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


[clang] [clang] Return larger CXX records in memory (PR #120670)

2024-12-30 Thread Pranav Kant via cfe-commits

https://github.com/pranavk updated 
https://github.com/llvm/llvm-project/pull/120670

>From 4b6839317bcd2a014011cb91b5a3e58d4a47b0b1 Mon Sep 17 00:00:00 2001
From: Pranav Kant 
Date: Fri, 20 Dec 2024 02:17:23 +
Subject: [PATCH 1/2] [clang] Return larger CXX records in memory

We incorrectly return CXX records in AVX registers when they should be
returned in memory. This is violation of x86-64 psABI.

Detailed discussion is here: 
https://groups.google.com/g/x86-64-abi/c/BjOOyihHuqg/m/KurXdUcWAgAJ
---
 clang/include/clang/Basic/LangOptions.h |  1 +
 clang/lib/CodeGen/Targets/X86.cpp   | 18 ++
 2 files changed, 19 insertions(+)

diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 949c8f5d448bcf..0dd644eba559b9 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -245,6 +245,7 @@ class LangOptionsBase {
 ///   construction vtable because it hasn't added 'type' as a substitution.
 ///   - Skip mangling enclosing class templates of member-like friend
 ///   function templates.
+///   - Incorrectly return C++ records in AVX registers.
 Ver19,
 
 /// Conform to the underlying platform's C and C++ ABIs as closely
diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 7f73bf2a65266e..70d812057d0b01 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -1334,6 +1334,20 @@ class X86_64ABIInfo : public ABIInfo {
 return T.isOSLinux() || T.isOSNetBSD();
   }
 
+  bool returnCXXRecordGreaterThan128InMem(unsigned Size, unsigned TypeSize,
+  unsigned NativeSize) const {
+// Clang <= 19.0 did not do this.
+if (getContext().getLangOpts().getClangABICompat() <=
+LangOptions::ClangABI::Ver19)
+  return false;
+
+// The only case a 256(or 512)-bit wide vector could be used to return
+// is when CXX record contains a single 256(or 512)-bit element.
+if (Size > 128 && (Size != TypeSize || Size > NativeSize))
+  return true;
+return false;
+  }
+
   X86AVXABILevel AVXLevel;
   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
   // 64-bit hardware.
@@ -2067,6 +2081,10 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t 
OffsetBase, Class &Lo,
 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
 Lo = merge(Lo, FieldLo);
 Hi = merge(Hi, FieldHi);
+if (returnCXXRecordGreaterThan128InMem(
+Size, getContext().getTypeSize(I.getType()),
+getNativeVectorSizeForAVXABI(AVXLevel)))
+  Lo = Memory;
 if (Lo == Memory || Hi == Memory) {
   postMerge(Size, Lo, Hi);
   return;

>From 6e62d019db05601bb6d4046785b9a219f92cebe8 Mon Sep 17 00:00:00 2001
From: Pranav Kant 
Date: Mon, 30 Dec 2024 14:57:31 +
Subject: [PATCH 2/2] add a regression test

---
 clang/test/CodeGen/X86/avx-cxx-record.cpp | 23 +++
 1 file changed, 23 insertions(+)
 create mode 100644 clang/test/CodeGen/X86/avx-cxx-record.cpp

diff --git a/clang/test/CodeGen/X86/avx-cxx-record.cpp 
b/clang/test/CodeGen/X86/avx-cxx-record.cpp
new file mode 100644
index 00..0d5f070b7754fb
--- /dev/null
+++ b/clang/test/CodeGen/X86/avx-cxx-record.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang %s -c -S -emit-llvm -O2 -march=x86-64-v3 -o - | FileCheck %s
+
+using UInt64x2 = unsigned long long __attribute__((__vector_size__(16), 
may_alias));
+
+template
+struct XMM1 {
+UInt64x2 x;
+};
+
+struct XMM2 : XMM1<0>, XMM1<1> {
+};
+
+// CHECK: define{{.*}} @_Z3foov({{.*}} [[ARG:%.*]]){{.*}}
+// CHECK-NEXT: entry:
+// CHECK-NEXT: store {{.*}}, ptr [[ARG]]{{.*}}
+// CHECK-NEXT: [[TMP1:%.*]] = getelementptr {{.*}}, ptr [[ARG]]{{.*}}
+// CHECK-NEXT: store {{.*}}, ptr [[TMP1]]{{.*}}
+XMM2 foo() {
+  XMM2 result;
+  ((XMM1<0>*)&result)->x = UInt64x2{1, 2};
+  ((XMM1<1>*)&result)->x = UInt64x2{3, 4};
+  return result;
+}

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


[clang] Propagate lifetimebound from formal parameters to those in the canonical declaration and use that for analysis (PR #107627)

2024-12-30 Thread via cfe-commits

https://github.com/higher-performance updated 
https://github.com/llvm/llvm-project/pull/107627

>From 4dfad6c21220585a6a0f796f5699128ca7c4615b Mon Sep 17 00:00:00 2001
From: higher-performance 
Date: Fri, 6 Sep 2024 14:16:15 -0400
Subject: [PATCH 1/3] Propagate lifetimebound from formal parameters to those
 in the canonical declaration, then use the canonical declaration for analysis

Note that this doesn't handle the implicit 'this' parameter; that can be 
addressed in a separate commit.
---
 clang/lib/Sema/CheckExprLifetime.cpp  | 20 ++---
 clang/lib/Sema/SemaAttr.cpp   | 34 +++
 clang/test/SemaCXX/attr-lifetimebound.cpp |  5 
 3 files changed, 37 insertions(+), 22 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 7109de03cadd12..4befd703beb422 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -645,9 +645,9 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 }
   }
 
-  for (unsigned I = 0,
-N = std::min(Callee->getNumParams(), Args.size());
-   I != N; ++I) {
+  const FunctionDecl *CanonCallee = Callee->getCanonicalDecl();
+  unsigned NP = std::min(Callee->getNumParams(), CanonCallee->getNumParams());
+  for (unsigned I = 0, N = std::min(NP, Args.size()); I != N; ++I) {
 Expr *Arg = Args[I];
 RevertToOldSizeRAII RAII(Path);
 if (auto *DAE = dyn_cast(Arg)) {
@@ -655,11 +655,11 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   {IndirectLocalPathEntry::DefaultArg, DAE, DAE->getParam()});
   Arg = DAE->getExpr();
 }
-if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr())
-  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+if (CheckCoroCall || 
CanonCallee->getParamDecl(I)->hasAttr())
+  VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
 else if (const auto *CaptureAttr =
- Callee->getParamDecl(I)->getAttr();
- CaptureAttr && isa(Callee) &&
+ 
CanonCallee->getParamDecl(I)->getAttr();
+ CaptureAttr && isa(CanonCallee) &&
  llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
return ArgIdx == LifetimeCaptureByAttr::THIS;
  }))
@@ -676,11 +676,11 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   // `lifetimebound` and shares the same code path. This implies the 
emitted
   // diagnostics will be emitted under `-Wdangling`, not
   // `-Wdangling-capture`.
-  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+  VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
 else if (EnableGSLAnalysis && I == 0) {
   // Perform GSL analysis for the first argument
-  if (shouldTrackFirstArgument(Callee)) {
-VisitGSLPointerArg(Callee, Arg);
+  if (shouldTrackFirstArgument(CanonCallee)) {
+VisitGSLPointerArg(CanonCallee, Arg);
   } else if (auto *Ctor = dyn_cast(Call);
  Ctor && shouldTrackFirstArgumentForConstructor(Ctor)) {
 VisitGSLPointerArg(Ctor->getConstructor(), Arg);
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index 44485e71d57a01..3fd122b20d7b12 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -217,7 +217,8 @@ void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl 
*Record) {
 }
 
 void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
-  if (FD->getNumParams() == 0)
+  unsigned NumParams = FD->getNumParams();
+  if (NumParams == 0)
 return;
 
   if (unsigned BuiltinID = FD->getBuiltinID()) {
@@ -239,18 +240,13 @@ void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
 default:
   break;
 }
-return;
-  }
-  if (auto *CMD = dyn_cast(FD)) {
-const auto *CRD = CMD->getParent();
-if (!CRD->isInStdNamespace() || !CRD->getIdentifier())
-  return;
-
-if (isa(CMD)) {
+  } else if (auto *CMD = dyn_cast(FD)) {
+const CXXRecordDecl *CRD = CMD->getParent();
+if (CRD->isInStdNamespace() && CRD->getIdentifier() &&
+isa(CMD)) {
   auto *Param = CMD->getParamDecl(0);
-  if (Param->hasAttr())
-return;
-  if (CRD->getName() == "basic_string_view" &&
+  if (!Param->hasAttr() &&
+  CRD->getName() == "basic_string_view" &&
   Param->getType()->isPointerType()) {
 // construct from a char array pointed by a pointer.
 //   basic_string_view(const CharT* s);
@@ -266,6 +262,20 @@ void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
   LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
   }
 }
+  } else if (auto *CanonDecl = FD->getCanonicalDecl(); FD != CanonDecl) {
+// Propagate the lifetimebound attribute from parameters to the canonical
+// declaration.
+// Note that this doesn't include the implicit 'this' p

[clang] Propagate lifetimebound from formal parameters to those in the canonical declaration and use that for analysis (PR #107627)

2024-12-30 Thread via cfe-commits

https://github.com/higher-performance updated 
https://github.com/llvm/llvm-project/pull/107627

>From 4dfad6c21220585a6a0f796f5699128ca7c4615b Mon Sep 17 00:00:00 2001
From: higher-performance 
Date: Fri, 6 Sep 2024 14:16:15 -0400
Subject: [PATCH 1/3] Propagate lifetimebound from formal parameters to those
 in the canonical declaration, then use the canonical declaration for analysis

Note that this doesn't handle the implicit 'this' parameter; that can be 
addressed in a separate commit.
---
 clang/lib/Sema/CheckExprLifetime.cpp  | 20 ++---
 clang/lib/Sema/SemaAttr.cpp   | 34 +++
 clang/test/SemaCXX/attr-lifetimebound.cpp |  5 
 3 files changed, 37 insertions(+), 22 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 7109de03cadd12..4befd703beb422 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -645,9 +645,9 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 }
   }
 
-  for (unsigned I = 0,
-N = std::min(Callee->getNumParams(), Args.size());
-   I != N; ++I) {
+  const FunctionDecl *CanonCallee = Callee->getCanonicalDecl();
+  unsigned NP = std::min(Callee->getNumParams(), CanonCallee->getNumParams());
+  for (unsigned I = 0, N = std::min(NP, Args.size()); I != N; ++I) {
 Expr *Arg = Args[I];
 RevertToOldSizeRAII RAII(Path);
 if (auto *DAE = dyn_cast(Arg)) {
@@ -655,11 +655,11 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   {IndirectLocalPathEntry::DefaultArg, DAE, DAE->getParam()});
   Arg = DAE->getExpr();
 }
-if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr())
-  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+if (CheckCoroCall || 
CanonCallee->getParamDecl(I)->hasAttr())
+  VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
 else if (const auto *CaptureAttr =
- Callee->getParamDecl(I)->getAttr();
- CaptureAttr && isa(Callee) &&
+ 
CanonCallee->getParamDecl(I)->getAttr();
+ CaptureAttr && isa(CanonCallee) &&
  llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
return ArgIdx == LifetimeCaptureByAttr::THIS;
  }))
@@ -676,11 +676,11 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   // `lifetimebound` and shares the same code path. This implies the 
emitted
   // diagnostics will be emitted under `-Wdangling`, not
   // `-Wdangling-capture`.
-  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+  VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
 else if (EnableGSLAnalysis && I == 0) {
   // Perform GSL analysis for the first argument
-  if (shouldTrackFirstArgument(Callee)) {
-VisitGSLPointerArg(Callee, Arg);
+  if (shouldTrackFirstArgument(CanonCallee)) {
+VisitGSLPointerArg(CanonCallee, Arg);
   } else if (auto *Ctor = dyn_cast(Call);
  Ctor && shouldTrackFirstArgumentForConstructor(Ctor)) {
 VisitGSLPointerArg(Ctor->getConstructor(), Arg);
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index 44485e71d57a01..3fd122b20d7b12 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -217,7 +217,8 @@ void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl 
*Record) {
 }
 
 void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
-  if (FD->getNumParams() == 0)
+  unsigned NumParams = FD->getNumParams();
+  if (NumParams == 0)
 return;
 
   if (unsigned BuiltinID = FD->getBuiltinID()) {
@@ -239,18 +240,13 @@ void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
 default:
   break;
 }
-return;
-  }
-  if (auto *CMD = dyn_cast(FD)) {
-const auto *CRD = CMD->getParent();
-if (!CRD->isInStdNamespace() || !CRD->getIdentifier())
-  return;
-
-if (isa(CMD)) {
+  } else if (auto *CMD = dyn_cast(FD)) {
+const CXXRecordDecl *CRD = CMD->getParent();
+if (CRD->isInStdNamespace() && CRD->getIdentifier() &&
+isa(CMD)) {
   auto *Param = CMD->getParamDecl(0);
-  if (Param->hasAttr())
-return;
-  if (CRD->getName() == "basic_string_view" &&
+  if (!Param->hasAttr() &&
+  CRD->getName() == "basic_string_view" &&
   Param->getType()->isPointerType()) {
 // construct from a char array pointed by a pointer.
 //   basic_string_view(const CharT* s);
@@ -266,6 +262,20 @@ void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
   LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
   }
 }
+  } else if (auto *CanonDecl = FD->getCanonicalDecl(); FD != CanonDecl) {
+// Propagate the lifetimebound attribute from parameters to the canonical
+// declaration.
+// Note that this doesn't include the implicit 'this' p

[clang] Propagate lifetimebound from formal parameters to those in the canonical declaration and use that for analysis (PR #107627)

2024-12-30 Thread via cfe-commits

higher-performance wrote:

Okay, I believe this PR is ready. Could we merge it?

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


[clang] Introduce virtual interface for lattices and remove dependency on `llvm::Any`. (PR #120967)

2024-12-30 Thread Yitzhak Mandelbaum via cfe-commits

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

>From db206514c03a58065e24afccd55886a012b2abcc Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Mon, 23 Dec 2024 13:42:21 +
Subject: [PATCH] Introduce virtual interface for lattices and remove
 dependency on `llvm::Any`.

This PR has 2 related goals:

*Remove dependency on `llvm::Any`*. For some platforms, use of `llvm::Any`
forces users to explicitly define internal details related to `Any`. Aside from
aesthetics, this places an obscure requirement on lattice implementers. We
prefer to use LLVM's (explicit) RTTI framework instead.

*Introduce virtual interface for lattices*. Currently, we implicitly define the
interface for lattices, because the interface to analyses is fully captured in
templates. This PR moves to an explicit, virtual interface.

We combine these two changes in a single PR because they are closely related: we
use the new lattice interface as the basis of an open type hierarchy that embeds
RTTI for safe interfacing with the dataflow engine.

As a side-effect, we are able to greatly simplify the interface of
`DataflowAnalysis` and collapse the distinction between it and
`TypeErasedDataflowAnalysis`.
---
 .../CachedConstAccessorsLattice.h |  29 +++-
 .../Analysis/FlowSensitive/DataflowAnalysis.h | 147 +-
 .../Analysis/FlowSensitive/DataflowLattice.h  |  46 ++
 .../clang/Analysis/FlowSensitive/Logger.h |   5 +-
 .../clang/Analysis/FlowSensitive/MapLattice.h |  26 +++-
 .../Models/UncheckedOptionalAccessModel.h |  19 ++-
 .../Analysis/FlowSensitive/NoopAnalysis.h |  20 +--
 .../Analysis/FlowSensitive/NoopLattice.h  |  30 ++--
 .../TypeErasedDataflowAnalysis.h  |  83 --
 clang/lib/Analysis/FlowSensitive/Arena.cpp|   4 +-
 .../lib/Analysis/FlowSensitive/HTMLLogger.cpp |   3 +-
 clang/lib/Analysis/FlowSensitive/Logger.cpp   |   4 +-
 .../Models/UncheckedOptionalAccessModel.cpp   |   9 +-
 clang/lib/Analysis/FlowSensitive/Transfer.cpp |   1 +
 .../TypeErasedDataflowAnalysis.cpp|  71 -
 .../FlowSensitive/ChromiumCheckModelTest.cpp  |  15 +-
 .../Analysis/FlowSensitive/LoggerTest.cpp |  50 --
 .../Analysis/FlowSensitive/MapLatticeTest.cpp |  40 +++--
 .../MultiVarConstantPropagationTest.cpp   |  56 ---
 .../FlowSensitive/SignAnalysisTest.cpp|  17 +-
 .../SingleVarConstantPropagationTest.cpp  |  52 ---
 .../Analysis/FlowSensitive/TestingSupport.h   |  10 +-
 .../FlowSensitive/TransferBranchTest.cpp  |  34 ++--
 .../TypeErasedDataflowAnalysisTest.cpp| 117 +-
 24 files changed, 451 insertions(+), 437 deletions(-)

diff --git 
a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
index 48c5287367739a..07478d40a42345 100644
--- a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
@@ -20,6 +20,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
+#include "llvm/Support/ExtensibleRTTI.h"
 
 namespace clang {
 namespace dataflow {
@@ -45,9 +46,15 @@ namespace dataflow {
 /// use(s.getFoo().value()); // unsafe (invalidate cache for s)
 ///   }
 /// }
-template  class CachedConstAccessorsLattice : public Base {
+template 
+class CachedConstAccessorsLattice
+: public llvm::RTTIExtends, Base> {
 public:
-  using Base::Base; // inherit all constructors
+  using Parent = llvm::RTTIExtends;
+  using Parent::Parent; // inherit all constructors
+
+  /// For RTTI.
+  inline static char ID = 0;
 
   /// Creates or returns a previously created `Value` associated with a const
   /// method call `obj.getFoo()` where `RecordLoc` is the
@@ -88,7 +95,16 @@ template  class CachedConstAccessorsLattice : 
public Base {
 return Base::operator==(Other);
   }
 
-  LatticeJoinEffect join(const CachedConstAccessorsLattice &Other);
+  std::unique_ptr clone() override {
+return std::make_unique(*this);
+  }
+
+  bool isEqual(const DataflowLattice &Other) const override {
+return llvm::isa(Other) &&
+   *this == llvm::cast(Other);
+  }
+
+  LatticeEffect join(const DataflowLattice &Other) override;
 
 private:
   // Maps a record storage location and const method to the value to return
@@ -145,10 +161,11 @@ joinConstMethodMap(
 } // namespace internal
 
 template 
-LatticeEffect CachedConstAccessorsLattice::join(
-const CachedConstAccessorsLattice &Other) {
+LatticeEffect
+CachedConstAccessorsLattice::join(const DataflowLattice &L) {
+  LatticeEffect Effect = Base::join(L);
 
-  LatticeEffect Effect = Base::join(Other);
+  const auto &Other = llvm::cast>(L);
 
   // For simplicity, we only retain values that are identical, but not ones 
that
   // are non-identical but equivalent. This is like

[clang] [clang-format] Add new option: WrapNamespaceBodyWithNewlines (PR #106145)

2024-12-30 Thread Owen Pan via cfe-commits

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

Please enable "Allowing edits by maintainers".

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


[clang] [Tooling/Inclusion] Modify the Python script to open the C++ reference with UTF-8 encoding. (PR #121341)

2024-12-30 Thread via cfe-commits

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


[clang] f385542 - [Tooling/Inclusion] Modify the Python script to open the C++ reference with UTF-8 encoding. (#121341)

2024-12-30 Thread via cfe-commits

Author: c8ef
Date: 2024-12-31T09:28:34+08:00
New Revision: f385542f62fa1f57001c95c476165e1618cb54ba

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

LOG: [Tooling/Inclusion] Modify the Python script to open the C++ reference 
with UTF-8 encoding. (#121341)

This will prevent the error on systems with a default encoding other
than utf-8.

```
UnicodeDecodeError: 'gbk' codec can't decode byte 0xb6 in position 12958: 
illegal multibyte sequence
```

Added: 


Modified: 
clang/tools/include-mapping/cppreference_parser.py

Removed: 




diff  --git a/clang/tools/include-mapping/cppreference_parser.py 
b/clang/tools/include-mapping/cppreference_parser.py
index 9101f3dbff0f94..f7da2ba8bb6d84 100644
--- a/clang/tools/include-mapping/cppreference_parser.py
+++ b/clang/tools/include-mapping/cppreference_parser.py
@@ -139,7 +139,7 @@ def _ParseIndexPage(index_page_html):
 
 
 def _ReadSymbolPage(path, name, qual_name):
-with open(path) as f:
+with open(path, encoding="utf-8") as f:
 return _ParseSymbolPage(f.read(), name, qual_name)
 
 
@@ -156,7 +156,7 @@ def _GetSymbols(pool, root_dir, index_page_name, namespace, 
variants_to_accept):
 #  contains the defined header.
 #   2. Parse the symbol page to get the defined header.
 index_page_path = os.path.join(root_dir, index_page_name)
-with open(index_page_path, "r") as f:
+with open(index_page_path, "r", encoding="utf-8") as f:
 # Read each symbol page in parallel.
 results = []  # (symbol_name, promise of [header...])
 for symbol_name, symbol_page_path, variant in 
_ParseIndexPage(f.read()):



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


[clang] [Clang][C++23] Core language changes from P1467R9 extended floating-point types and standard names. (PR #78503)

2024-12-30 Thread M. Zeeshan Siddiqui via cfe-commits

https://github.com/codemzs updated 
https://github.com/llvm/llvm-project/pull/78503

>From 6ba3b01a87fad05ce11a47579e12fe0a293212c4 Mon Sep 17 00:00:00 2001
From: "M. Zeeshan Siddiqui" 
Date: Mon, 13 Nov 2023 17:37:36 +
Subject: [PATCH] [Clang][C++23] Implement core language changes from P1467R9
 extended floating-point types and standard names.

This commit implements Core language changes based on P1467R9 Extended
floating-point types and standard names.

As per the proposal's definition the following two types are marked as
extended floating point: Float16 (aka _Float16) and
Bfloat16 (aka decltype (0.0bf16) or __bf16). Future work can extend this
to support other floating-point types such as Float32, Float64, and
Float128.

RFC: 
https://discourse.llvm.org/t/rfc-c-23-p1467r9-extended-floating-point-types-and-standard-names/70033

Differential Revision: https://reviews.llvm.org/D149573
---
 clang/docs/ReleaseNotes.rst   |   5 +
 clang/include/clang/AST/ASTContext.h  |  54 +-
 clang/include/clang/AST/BuiltinTypes.def  |   4 +-
 clang/include/clang/AST/Type.h|   7 +
 .../clang/Basic/DiagnosticSemaKinds.td|   2 +
 clang/include/clang/Lex/LiteralSupport.h  |   1 +
 .../Core/PathSensitive/SMTConv.h  |  19 +-
 clang/lib/AST/ASTContext.cpp  | 147 -
 clang/lib/AST/StmtPrinter.cpp |   1 +
 clang/lib/AST/Type.cpp|  27 +
 clang/lib/Frontend/InitPreprocessor.cpp   |   6 +-
 clang/lib/Lex/LiteralSupport.cpp  |  17 +
 clang/lib/Sema/Sema.cpp   |  16 +
 clang/lib/Sema/SemaCast.cpp   |  13 +
 clang/lib/Sema/SemaChecking.cpp   |  23 +-
 clang/lib/Sema/SemaExpr.cpp   |  60 ++-
 clang/lib/Sema/SemaOverload.cpp   |  80 ++-
 .../cxx23-fp-ext-std-names-p1467r9.cpp| 499 +
 .../test/CodeGenCXX/cxx23-vector-bfloat16.cpp |  67 +++
 .../Sema/cxx23-fp-ext-std-names-p1467r9.cpp   | 505 ++
 20 files changed, 1507 insertions(+), 46 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/cxx23-fp-ext-std-names-p1467r9.cpp
 create mode 100644 clang/test/CodeGenCXX/cxx23-vector-bfloat16.cpp
 create mode 100644 clang/test/Sema/cxx23-fp-ext-std-names-p1467r9.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b7da12bcf65818..f5b10d1bc776ad 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -248,6 +248,11 @@ C++ Language Changes
 - The builtin type alias ``__builtin_common_type`` has been added to improve 
the
   performance of ``std::common_type``.
 
+- Implemented `P1467R9: Extended floating-point types and standard names 
`_. Enables
+  extended floating-point types beyond the three standard ones, establishing 
rules for their interactions and
+  conversions with each other and other types, while ensuring no alteration in 
the behavior of existing
+  standard types. The current implementation enables support for 
`std::float16_t` and `std::bfloat16_t` types.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 1e89a6805ce9c6..440848bb44e0cd 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -55,6 +55,16 @@ template  class SmallPtrSet;
 
 namespace clang {
 
+// Conversion ranks introduced in C++23 6.8.6p2 [conv.rank]
+enum FloatConvRankCompareResult {
+  FRCR_Unordered,
+  FRCR_Lesser,
+  FRCR_Greater,
+  FRCR_Equal,
+  FRCR_Equal_Lesser_Subrank,
+  FRCR_Equal_Greater_Subrank,
+};
+
 class APValue;
 class ASTMutationListener;
 class ASTRecordLayout;
@@ -1182,8 +1192,8 @@ class ASTContext : public RefCountedBase {
   CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
   SatUnsignedLongFractTy;
   CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
-  CanQualType BFloat16Ty;
-  CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
+  CanQualType BFloat16Ty; // [C++23 6.8.3p5][basic.extended.fp]
+  CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3 and [C++23 
6.8.3p1][basic.extended.fp]
   CanQualType VoidPtrTy, NullPtrTy;
   CanQualType DependentTy, OverloadTy, BoundMemberTy, UnresolvedTemplateTy,
   UnknownAnyTy;
@@ -2563,6 +2573,9 @@ class ASTContext : public RefCountedBase {
   /// More type predicates useful for type checking/promotion
   bool isPromotableIntegerType(QualType T) const; // C99 6.3.1.1p2
 
+  /// Determine if a floating type can be promoted to another floating type.
+  bool isPromotableFloatingType(QualType T) const;
+
   /// Return the "preferred" alignment of the specified type \p T for
   /// the current target, in bits.
   ///
@@ -2970,6 +2983,9 @@ class ASTContext : public RefCountedBase {
   /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
   QualType getPromotedIntegerType(QualType Pr

[clang] [Clang][Sema] Expose static inline functions from GMF (PR #104701)

2024-12-30 Thread LLVM Continuous Integration via cfe-commits
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= ,
Jan =?utf-8?q?Kokemüller?= 
Message-ID:
In-Reply-To: 


llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `clang-aarch64-quick` 
running on `linaro-clang-aarch64-quick` while building `clang` at step 5 "ninja 
check 1".

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


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

```
Step 5 (ninja check 1) failure: stage 1 checked (failure)
 TEST 'Clangd Unit Tests :: ./ClangdTests/154/318' FAILED 

Script(shard):
--
GTEST_OUTPUT=json:/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/clangd/unittests/./ClangdTests-Clangd
 Unit Tests-3527952-154-318.json GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=318 
GTEST_SHARD_INDEX=154 
/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/clangd/unittests/./ClangdTests
--

Script:
--
/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/clangd/unittests/./ClangdTests
 --gtest_filter=CompletionTest.EnableSpeculativeIndexRequest
--
ASTWorker building file /clangd-test/foo.cpp version null with command 
[/clangd-test]
clang -ffreestanding /clangd-test/foo.cpp
Driver produced command: cc1 -cc1 -triple aarch64-unknown-linux-gnu 
-fsyntax-only -disable-free -clear-ast-before-backend -main-file-name foo.cpp 
-mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=non-leaf 
-fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases 
-ffreestanding -target-cpu generic -target-feature +v8a -target-feature 
+fp-armv8 -target-feature +neon -target-abi aapcs -debugger-tuning=gdb 
-fdebug-compilation-dir=/clangd-test -fcoverage-compilation-dir=/clangd-test 
-resource-dir lib/clang/20 -internal-isystem lib/clang/20/include 
-internal-isystem /usr/local/include -internal-externc-isystem /include 
-internal-externc-isystem /usr/include -fdeprecated-macro -ferror-limit 19 
-fno-signed-char -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fcxx-exceptions 
-fexceptions -no-round-trip-args -target-feature -fmv -faddrsig 
-D__GCC_HAVE_DWARF2_CFI_ASM=1 -x c++ /clangd-test/foo.cpp
Building first preamble for /clangd-test/foo.cpp version null
Built preamble of size 705748 for file /clangd-test/foo.cpp version null in 
0.06 seconds
Code complete: fuzzyFind({
  "AnyScope": false,
  "Limit": null,
  "PreferredTypes": [],
  "ProximityPaths": [
"/clangd-test/foo.cpp"
  ],
  "Query": "ab",
  "RestrictForCodeCompletion": true,
  "Scopes": [
"ns1::"
  ]
})
Code complete: sema context Symbol, query scopes [ns1::] (AnyScope=false), 
expected type 
Code complete: 1 results from Sema, 0 from Index, 0 matched, 0 from 
identifiers, 1 returned (incomplete).
Ignored diagnostic. /clangd-test/foo.cpp:4:23:no member named 'ab' in namespace 
'ns1'
Code complete: fuzzyFind({
  "AnyScope": false,
  "Limit": null,
  "PreferredTypes": [],
  "ProximityPaths": [
"/clangd-test/foo.cpp"
  ],
  "Query": "ab",
  "RestrictForCodeCompletion": true,
  "Scopes": [
"ns1::"
  ]
})
Code complete: sema context Symbol, query scopes [ns1::] (AnyScope=false), 
expected type 
Code complete: 1 results from Sema, 0 from Index, 0 matched, 0 from 
identifiers, 1 returned (incomplete).
Code complete: fuzzyFind({
  "AnyScope": false,
  "Limit": null,
...

```



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


[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2024-12-30 Thread Owen Pan via cfe-commits

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

>From 7e865d66f147da3afa1ebcd55354e97fdfd8374a Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 29 Dec 2024 20:17:46 -0800
Subject: [PATCH] [clang-format] Add VariableTemplate option

Closes #120148.
---
 clang/docs/ClangFormatStyleOptions.rst|  9 +
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Format/Format.h   | 11 ++-
 clang/lib/Format/Format.cpp   |  1 +
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/FormatTokenLexer.cpp |  4 
 clang/lib/Format/FormatTokenLexer.h   |  3 ++-
 clang/lib/Format/TokenAnnotator.cpp   | 19 +++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 13 +
 9 files changed, 56 insertions(+), 6 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..fa098c17a9bb31 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -6793,6 +6793,15 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+.. _VariableTemplates:
+
+**VariableTemplates** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
+  A vector of non-keyword identifiers that should be interpreted as variable
+  template names.
+
+  A ``)`` after a variable template instantiation is **not** annotated as
+  the closing parenthesis of C-style cast operator.
+
 .. _VerilogBreakBetweenInstancePorts:
 
 **VerilogBreakBetweenInstancePorts** (``Boolean``) :versionbadge:`clang-format 
17` :ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9b0cb815a15db..f05a95e31dc255 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1118,6 +1118,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``VariableTemplates`` option.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..8c3d184cc71419 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5099,6 +5099,15 @@ struct FormatStyle {
   /// \version 3.7
   UseTabStyle UseTab;
 
+  /// A vector of non-keyword identifiers that should be interpreted as 
variable
+  /// template names.
+  ///
+  /// A ``)`` after a variable template instantiation is **not** annotated as
+  /// the closing parenthesis of C-style cast operator.
+  ///
+  /// \version 20
+  std::vector VariableTemplates;
+
   /// For Verilog, put each port on its own line in module instantiations.
   /// \code
   ///true:
@@ -5308,7 +5317,7 @@ struct FormatStyle {
TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
-   UseTab == R.UseTab &&
+   UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
VerilogBreakBetweenInstancePorts ==
R.VerilogBreakBetweenInstancePorts &&
WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros;
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..fe5465ce7b09de 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1164,6 +1164,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
 IO.mapOptional("UseTab", Style.UseTab);
+IO.mapOptional("VariableTemplates", Style.VariableTemplates);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
 IO.mapOptional("WhitespaceSensitiveMacros",
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f6bb860a1fea31..8917049cefb865 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -186,6 +186,7 @@ namespace format {
   TYPE(UnionLBrace)
\
   TYPE(UnionRBrace)
\
   TYPE(UntouchableMacroFunc)   
\
+  TYPE(VariableTemplate)   
\
   /* Like in 'assign x = 0, y = 1;' . */   
\
   TYPE(VerilogAssignComma) 
\
   /* like in begin : block */  
\
diff --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 7a264bddcdfe19..0f8d4940d4369a 100644
--- a/clang/lib/Format/FormatTo

[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2024-12-30 Thread Owen Pan via cfe-commits

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

>From 7e865d66f147da3afa1ebcd55354e97fdfd8374a Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 29 Dec 2024 20:17:46 -0800
Subject: [PATCH] [clang-format] Add VariableTemplate option

Closes #120148.
---
 clang/docs/ClangFormatStyleOptions.rst|  9 +
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Format/Format.h   | 11 ++-
 clang/lib/Format/Format.cpp   |  1 +
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/FormatTokenLexer.cpp |  4 
 clang/lib/Format/FormatTokenLexer.h   |  3 ++-
 clang/lib/Format/TokenAnnotator.cpp   | 19 +++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 13 +
 9 files changed, 56 insertions(+), 6 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..fa098c17a9bb31 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -6793,6 +6793,15 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+.. _VariableTemplates:
+
+**VariableTemplates** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
+  A vector of non-keyword identifiers that should be interpreted as variable
+  template names.
+
+  A ``)`` after a variable template instantiation is **not** annotated as
+  the closing parenthesis of C-style cast operator.
+
 .. _VerilogBreakBetweenInstancePorts:
 
 **VerilogBreakBetweenInstancePorts** (``Boolean``) :versionbadge:`clang-format 
17` :ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9b0cb815a15db..f05a95e31dc255 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1118,6 +1118,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``VariableTemplates`` option.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..8c3d184cc71419 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5099,6 +5099,15 @@ struct FormatStyle {
   /// \version 3.7
   UseTabStyle UseTab;
 
+  /// A vector of non-keyword identifiers that should be interpreted as 
variable
+  /// template names.
+  ///
+  /// A ``)`` after a variable template instantiation is **not** annotated as
+  /// the closing parenthesis of C-style cast operator.
+  ///
+  /// \version 20
+  std::vector VariableTemplates;
+
   /// For Verilog, put each port on its own line in module instantiations.
   /// \code
   ///true:
@@ -5308,7 +5317,7 @@ struct FormatStyle {
TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
-   UseTab == R.UseTab &&
+   UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
VerilogBreakBetweenInstancePorts ==
R.VerilogBreakBetweenInstancePorts &&
WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros;
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..fe5465ce7b09de 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1164,6 +1164,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
 IO.mapOptional("UseTab", Style.UseTab);
+IO.mapOptional("VariableTemplates", Style.VariableTemplates);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
 IO.mapOptional("WhitespaceSensitiveMacros",
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f6bb860a1fea31..8917049cefb865 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -186,6 +186,7 @@ namespace format {
   TYPE(UnionLBrace)
\
   TYPE(UnionRBrace)
\
   TYPE(UntouchableMacroFunc)   
\
+  TYPE(VariableTemplate)   
\
   /* Like in 'assign x = 0, y = 1;' . */   
\
   TYPE(VerilogAssignComma) 
\
   /* like in begin : block */  
\
diff --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 7a264bddcdfe19..0f8d4940d4369a 100644
--- a/clang/lib/Format/FormatTo

[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits


@@ -2720,6 +2720,22 @@ TEST_F(ConstantRangeTest, binaryAnd) {
   EXPECT_EQ(R16_32.binaryAnd(R0_99), R0_32);
   EXPECT_EQ(R0_99.binaryAnd(R16_32), R0_32);
 
+  // 'And' with leading bits are masked (with common leading bits stripped)

zsrkmyn wrote:

Oh, if you're asking wrapped set, e.g., `[254, 1)` (or `[-2, 1)`), the 
algorithm bails out early at 
[here](https://github.com/llvm/llvm-project/commit/9c49208195b25c6cf5bdbd0f6d85ed5f8348812d#diff-b4f991f8e64d4fd23608e9ac00520c91429ad1dca8ea91f8be3a2922ea465dbdR1553).
 In such case, 0 is always in the range.

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


[clang] [C++20] [Modules] [Serialization] Delay marking pending incomplete decl chains until the end of `finishPendingActions`. (PR #121245)

2024-12-30 Thread Michael Park via cfe-commits

mpark wrote:

> +1. It is best to have more test case. Generally I reduce it by hand in this 
> case.

Yeah, I did already spent quite a bit of effort trying to reduce my hand but 
have not been successful so far. I'll try again and report back. Would you 
still review the logic / whether the suggested solution seems sensible?

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


[clang] [C++20] [Modules] [Serialization] Delay marking pending incomplete decl chains until the end of `finishPendingActions`. (PR #121245)

2024-12-30 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> > +1. It is best to have more test case. Generally I reduce it by hand in 
> > this case.
> 
> Yeah, I did already spent quite a bit of effort trying to reduce the creduce 
> result by hand but have not been successful so far 😕. I'll try again and 
> report back. Would you still review the logic / whether the suggested 
> solution seems sensible?

The solution looks neat to me. 

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits

https://github.com/zsrkmyn updated 
https://github.com/llvm/llvm-project/pull/120352

>From c585a24277ddbf828f19faa6a66c6dd3bae699e2 Mon Sep 17 00:00:00 2001
From: Senran Zhang 
Date: Tue, 17 Dec 2024 16:15:25 +0800
Subject: [PATCH] [ConstantRange] Estimate tighter lower (upper) bounds for
 masked binary and (or)

Co-author: Yingwei Zheng (@dtcxzyw)
---
 clang/test/CodeGen/AArch64/fpm-helpers.c  | 18 ++--
 llvm/lib/IR/ConstantRange.cpp | 76 ++--
 .../SCCP/range-and-or-bit-masked.ll   | 88 +++
 llvm/unittests/IR/ConstantRangeTest.cpp   | 28 ++
 4 files changed, 195 insertions(+), 15 deletions(-)
 create mode 100644 llvm/test/Transforms/SCCP/range-and-or-bit-masked.ll

diff --git a/clang/test/CodeGen/AArch64/fpm-helpers.c 
b/clang/test/CodeGen/AArch64/fpm-helpers.c
index 4bced01d5c71fa..6264b5caeb4f50 100644
--- a/clang/test/CodeGen/AArch64/fpm-helpers.c
+++ b/clang/test/CodeGen/AArch64/fpm-helpers.c
@@ -35,7 +35,7 @@ extern "C" {
 //
 fpm_t test_init() { return __arm_fpm_init(); }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src1_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -6) i64 @test_src1_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 -8
@@ -44,7 +44,7 @@ fpm_t test_src1_1() {
   return __arm_set_fpm_src1_format(INIT_ONES, __ARM_FPM_E5M2);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src1_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -6) i64 @test_src1_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 1
@@ -53,7 +53,7 @@ fpm_t test_src1_2() {
   return __arm_set_fpm_src1_format(INIT_ZERO, __ARM_FPM_E4M3);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src2_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -48) i64 @test_src2_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 -57
@@ -62,7 +62,7 @@ fpm_t test_src2_1() {
   return __arm_set_fpm_src2_format(INIT_ONES, __ARM_FPM_E5M2);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src2_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -48) i64 @test_src2_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 8
@@ -71,7 +71,7 @@ fpm_t test_src2_2() {
   return __arm_set_fpm_src2_format(INIT_ZERO, __ARM_FPM_E4M3);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_dst1_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -384) i64 @test_dst1_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 -449
@@ -80,7 +80,7 @@ fpm_t test_dst1_1() {
   return __arm_set_fpm_dst_format(INIT_ONES, __ARM_FPM_E5M2);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_dst2_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -384) i64 @test_dst2_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 64
@@ -139,21 +139,21 @@ fpm_t test_lscale() { return 
__arm_set_fpm_lscale(INIT_ZERO, 127); }
 //
 fpm_t test_lscale2() { return __arm_set_fpm_lscale2(INIT_ZERO, 63); }
 
-// CHECK-LABEL: define dso_local noundef range(i64 0, 4294967296) i64 
@test_nscale_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, 4278190081) i64 
@test_nscale_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 2147483648
 //
 fpm_t test_nscale_1() { return __arm_set_fpm_nscale(INIT_ZERO, -128); }
 
-// CHECK-LABEL: define dso_local noundef range(i64 0, 4294967296) i64 
@test_nscale_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, 4278190081) i64 
@test_nscale_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 2130706432
 //
 fpm_t test_nscale_2() { return __arm_set_fpm_nscale(INIT_ZERO, 127); }
 
-// CHECK-LABEL: define dso_local noundef range(i64 0, 4294967296) i64 
@test_nscale_3(
+// CHECK-LABEL: define dso_local noundef range(i64 0, 4278190081) i64 
@test_nscale_3(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 4278190080
diff --git a/llvm/lib/IR/ConstantRange.cpp b/llvm/lib/IR/ConstantRange.cpp
index d81a292916fdea..35664353989929 100644
--- a/llvm/lib/IR/ConstantRange.cpp
+++ b/llvm/lib/IR/ConstantRange.cpp
@@ -1520,15 +1520,72 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'00101'1,  ; LLo
+///  10'1'0]  ; LHi
+///   RHS = [10'1'0,  ; RLo
+///  10'1'1]  ; RHi
+///
+/// we know that the higher 2 bits of t

[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits


@@ -1520,15 +1520,72 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'00101'1,  ; LLo
+///  10'1'0]  ; LHi
+///   RHS = [10'1'0,  ; RLo
+///  10'1'1]  ; RHi
+///
+/// we know that the higher 2 bits of the result is always 10; and we also
+/// notice that RHS[1:6] are always 1, so the result[1:6] cannot be less than
+/// LHS[1:6] (i.e., 00101). Thus, the lower bound is 10'00101'0.
+///
+/// The algorithm is as follows,
+/// 1. we first calculate a mask to find the higher common bits by
+///   Mask = ~((LLo ^ LHi) | (LLo ^ LHi) | (LLo ^ RLo));

zsrkmyn wrote:

Fixed; thanks!

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits


@@ -2720,6 +2720,22 @@ TEST_F(ConstantRangeTest, binaryAnd) {
   EXPECT_EQ(R16_32.binaryAnd(R0_99), R0_32);
   EXPECT_EQ(R0_99.binaryAnd(R16_32), R0_32);
 
+  // 'And' with leading bits are masked (with common leading bits stripped)

zsrkmyn wrote:

Test added.

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits


@@ -2720,6 +2720,22 @@ TEST_F(ConstantRangeTest, binaryAnd) {
   EXPECT_EQ(R16_32.binaryAnd(R0_99), R0_32);
   EXPECT_EQ(R0_99.binaryAnd(R16_32), R0_32);
 
+  // 'And' with leading bits are masked (with common leading bits stripped)
+  ConstantRange RMaskedL(APInt(8, 0b10'00101'1), APInt(8, 0b10'1'0 + 1));
+  ConstantRange RMaskedR(APInt(8, 0b10'1'0), APInt(8, 0b10'1'1 + 1));
+  EXPECT_EQ(RMaskedL.binaryAnd(RMaskedR).getLower(), APInt(8, 0b10'00101'0));
+  EXPECT_EQ(RMaskedR.binaryAnd(RMaskedL).getLower(), APInt(8, 0b10'00101'0));
+
+  ConstantRange RMaskedL1(APInt(8, 0b00'011'010), APInt(8, 0b00'100'100 + 1));
+  ConstantRange RMaskedR1(APInt(8, 0b00'111'010), APInt(8, 0b00'111'110 + 1));
+  EXPECT_EQ(RMaskedL1.binaryAnd(RMaskedR1).getLower(), APInt(8, 0b00'011'000));
+  EXPECT_EQ(RMaskedR1.binaryAnd(RMaskedL1).getLower(), APInt(8, 0b00'011'000));
+
+  ConstantRange RMaskedL2(APInt(8, 0b'0111u), APInt(8, 0b'1101u + 1u));
+  ConstantRange RMaskedR2(APInt(8, 0xff), APInt(8, 0));
+  EXPECT_EQ(RMaskedL2.binaryAnd(RMaskedR2), RMaskedL2);
+  EXPECT_EQ(RMaskedR2.binaryAnd(RMaskedL2), RMaskedL2);

zsrkmyn wrote:

Added.

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-30 Thread Stephen Senran Zhang via cfe-commits

https://github.com/zsrkmyn updated 
https://github.com/llvm/llvm-project/pull/120352

>From 19555edc7e2749a6e904c80d963a46431b23b6d1 Mon Sep 17 00:00:00 2001
From: Senran Zhang 
Date: Tue, 17 Dec 2024 16:15:25 +0800
Subject: [PATCH] [ConstantRange] Estimate tighter lower (upper) bounds for
 masked binary and (or)

Co-author: Yingwei Zheng (@dtcxzyw)
---
 clang/test/CodeGen/AArch64/fpm-helpers.c  | 18 ++--
 llvm/lib/IR/ConstantRange.cpp | 76 ++--
 .../SCCP/range-and-or-bit-masked.ll   | 88 +++
 llvm/unittests/IR/ConstantRangeTest.cpp   | 31 +++
 4 files changed, 198 insertions(+), 15 deletions(-)
 create mode 100644 llvm/test/Transforms/SCCP/range-and-or-bit-masked.ll

diff --git a/clang/test/CodeGen/AArch64/fpm-helpers.c 
b/clang/test/CodeGen/AArch64/fpm-helpers.c
index 4bced01d5c71fa..6264b5caeb4f50 100644
--- a/clang/test/CodeGen/AArch64/fpm-helpers.c
+++ b/clang/test/CodeGen/AArch64/fpm-helpers.c
@@ -35,7 +35,7 @@ extern "C" {
 //
 fpm_t test_init() { return __arm_fpm_init(); }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src1_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -6) i64 @test_src1_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 -8
@@ -44,7 +44,7 @@ fpm_t test_src1_1() {
   return __arm_set_fpm_src1_format(INIT_ONES, __ARM_FPM_E5M2);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src1_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -6) i64 @test_src1_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 1
@@ -53,7 +53,7 @@ fpm_t test_src1_2() {
   return __arm_set_fpm_src1_format(INIT_ZERO, __ARM_FPM_E4M3);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src2_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -48) i64 @test_src2_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 -57
@@ -62,7 +62,7 @@ fpm_t test_src2_1() {
   return __arm_set_fpm_src2_format(INIT_ONES, __ARM_FPM_E5M2);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src2_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -48) i64 @test_src2_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 8
@@ -71,7 +71,7 @@ fpm_t test_src2_2() {
   return __arm_set_fpm_src2_format(INIT_ZERO, __ARM_FPM_E4M3);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_dst1_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -384) i64 @test_dst1_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 -449
@@ -80,7 +80,7 @@ fpm_t test_dst1_1() {
   return __arm_set_fpm_dst_format(INIT_ONES, __ARM_FPM_E5M2);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_dst2_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -384) i64 @test_dst2_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 64
@@ -139,21 +139,21 @@ fpm_t test_lscale() { return 
__arm_set_fpm_lscale(INIT_ZERO, 127); }
 //
 fpm_t test_lscale2() { return __arm_set_fpm_lscale2(INIT_ZERO, 63); }
 
-// CHECK-LABEL: define dso_local noundef range(i64 0, 4294967296) i64 
@test_nscale_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, 4278190081) i64 
@test_nscale_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 2147483648
 //
 fpm_t test_nscale_1() { return __arm_set_fpm_nscale(INIT_ZERO, -128); }
 
-// CHECK-LABEL: define dso_local noundef range(i64 0, 4294967296) i64 
@test_nscale_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, 4278190081) i64 
@test_nscale_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 2130706432
 //
 fpm_t test_nscale_2() { return __arm_set_fpm_nscale(INIT_ZERO, 127); }
 
-// CHECK-LABEL: define dso_local noundef range(i64 0, 4294967296) i64 
@test_nscale_3(
+// CHECK-LABEL: define dso_local noundef range(i64 0, 4278190081) i64 
@test_nscale_3(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 4278190080
diff --git a/llvm/lib/IR/ConstantRange.cpp b/llvm/lib/IR/ConstantRange.cpp
index d81a292916fdea..35664353989929 100644
--- a/llvm/lib/IR/ConstantRange.cpp
+++ b/llvm/lib/IR/ConstantRange.cpp
@@ -1520,15 +1520,72 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'00101'1,  ; LLo
+///  10'1'0]  ; LHi
+///   RHS = [10'1'0,  ; RLo
+///  10'1'1]  ; RHi
+///
+/// we know that the higher 2 bits of 

[clang] [Clang] Consider preferred_type in bitfield warnings (#116760) (PR #116785)

2024-12-30 Thread Oliver Hunt via cfe-commits

https://github.com/ojhunt updated 
https://github.com/llvm/llvm-project/pull/116785

>From 5f260726253e78a00d2dff02c22837ce02b49075 Mon Sep 17 00:00:00 2001
From: Oliver Hunt 
Date: Tue, 19 Nov 2024 11:55:11 +0100
Subject: [PATCH 1/5] [Clang] Consider preferred_type in bitfield warnings
 (#116760)

Very simply extends the bitfield sema checks for assignment to fields
with a preferred type specified to consider the preferred type if the
decl storage type is not explicitly an enum type.

This does mean that if the preferred and explicit types have different
storage requirements we may not warn in all possible cases, but that's
a scenario for which the warnings are much more complex and confusing.
---
 .../clang/Basic/DiagnosticSemaKinds.td|   9 +-
 clang/lib/Sema/SemaChecking.cpp   |  23 +-
 .../Sema/bitfield-preferred-type-sizing.c | 108 +
 .../bitfield-preferred-type-sizing.cpp| 413 ++
 4 files changed, 546 insertions(+), 7 deletions(-)
 create mode 100644 clang/test/Sema/bitfield-preferred-type-sizing.c
 create mode 100644 clang/test/SemaCXX/bitfield-preferred-type-sizing.cpp

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 3caf471d3037f9..226b52f58d88d9 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6404,20 +6404,23 @@ def warn_bitfield_width_exceeds_type_width: Warning<
 def err_bitfield_too_wide : Error<
   "%select{bit-field %1|anonymous bit-field}0 is too wide (%2 bits)">;
 def warn_bitfield_too_small_for_enum : Warning<
-  "bit-field %0 is not wide enough to store all enumerators of %1">,
+  "bit-field %0 is not wide enough to store all enumerators of 
%select{|preferred type }1%2">,
   InGroup, DefaultIgnore;
 def note_widen_bitfield : Note<
   "widen this field to %0 bits to store all values of %1">;
 def warn_unsigned_bitfield_assigned_signed_enum : Warning<
-  "assigning value of signed enum type %1 to unsigned bit-field %0; "
+  "assigning value of %select{|preferred }1signed enum type %2 to unsigned 
bit-field %0; "
   "negative enumerators of enum %1 will be converted to positive values">,
   InGroup, DefaultIgnore;
 def warn_signed_bitfield_enum_conversion : Warning<
   "signed bit-field %0 needs an extra bit to represent the largest positive "
-  "enumerators of %1">,
+  "enumerators of %select{|preferred type }1%2">,
   InGroup, DefaultIgnore;
 def note_change_bitfield_sign : Note<
   "consider making the bitfield type %select{unsigned|signed}0">;
+def note_bitfield_preferred_type : Note<
+  "preferred type for bitfield %0 specified here"
+>;
 
 def warn_missing_braces : Warning<
   "suggest braces around initialization of subobject">,
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 2d4a7cd287b70d..254284e950c7e5 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -10488,7 +10488,14 @@ static bool AnalyzeBitFieldAssignment(Sema &S, 
FieldDecl *Bitfield, Expr *Init,
 // The RHS is not constant.  If the RHS has an enum type, make sure the
 // bitfield is wide enough to hold all the values of the enum without
 // truncation.
-if (const auto *EnumTy = OriginalInit->getType()->getAs()) {
+const auto *EnumTy = OriginalInit->getType()->getAs();
+const PreferredTypeAttr *PTAttr = nullptr;
+if (!EnumTy) {
+  PTAttr = Bitfield->getAttr();
+  if (PTAttr)
+EnumTy = PTAttr->getType()->getAs();
+}
+if (EnumTy) {
   EnumDecl *ED = EnumTy->getDecl();
   bool SignedBitfield = BitfieldType->isSignedIntegerType();
 
@@ -10509,14 +10516,18 @@ static bool AnalyzeBitFieldAssignment(Sema &S, 
FieldDecl *Bitfield, Expr *Init,
  ED->getNumPositiveBits() == FieldWidth) {
 DiagID = diag::warn_signed_bitfield_enum_conversion;
   }
-
+  unsigned PreferredTypeDiagIndex = PTAttr != nullptr;
   if (DiagID) {
-S.Diag(InitLoc, DiagID) << Bitfield << ED;
+S.Diag(InitLoc, DiagID) << Bitfield << PreferredTypeDiagIndex << ED;
 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
 SourceRange TypeRange =
 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
 S.Diag(Bitfield->getTypeSpecStartLoc(), 
diag::note_change_bitfield_sign)
 << SignedEnum << TypeRange;
+if (PTAttr) {
+  S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
+  << ED;
+}
   }
 
   // Compute the required bitwidth. If the enum has negative values, we 
need
@@ -10530,9 +10541,13 @@ static bool AnalyzeBitFieldAssignment(Sema &S, 
FieldDecl *Bitfield, Expr *Init,
   if (BitsNeeded > FieldWidth) {
 Expr *WidthExpr = Bitfield->getBitWidth();
 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
-<< Bitfield << ED;
+<< Bitfield << Pref

[clang] [Tooling/Inclusion] Modify the Python script to open the C++ reference with UTF-8 encoding. (PR #121341)

2024-12-30 Thread Haojian Wu via cfe-commits

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


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


[clang] [clang][analyzer] Stabilize path-constraint order by using alloc IDs (PR #121347)

2024-12-30 Thread Balazs Benics via cfe-commits

steakhal wrote:

Disclaimer: I haven't checked the actual patch, but I'll come back to it :D 
Maybe next year.
I think I've seen already a variant of this downstream and I generally agreed 
with the vision. I don't expect much friction on this front, but I'll have a 
deeper look.

---

> This patch reduced the run-to-run churn (flakiness) in SE issues from 80-90 
> to 30-40 (out of 78K) in our CSA deployment (in our setting flaky issues are 
> mostly due to Z3 refutation instability).

Does the unstable constraint order only affect Z3 refutation, or did you 
measure/notice differences in report flakyness even without Z3 refutation? I 
think it would be great to see the impact of this change, while we eliminate 
the Z3 from the equation.

---

> I considered using simple incremental ids instead of allocator offsets, but 
> found no advantage. Do you see any?

I'm okay with using allocator offsets for this purpose. That's already a global 
state, I don't think having another one would really bring much benefit (aka. 
having a separate global counter for them).

> Would it make sense to unify SymbolData::Sym and SymExpr::AllocID, and maybe 
> get rid of the intermediary SymbolData?

I think SymbolData::Sym and SymExpr::AllocID could be unified. The SymbolData 
abstraction is useful in general and allows us to differentiate the "source" of 
the different symbols we have identities for (aka. they are the "interesting" 
symbols). These are always the "leaves" of the SymExpr trees, so that could be 
another useful way of looking at SymbolData - once you see that, you won't 
traverse any deeper.

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


[clang] [NFC][Driver] Use global --implicit-check-not=libclang_rt (PR #121081)

2024-12-30 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Hi, we see this test failed on our clang bots, looks like we should relax the 
check 
log:
```
/b/s/w/ir/cache/builder/src/third_party/llvm/clang/test/Driver/sanitizer-ld.c:335:39:
 error: CHECK-ASAN-ANDROID-SHARED-LIBASAN: expected string not found in input
 // CHECK-ASAN-ANDROID-SHARED-LIBASAN: libclang_rt.asan.so"
   ^
 :1:1: note: scanning from here
 clang version 20.0.0git 
(https://chromium.googlesource.com/a/external/github.com/llvm/llvm-project 
79af7bdd4e415aa8a94263a4507b51862fba882f)
 ^
 :5:1765: note: possible intended match here
  
"/b/s/w/ir/cache/builder/src/third_party/llvm-build/Release+Asserts/bin/clang" 
"-cc1" "-triple" "armv4t-unknown-linux-android" "-emit-obj" "-dumpdir" "a-" 
"-disable-free" "-clear-ast-before-backend" "-disable-llvm-verifier" 
"-discard-value-names" "-main-file-name" "sanitizer-ld.c" "-mrelocation-model" 
"pic" "-pic-level" "2" "-pic-is-pie" "-mframe-pointer=all" "-ffp-contract=on" 
"-fno-rounding-math" "-mconstructor-aliases" "-funwind-tables=2" "-target-cpu" 
"arm7tdmi" "-target-feature" "+soft-float" "-target-feature" "+soft-float-abi" 
"-target-feature" "-vfp2" "-target-feature" "-vfp2sp" "-target-feature" "-vfp3" 
"-target-feature" "-vfp3d16" "-target-feature" "-vfp3d16sp" "-target-feature" 
"-vfp3sp" "-target-feature" "-fp16" "-target-feature" "-vfp4" "-target-feature" 
"-vfp4d16" "-target-feature" "-vfp4d16sp" "-target-feature" "-vfp4sp" 
"-target-feature" "-fp-armv8" "-target-feature" "-fp-armv8d16" 
"-target-feature" "-fp-armv8d16sp" "-target-feature" "-fp-armv8sp" 
"-target-feature" "-fullfp16" "-target-feature" "-fp64" "-target-feature" 
"-d32" "-target-feature" "-neon" "-target-feature" "-sha2" "-target-feature" 
"-aes" "-target-feature" "-dotprod" "-target-feature" "-fp16fml" 
"-target-feature" "-bf16" "-target-feature" "-mve" "-target-feature" "-mve.fp" 
"-target-feature" "-fpregs" "-target-feature" "+strict-align" "-target-abi" 
"aapcs-linux" "-msoft-float" "-mfloat-abi" "soft" "-Wunaligned-access" 
"-debugger-tuning=gdb" 
"-fdebug-compilation-dir=/b/s/w/ir/cache/builder/src/third_party/llvm-build/Release+Asserts/tools/clang/test/Driver"
 
"-fcoverage-compilation-dir=/b/s/w/ir/cache/builder/src/third_party/llvm-build/Release+Asserts/tools/clang/test/Driver"
 "-resource-dir" 
"/b/s/w/ir/cache/builder/src/third_party/llvm-build/Release+Asserts/lib/clang/20"
 "-isysroot" 
"/b/s/w/ir/cache/builder/src/third_party/llvm/clang/test/Driver/Inputs/basic_android_tree/sysroot"
 "-internal-isystem" 
"/b/s/w/ir/cache/builder/src/third_party/llvm-build/Release+Asserts/lib/clang/20/include"
 "-internal-isystem" 
"/b/s/w/ir/cache/builder/src/third_party/llvm/clang/test/Driver/Inputs/basic_android_tree/sysroot/usr/local/include"
 "-internal-externc-isystem" 
"/b/s/w/ir/cache/builder/src/third_party/llvm/clang/test/Driver/Inputs/basic_android_tree/sysroot/include"
 "-internal-externc-isystem" 
"/b/s/w/ir/cache/builder/src/third_party/llvm/clang/test/Driver/Inputs/basic_android_tree/sysroot/usr/include"
 "-ferror-limit" "19" "-femulated-tls" "-fno-signed-char" 
"-fgnuc-version=4.2.1" "-fskip-odr-check-in-gmf" "-fsanitize=address" 
"-fsanitize-system-ignorelist=/b/s/w/ir/cache/builder/src/third_party/llvm-build/Release+Asserts/lib/clang/20/share/asan_ignorelist.txt"
 "-fno-sanitize-memory-param-retval" "-fsanitize-address-use-after-scope" 
"-fsanitize-address-globals-dead-stripping" "-fno-assume-sane-operator-new" 
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o" 
"/b/s/w/ir/x/t/lit-tmp-oclbdku5/sanitizer-ld-7c3b22.o" "-x" "c" 
"/b/s/w/ir/cache/builder/src/third_party/llvm/clang/test/Driver/sanitizer-ld.c"
















 

[clang-tools-extra] [clang-tidy][doc] mention smart ptr in bugprone-unhandled-self-assignment.WarnOnlyIfThisHasSuspiciousField option (PR #121316)

2024-12-30 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti approved this pull request.


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


[clang-tools-extra] [clang-tidy][doc] mention smart ptr in bugprone-unhandled-self-assignment.WarnOnlyIfThisHasSuspiciousField option (PR #121316)

2024-12-30 Thread Congcong Cai via cfe-commits

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


[clang-tools-extra] 08f7724 - [clang-tidy][doc] mention smart ptr in bugprone-unhandled-self-assignment.WarnOnlyIfThisHasSuspiciousField option (#121316)

2024-12-30 Thread via cfe-commits

Author: Congcong Cai
Date: 2024-12-31T05:11:13+08:00
New Revision: 08f77241c0d90737f1818b948978876a0822be32

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

LOG: [clang-tidy][doc] mention smart ptr in 
bugprone-unhandled-self-assignment.WarnOnlyIfThisHasSuspiciousField option 
(#121316)

Added: 


Modified: 

clang-tools-extra/docs/clang-tidy/checks/bugprone/unhandled-self-assignment.rst

Removed: 




diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unhandled-self-assignment.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unhandled-self-assignment.rst
index dee139861c8cfe..d3cdd5a12fdca3 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unhandled-self-assignment.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unhandled-self-assignment.rst
@@ -120,5 +120,7 @@ temporary object into ``this`` (needs a move assignment 
operator):
 
 .. option:: WarnOnlyIfThisHasSuspiciousField
 
-  When `true`, the check will warn only if the container class of the copy 
assignment operator
-  has any suspicious fields (pointer or C array). This option is set to `true` 
by default.
+  When `true`, the check will warn only if the container class of the copy
+  assignment operator has any suspicious fields (pointer, C array and C++ smart
+  pointer).
+  This option is set to `true` by default.



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


[clang] [clang][transformer] Allow usage of applyFirst with rewriteDescendants (PR #117658)

2024-12-30 Thread Yitzhak Mandelbaum via cfe-commits

ymand wrote:

> Yes, indeed the original match happens in separate context, but all contexts 
> share one `NodesMap`, which values are overriden with a consecutive match 
> ('clash').

I see -- I'd missed the reuse of the MatchResult. Now that I understand the 
problem, I don't think that you're suggestion will fix it.  The problem is that 
the IDs of the matchers are unique between different matchers, but not 
necessarily unique within a rule, because you can trivially reuse a matcher 
twice within the rule. So, we need a different source of uniqueness.

I don't have a quick fix offhand -- I think we'd probably want to package the 
ID with the rule case and then use a unique-ID generator (e.g. a global int 
variable) when we create the cases. But, in the meantime, if you want to 
unblock your progress, you could combine the position-based ID with the 
matcher-based ID, which would significantly decrease the likelihood of 
conflict. But, if you do that, please include a simple test that demonstrates 
the problem.

thanks!

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


[clang] [llvm] [Driver][clang-linker-wrapper] Add initial support for OpenMP offloading to generic SPIR-V (PR #120145)

2024-12-30 Thread Nick Sarnie via cfe-commits

https://github.com/sarnex updated 
https://github.com/llvm/llvm-project/pull/120145

>From e1b9b503b1e9b8ebf5a9c94dcefd0c47ab009019 Mon Sep 17 00:00:00 2001
From: "Sarnie, Nick" 
Date: Mon, 16 Dec 2024 09:25:44 -0800
Subject: [PATCH 01/10] [Driver][clang-linker-wrapper] Add initial support for
 OpenMP offloading to generic SPIR-V

This is the first of a series of patches to add support for OpenMP offloading 
to SPIR-V through liboffload with the first intended target being Intel GPUs. 
This patch implements the basic driver and `clang-linker-wrapper` work for JIT 
mode. There are still many missing pieces, so this is not yet usable.

We introduce `spirv64-intel-unknown` as the only currently supported triple. 
The user-facing argument to enable offloading will be `-fopenmp 
-fopenmp-targets=spirv64-intel`

Add a new `SPIRVOpenMPToolChain` toolchain based on the existing general SPIR-V 
toolchain which will call all the required SPIR-V tools as well as add the 
device RTL as an argument to the linker.

As there is no production quality SPIR-V linker available, manually create an 
ELF binary containing the offloading image in a way that fits into the existing 
`liboffload` infrastructure. This ELF will eventually be passed to a runtime 
plugin that interacts with the Intel GPU runtime.

There is also a small fix to an issue I found when trying to assemble SPIR-V 
when in text format.

Signed-off-by: Sarnie, Nick 
---
 clang/include/clang/Driver/Options.td |  2 +
 clang/lib/Driver/CMakeLists.txt   |  1 +
 clang/lib/Driver/Driver.cpp   | 40 +++--
 clang/lib/Driver/ToolChains/CommonArgs.cpp|  9 +-
 clang/lib/Driver/ToolChains/SPIRV.cpp |  5 +-
 clang/lib/Driver/ToolChains/SPIRV.h   |  2 +-
 clang/lib/Driver/ToolChains/SPIRVOpenMP.cpp   | 36 
 clang/lib/Driver/ToolChains/SPIRVOpenMP.h | 29 +++
 clang/lib/Frontend/CompilerInvocation.cpp |  1 +
 .../lib/libomptarget-spirv64-spirv64-intel.bc |  0
 clang/test/Driver/spirv-openmp-toolchain.c| 71 +++
 clang/test/Driver/spirv-toolchain.cl  |  6 +-
 .../ClangLinkerWrapper.cpp| 17 ++--
 .../llvm/Frontend/Offloading/Utility.h|  5 ++
 llvm/include/llvm/TargetParser/Triple.h   |  3 +-
 llvm/lib/Frontend/Offloading/CMakeLists.txt   |  1 +
 llvm/lib/Frontend/Offloading/Utility.cpp  | 86 +++
 llvm/lib/TargetParser/Triple.cpp  |  2 +
 18 files changed, 296 insertions(+), 20 deletions(-)
 create mode 100644 clang/lib/Driver/ToolChains/SPIRVOpenMP.cpp
 create mode 100644 clang/lib/Driver/ToolChains/SPIRVOpenMP.h
 create mode 100644 
clang/test/Driver/Inputs/spirv-openmp/lib/libomptarget-spirv64-spirv64-intel.bc
 create mode 100644 clang/test/Driver/spirv-openmp-toolchain.c

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index bed2a56b003512..a46fa1353af587 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1493,6 +1493,8 @@ def libomptarget_amdgcn_bc_path_EQ : Joined<["--"], 
"libomptarget-amdgcn-bc-path
   HelpText<"Path to libomptarget-amdgcn bitcode library">, 
Alias;
 def libomptarget_nvptx_bc_path_EQ : Joined<["--"], 
"libomptarget-nvptx-bc-path=">, Group,
   HelpText<"Path to libomptarget-nvptx bitcode library">;
+def libomptarget_spirv_bc_path_EQ : Joined<["--"], 
"libomptarget-spirv-bc-path=">, Group,
+  HelpText<"Path to libomptarget-spirv bitcode library">;
 def dD : Flag<["-"], "dD">, Group, Visibility<[ClangOption, 
CC1Option]>,
   HelpText<"Print macro definitions in -E mode in addition to normal output">;
 def dI : Flag<["-"], "dI">, Group, Visibility<[ClangOption, 
CC1Option]>,
diff --git a/clang/lib/Driver/CMakeLists.txt b/clang/lib/Driver/CMakeLists.txt
index 4fd10bf671512f..57d04c3fefa843 100644
--- a/clang/lib/Driver/CMakeLists.txt
+++ b/clang/lib/Driver/CMakeLists.txt
@@ -77,6 +77,7 @@ add_clang_library(clangDriver
   ToolChains/RISCVToolchain.cpp
   ToolChains/Solaris.cpp
   ToolChains/SPIRV.cpp
+  ToolChains/SPIRVOpenMP.cpp
   ToolChains/TCE.cpp
   ToolChains/UEFI.cpp
   ToolChains/VEToolchain.cpp
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index dc84c1b9d1cc4e..c74a474f487d95 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -43,6 +43,7 @@
 #include "ToolChains/PS4CPU.h"
 #include "ToolChains/RISCVToolchain.h"
 #include "ToolChains/SPIRV.h"
+#include "ToolChains/SPIRVOpenMP.h"
 #include "ToolChains/Solaris.h"
 #include "ToolChains/TCE.h"
 #include "ToolChains/UEFI.h"
@@ -166,6 +167,20 @@ getHIPOffloadTargetTriple(const Driver &D, const ArgList 
&Args) {
   return std::nullopt;
 }
 
+static std::optional
+getSPIRVOffloadTargetTriple(const Driver &D, const ArgList &Args) {
+  if (!Args.hasArg(options::OPT_offload_EQ))
+return llvm::Triple(
+"spirv64-intel"); // Only vendor "intel" is currently supported.
+  auto TT = getOffloadTargetTri

[clang] [clang] Absoultify paths in dependency file output (PR #117458)

2024-12-30 Thread Fangrui Song via cfe-commits

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


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


[clang] [clang] Absoultify paths in dependency file output (PR #117458)

2024-12-30 Thread Fangrui Song via cfe-commits


@@ -312,11 +314,18 @@ void 
DependencyFileGenerator::finishedMainFile(DiagnosticsEngine &Diags) {
 /// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
 /// 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
 /// for Windows file-naming info.
-static void PrintFilename(raw_ostream &OS, StringRef Filename,
+static void PrintFilename(raw_ostream &OS, llvm::vfs::FileSystem *FS,
+  StringRef Filename,
   DependencyOutputFormat OutputFormat) {
   // Convert filename to platform native path
   llvm::SmallString<256> NativePath;
   llvm::sys::path::native(Filename.str(), NativePath);
+  // Make path absolute. Make and Ninja canonicalize paths without checking for
+  // symbolic links in the path, for performance concerns.
+  // If there is something like `/bin/../lib64` -> `/usr/lib64`
+  // (where `/bin` links to `/usr/bin`), Make will see them as `/lib64`.
+  if (FS != nullptr && llvm::sys::path::is_absolute(NativePath))
+FS->makeAbsolute(NativePath);

MaskRay wrote:

`makeAbsolute` does not resolve an absolute path, so this does not work as 
intended.

`Make path absolute` => `Resolve an absolute path`?

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


[clang] [clang] Absoultify paths in dependency file output (PR #117458)

2024-12-30 Thread Fangrui Song via cfe-commits


@@ -312,11 +314,18 @@ void 
DependencyFileGenerator::finishedMainFile(DiagnosticsEngine &Diags) {
 /// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
 /// 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
 /// for Windows file-naming info.
-static void PrintFilename(raw_ostream &OS, StringRef Filename,
+static void PrintFilename(raw_ostream &OS, llvm::vfs::FileSystem *FS,
+  StringRef Filename,
   DependencyOutputFormat OutputFormat) {
   // Convert filename to platform native path
   llvm::SmallString<256> NativePath;
   llvm::sys::path::native(Filename.str(), NativePath);
+  // Make path absolute. Make and Ninja canonicalize paths without checking for
+  // symbolic links in the path, for performance concerns.
+  // If there is something like `/bin/../lib64` -> `/usr/lib64`
+  // (where `/bin` links to `/usr/bin`), Make will see them as `/lib64`.
+  if (FS != nullptr && llvm::sys::path::is_absolute(NativePath))
+FS->makeAbsolute(NativePath);

MaskRay wrote:

You can make the function `functionName` instead of `FunctionName` while 
updating its signature.

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


[clang] [llvm] [Driver][clang-linker-wrapper] Add initial support for OpenMP offloading to generic SPIR-V (PR #120145)

2024-12-30 Thread Nick Sarnie via cfe-commits

https://github.com/sarnex updated 
https://github.com/llvm/llvm-project/pull/120145

>From e1b9b503b1e9b8ebf5a9c94dcefd0c47ab009019 Mon Sep 17 00:00:00 2001
From: "Sarnie, Nick" 
Date: Mon, 16 Dec 2024 09:25:44 -0800
Subject: [PATCH 01/11] [Driver][clang-linker-wrapper] Add initial support for
 OpenMP offloading to generic SPIR-V

This is the first of a series of patches to add support for OpenMP offloading 
to SPIR-V through liboffload with the first intended target being Intel GPUs. 
This patch implements the basic driver and `clang-linker-wrapper` work for JIT 
mode. There are still many missing pieces, so this is not yet usable.

We introduce `spirv64-intel-unknown` as the only currently supported triple. 
The user-facing argument to enable offloading will be `-fopenmp 
-fopenmp-targets=spirv64-intel`

Add a new `SPIRVOpenMPToolChain` toolchain based on the existing general SPIR-V 
toolchain which will call all the required SPIR-V tools as well as add the 
device RTL as an argument to the linker.

As there is no production quality SPIR-V linker available, manually create an 
ELF binary containing the offloading image in a way that fits into the existing 
`liboffload` infrastructure. This ELF will eventually be passed to a runtime 
plugin that interacts with the Intel GPU runtime.

There is also a small fix to an issue I found when trying to assemble SPIR-V 
when in text format.

Signed-off-by: Sarnie, Nick 
---
 clang/include/clang/Driver/Options.td |  2 +
 clang/lib/Driver/CMakeLists.txt   |  1 +
 clang/lib/Driver/Driver.cpp   | 40 +++--
 clang/lib/Driver/ToolChains/CommonArgs.cpp|  9 +-
 clang/lib/Driver/ToolChains/SPIRV.cpp |  5 +-
 clang/lib/Driver/ToolChains/SPIRV.h   |  2 +-
 clang/lib/Driver/ToolChains/SPIRVOpenMP.cpp   | 36 
 clang/lib/Driver/ToolChains/SPIRVOpenMP.h | 29 +++
 clang/lib/Frontend/CompilerInvocation.cpp |  1 +
 .../lib/libomptarget-spirv64-spirv64-intel.bc |  0
 clang/test/Driver/spirv-openmp-toolchain.c| 71 +++
 clang/test/Driver/spirv-toolchain.cl  |  6 +-
 .../ClangLinkerWrapper.cpp| 17 ++--
 .../llvm/Frontend/Offloading/Utility.h|  5 ++
 llvm/include/llvm/TargetParser/Triple.h   |  3 +-
 llvm/lib/Frontend/Offloading/CMakeLists.txt   |  1 +
 llvm/lib/Frontend/Offloading/Utility.cpp  | 86 +++
 llvm/lib/TargetParser/Triple.cpp  |  2 +
 18 files changed, 296 insertions(+), 20 deletions(-)
 create mode 100644 clang/lib/Driver/ToolChains/SPIRVOpenMP.cpp
 create mode 100644 clang/lib/Driver/ToolChains/SPIRVOpenMP.h
 create mode 100644 
clang/test/Driver/Inputs/spirv-openmp/lib/libomptarget-spirv64-spirv64-intel.bc
 create mode 100644 clang/test/Driver/spirv-openmp-toolchain.c

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index bed2a56b003512..a46fa1353af587 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1493,6 +1493,8 @@ def libomptarget_amdgcn_bc_path_EQ : Joined<["--"], 
"libomptarget-amdgcn-bc-path
   HelpText<"Path to libomptarget-amdgcn bitcode library">, 
Alias;
 def libomptarget_nvptx_bc_path_EQ : Joined<["--"], 
"libomptarget-nvptx-bc-path=">, Group,
   HelpText<"Path to libomptarget-nvptx bitcode library">;
+def libomptarget_spirv_bc_path_EQ : Joined<["--"], 
"libomptarget-spirv-bc-path=">, Group,
+  HelpText<"Path to libomptarget-spirv bitcode library">;
 def dD : Flag<["-"], "dD">, Group, Visibility<[ClangOption, 
CC1Option]>,
   HelpText<"Print macro definitions in -E mode in addition to normal output">;
 def dI : Flag<["-"], "dI">, Group, Visibility<[ClangOption, 
CC1Option]>,
diff --git a/clang/lib/Driver/CMakeLists.txt b/clang/lib/Driver/CMakeLists.txt
index 4fd10bf671512f..57d04c3fefa843 100644
--- a/clang/lib/Driver/CMakeLists.txt
+++ b/clang/lib/Driver/CMakeLists.txt
@@ -77,6 +77,7 @@ add_clang_library(clangDriver
   ToolChains/RISCVToolchain.cpp
   ToolChains/Solaris.cpp
   ToolChains/SPIRV.cpp
+  ToolChains/SPIRVOpenMP.cpp
   ToolChains/TCE.cpp
   ToolChains/UEFI.cpp
   ToolChains/VEToolchain.cpp
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index dc84c1b9d1cc4e..c74a474f487d95 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -43,6 +43,7 @@
 #include "ToolChains/PS4CPU.h"
 #include "ToolChains/RISCVToolchain.h"
 #include "ToolChains/SPIRV.h"
+#include "ToolChains/SPIRVOpenMP.h"
 #include "ToolChains/Solaris.h"
 #include "ToolChains/TCE.h"
 #include "ToolChains/UEFI.h"
@@ -166,6 +167,20 @@ getHIPOffloadTargetTriple(const Driver &D, const ArgList 
&Args) {
   return std::nullopt;
 }
 
+static std::optional
+getSPIRVOffloadTargetTriple(const Driver &D, const ArgList &Args) {
+  if (!Args.hasArg(options::OPT_offload_EQ))
+return llvm::Triple(
+"spirv64-intel"); // Only vendor "intel" is currently supported.
+  auto TT = getOffloadTargetTri

[clang] [Clang][Driver][AMDGPU] Add missing space in missing device-libs error message (PR #121335)

2024-12-30 Thread Juan Manuel Martinez Caamaño via cfe-commits

https://github.com/jmmartinez created 
https://github.com/llvm/llvm-project/pull/121335

Before/After:

cannot find ROCm device **libraryfor** ABI version 6
cannot find ROCm device **library for** ABI version 6

From b43f459b681c88e697cdd18a9836e967ffe83733 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Juan=20Manuel=20Martinez=20Caama=C3=B1o?= 
Date: Mon, 30 Dec 2024 14:23:29 +0100
Subject: [PATCH] [Clang][Driver][AMDGPU] Add missing space in missing
 device-libs error message

Before/After:

cannot find ROCm device **libraryfor** ABI version 6
cannot find ROCm device **library for** ABI version 6
---
 clang/include/clang/Basic/DiagnosticDriverKinds.td | 2 +-
 clang/test/Driver/hip-device-libs.hip  | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 5155b23d151c04..42c39ac6606c7f 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -67,7 +67,7 @@ def err_drv_no_cuda_libdevice : Error<
   "libdevice">;
 
 def err_drv_no_rocm_device_lib : Error<
-  "cannot find ROCm device library%select{| for %1|for ABI version %1}0; 
provide its path via "
+  "cannot find ROCm device library%select{| for %1| for ABI version %1}0; 
provide its path via "
   "'--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to build "
   "without ROCm device library">;
 def err_drv_no_hip_runtime : Error<
diff --git a/clang/test/Driver/hip-device-libs.hip 
b/clang/test/Driver/hip-device-libs.hip
index 6f1d31508e3302..317fd792426972 100644
--- a/clang/test/Driver/hip-device-libs.hip
+++ b/clang/test/Driver/hip-device-libs.hip
@@ -253,5 +253,5 @@
 // NOABI4-NOT: error:
 // NOABI4-NOT: "-mlink-builtin-bitcode" "{{.*}}oclc_abi_version_400.bc"
 // NOABI4-NOT: "-mlink-builtin-bitcode" "{{.*}}oclc_abi_version_500.bc"
-// NOABI5: error: cannot find ROCm device libraryfor ABI version 5; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library
-// NOABI6: error: cannot find ROCm device libraryfor ABI version 6; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library
+// NOABI5: error: cannot find ROCm device library for ABI version 5; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library
+// NOABI6: error: cannot find ROCm device library for ABI version 6; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library

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


[clang] [Clang][Driver][AMDGPU] Add missing space in missing device-libs error message (PR #121335)

2024-12-30 Thread Juan Manuel Martinez Caamaño via cfe-commits

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


[clang] [Clang][Driver][AMDGPU] Add missing space in missing device-libs error message (PR #121335)

2024-12-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Juan Manuel Martinez Caamaño (jmmartinez)


Changes

Before/After:
> cannot find ROCm device **libraryfor** ABI version 6
> cannot find ROCm device **library for** ABI version 6

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


2 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+1-1) 
- (modified) clang/test/Driver/hip-device-libs.hip (+2-2) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 5155b23d151c04..42c39ac6606c7f 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -67,7 +67,7 @@ def err_drv_no_cuda_libdevice : Error<
   "libdevice">;
 
 def err_drv_no_rocm_device_lib : Error<
-  "cannot find ROCm device library%select{| for %1|for ABI version %1}0; 
provide its path via "
+  "cannot find ROCm device library%select{| for %1| for ABI version %1}0; 
provide its path via "
   "'--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to build "
   "without ROCm device library">;
 def err_drv_no_hip_runtime : Error<
diff --git a/clang/test/Driver/hip-device-libs.hip 
b/clang/test/Driver/hip-device-libs.hip
index 6f1d31508e3302..317fd792426972 100644
--- a/clang/test/Driver/hip-device-libs.hip
+++ b/clang/test/Driver/hip-device-libs.hip
@@ -253,5 +253,5 @@
 // NOABI4-NOT: error:
 // NOABI4-NOT: "-mlink-builtin-bitcode" "{{.*}}oclc_abi_version_400.bc"
 // NOABI4-NOT: "-mlink-builtin-bitcode" "{{.*}}oclc_abi_version_500.bc"
-// NOABI5: error: cannot find ROCm device libraryfor ABI version 5; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library
-// NOABI6: error: cannot find ROCm device libraryfor ABI version 6; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library
+// NOABI5: error: cannot find ROCm device library for ABI version 5; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library
+// NOABI6: error: cannot find ROCm device library for ABI version 6; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library

``




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


[clang] [Clang][Driver][AMDGPU] Add missing space in missing device-libs error message (PR #121335)

2024-12-30 Thread via cfe-commits

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


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


[clang] [Clang] Add GCC's __builtin_stack_address() to Clang. (PR #121332)

2024-12-30 Thread via cfe-commits

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


[clang] ff936ce - [Clang][Driver][AMDGPU] Add missing space in missing device-libs error message (#121335)

2024-12-30 Thread via cfe-commits

Author: Juan Manuel Martinez Caamaño
Date: 2024-12-30T15:07:28+01:00
New Revision: ff936ce62bda2f9148575caae527cc4c6ab282a5

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

LOG: [Clang][Driver][AMDGPU] Add missing space in missing device-libs error 
message (#121335)

Before/After:
> cannot find ROCm device **libraryfor** ABI version 6
> cannot find ROCm device **library for** ABI version 6

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/test/Driver/hip-device-libs.hip

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 5155b23d151c04..42c39ac6606c7f 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -67,7 +67,7 @@ def err_drv_no_cuda_libdevice : Error<
   "libdevice">;
 
 def err_drv_no_rocm_device_lib : Error<
-  "cannot find ROCm device library%select{| for %1|for ABI version %1}0; 
provide its path via "
+  "cannot find ROCm device library%select{| for %1| for ABI version %1}0; 
provide its path via "
   "'--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to build "
   "without ROCm device library">;
 def err_drv_no_hip_runtime : Error<

diff  --git a/clang/test/Driver/hip-device-libs.hip 
b/clang/test/Driver/hip-device-libs.hip
index 6f1d31508e3302..317fd792426972 100644
--- a/clang/test/Driver/hip-device-libs.hip
+++ b/clang/test/Driver/hip-device-libs.hip
@@ -253,5 +253,5 @@
 // NOABI4-NOT: error:
 // NOABI4-NOT: "-mlink-builtin-bitcode" "{{.*}}oclc_abi_version_400.bc"
 // NOABI4-NOT: "-mlink-builtin-bitcode" "{{.*}}oclc_abi_version_500.bc"
-// NOABI5: error: cannot find ROCm device libraryfor ABI version 5; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library
-// NOABI6: error: cannot find ROCm device libraryfor ABI version 6; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library
+// NOABI5: error: cannot find ROCm device library for ABI version 5; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library
+// NOABI6: error: cannot find ROCm device library for ABI version 6; provide 
its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to 
build without ROCm device library



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


[clang] [Clang][Driver][AMDGPU] Add missing space in missing device-libs error message (PR #121335)

2024-12-30 Thread Juan Manuel Martinez Caamaño via cfe-commits

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


[clang] Propagate lifetimebound from formal parameters to those in the canonical declaration and use that for analysis (PR #107627)

2024-12-30 Thread via cfe-commits

https://github.com/higher-performance updated 
https://github.com/llvm/llvm-project/pull/107627

>From 4dfad6c21220585a6a0f796f5699128ca7c4615b Mon Sep 17 00:00:00 2001
From: higher-performance 
Date: Fri, 6 Sep 2024 14:16:15 -0400
Subject: [PATCH 1/3] Propagate lifetimebound from formal parameters to those
 in the canonical declaration, then use the canonical declaration for analysis

Note that this doesn't handle the implicit 'this' parameter; that can be 
addressed in a separate commit.
---
 clang/lib/Sema/CheckExprLifetime.cpp  | 20 ++---
 clang/lib/Sema/SemaAttr.cpp   | 34 +++
 clang/test/SemaCXX/attr-lifetimebound.cpp |  5 
 3 files changed, 37 insertions(+), 22 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 7109de03cadd12..4befd703beb422 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -645,9 +645,9 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 }
   }
 
-  for (unsigned I = 0,
-N = std::min(Callee->getNumParams(), Args.size());
-   I != N; ++I) {
+  const FunctionDecl *CanonCallee = Callee->getCanonicalDecl();
+  unsigned NP = std::min(Callee->getNumParams(), CanonCallee->getNumParams());
+  for (unsigned I = 0, N = std::min(NP, Args.size()); I != N; ++I) {
 Expr *Arg = Args[I];
 RevertToOldSizeRAII RAII(Path);
 if (auto *DAE = dyn_cast(Arg)) {
@@ -655,11 +655,11 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   {IndirectLocalPathEntry::DefaultArg, DAE, DAE->getParam()});
   Arg = DAE->getExpr();
 }
-if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr())
-  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+if (CheckCoroCall || 
CanonCallee->getParamDecl(I)->hasAttr())
+  VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
 else if (const auto *CaptureAttr =
- Callee->getParamDecl(I)->getAttr();
- CaptureAttr && isa(Callee) &&
+ 
CanonCallee->getParamDecl(I)->getAttr();
+ CaptureAttr && isa(CanonCallee) &&
  llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
return ArgIdx == LifetimeCaptureByAttr::THIS;
  }))
@@ -676,11 +676,11 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   // `lifetimebound` and shares the same code path. This implies the 
emitted
   // diagnostics will be emitted under `-Wdangling`, not
   // `-Wdangling-capture`.
-  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+  VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
 else if (EnableGSLAnalysis && I == 0) {
   // Perform GSL analysis for the first argument
-  if (shouldTrackFirstArgument(Callee)) {
-VisitGSLPointerArg(Callee, Arg);
+  if (shouldTrackFirstArgument(CanonCallee)) {
+VisitGSLPointerArg(CanonCallee, Arg);
   } else if (auto *Ctor = dyn_cast(Call);
  Ctor && shouldTrackFirstArgumentForConstructor(Ctor)) {
 VisitGSLPointerArg(Ctor->getConstructor(), Arg);
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index 44485e71d57a01..3fd122b20d7b12 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -217,7 +217,8 @@ void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl 
*Record) {
 }
 
 void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
-  if (FD->getNumParams() == 0)
+  unsigned NumParams = FD->getNumParams();
+  if (NumParams == 0)
 return;
 
   if (unsigned BuiltinID = FD->getBuiltinID()) {
@@ -239,18 +240,13 @@ void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
 default:
   break;
 }
-return;
-  }
-  if (auto *CMD = dyn_cast(FD)) {
-const auto *CRD = CMD->getParent();
-if (!CRD->isInStdNamespace() || !CRD->getIdentifier())
-  return;
-
-if (isa(CMD)) {
+  } else if (auto *CMD = dyn_cast(FD)) {
+const CXXRecordDecl *CRD = CMD->getParent();
+if (CRD->isInStdNamespace() && CRD->getIdentifier() &&
+isa(CMD)) {
   auto *Param = CMD->getParamDecl(0);
-  if (Param->hasAttr())
-return;
-  if (CRD->getName() == "basic_string_view" &&
+  if (!Param->hasAttr() &&
+  CRD->getName() == "basic_string_view" &&
   Param->getType()->isPointerType()) {
 // construct from a char array pointed by a pointer.
 //   basic_string_view(const CharT* s);
@@ -266,6 +262,20 @@ void Sema::inferLifetimeBoundAttribute(FunctionDecl *FD) {
   LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
   }
 }
+  } else if (auto *CanonDecl = FD->getCanonicalDecl(); FD != CanonDecl) {
+// Propagate the lifetimebound attribute from parameters to the canonical
+// declaration.
+// Note that this doesn't include the implicit 'this' p

[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits


@@ -28314,6 +28320,116 @@ TEST_F(FormatTest, KeepFormFeed) {
Style);
 }
 
+TEST_F(FormatTest, ShortNamespacesOption) {
+  auto BaseStyle = getLLVMStyle();
+  BaseStyle.AllowShortNamespacesOnASingleLine = true;
+  BaseStyle.FixNamespaceComments = false;
+  BaseStyle.CompactNamespaces = true;
+
+  auto Style = BaseStyle;

owenca wrote:

```suggestion
  auto Style = getLLVMStyle();
  Style.AllowShortNamespacesOnASingleLine = true;
  Style.CompactNamespaces = true;
  Style.FixNamespaceComments = false;
```

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


[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits


@@ -28314,6 +28320,116 @@ TEST_F(FormatTest, KeepFormFeed) {
Style);
 }
 
+TEST_F(FormatTest, ShortNamespacesOption) {
+  auto BaseStyle = getLLVMStyle();
+  BaseStyle.AllowShortNamespacesOnASingleLine = true;
+  BaseStyle.FixNamespaceComments = false;
+  BaseStyle.CompactNamespaces = true;
+
+  auto Style = BaseStyle;
+
+  // Basic functionality.
+  verifyFormat("namespace foo { class bar; }", Style);
+  verifyFormat("namespace foo::bar { class baz; }", Style);
+  verifyFormat("namespace { class bar; }", Style);
+  verifyFormat("namespace foo {\n"
+   "class bar;\n"
+   "class baz;\n"
+   "}",
+   Style);
+
+  // Trailing comments prevent merging.
+  verifyFormat("namespace foo { namespace baz {\n"
+   "class qux;\n"
+   "} // comment\n"
+   "}",
+   Style);
+
+  // Make sure code doesn't walk too far on unbalanced code.
+  verifyFormat("namespace foo {", Style);
+  verifyFormat("namespace foo {\n"
+   "class baz;",
+   Style);
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }",
+   Style);
+
+  // Nested namespaces.
+  verifyFormat("namespace foo { namespace bar { class baz; } }", Style);
+
+  // Without CompactNamespaces, we won't merge consecutive namespace
+  // declarations
+  Style.CompactNamespaces = false;
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }\n"
+   "}",
+   Style);
+
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }\n"
+   "namespace qux { class quux; }\n"
+   "}",
+   Style);
+
+  Style = BaseStyle;

owenca wrote:

```suggestion
  Style.CompactNamespaces = true;
```

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


[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits


@@ -28314,6 +28320,116 @@ TEST_F(FormatTest, KeepFormFeed) {
Style);
 }
 
+TEST_F(FormatTest, ShortNamespacesOption) {
+  auto BaseStyle = getLLVMStyle();
+  BaseStyle.AllowShortNamespacesOnASingleLine = true;
+  BaseStyle.FixNamespaceComments = false;
+  BaseStyle.CompactNamespaces = true;
+
+  auto Style = BaseStyle;
+
+  // Basic functionality.
+  verifyFormat("namespace foo { class bar; }", Style);
+  verifyFormat("namespace foo::bar { class baz; }", Style);
+  verifyFormat("namespace { class bar; }", Style);
+  verifyFormat("namespace foo {\n"
+   "class bar;\n"
+   "class baz;\n"
+   "}",
+   Style);
+
+  // Trailing comments prevent merging.
+  verifyFormat("namespace foo { namespace baz {\n"
+   "class qux;\n"
+   "} // comment\n"
+   "}",
+   Style);
+
+  // Make sure code doesn't walk too far on unbalanced code.
+  verifyFormat("namespace foo {", Style);
+  verifyFormat("namespace foo {\n"
+   "class baz;",
+   Style);
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }",
+   Style);
+
+  // Nested namespaces.
+  verifyFormat("namespace foo { namespace bar { class baz; } }", Style);
+
+  // Without CompactNamespaces, we won't merge consecutive namespace
+  // declarations

owenca wrote:

```suggestion
  // declarations.
```

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


[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits


@@ -28314,6 +28320,116 @@ TEST_F(FormatTest, KeepFormFeed) {
Style);
 }
 
+TEST_F(FormatTest, ShortNamespacesOption) {
+  auto BaseStyle = getLLVMStyle();
+  BaseStyle.AllowShortNamespacesOnASingleLine = true;
+  BaseStyle.FixNamespaceComments = false;
+  BaseStyle.CompactNamespaces = true;
+
+  auto Style = BaseStyle;
+
+  // Basic functionality.
+  verifyFormat("namespace foo { class bar; }", Style);
+  verifyFormat("namespace foo::bar { class baz; }", Style);
+  verifyFormat("namespace { class bar; }", Style);
+  verifyFormat("namespace foo {\n"
+   "class bar;\n"
+   "class baz;\n"
+   "}",
+   Style);
+
+  // Trailing comments prevent merging.
+  verifyFormat("namespace foo { namespace baz {\n"
+   "class qux;\n"
+   "} // comment\n"
+   "}",
+   Style);
+
+  // Make sure code doesn't walk too far on unbalanced code.
+  verifyFormat("namespace foo {", Style);
+  verifyFormat("namespace foo {\n"
+   "class baz;",
+   Style);
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }",
+   Style);
+
+  // Nested namespaces.
+  verifyFormat("namespace foo { namespace bar { class baz; } }", Style);
+
+  // Without CompactNamespaces, we won't merge consecutive namespace
+  // declarations
+  Style.CompactNamespaces = false;
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }\n"
+   "}",
+   Style);
+
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }\n"
+   "namespace qux { class quux; }\n"
+   "}",
+   Style);
+
+  Style = BaseStyle;
+
+  // Varying inner content.
+  verifyFormat("namespace foo {\n"
+   "int f() { return 5; }\n"
+   "}",
+   Style);
+  verifyFormat("namespace foo { template  struct bar; }", Style);
+  verifyFormat("namespace foo { constexpr int num = 42; }", Style);
+
+  // Validate nested namespace wrapping scenarios around the ColumnLimit.
+  Style.ColumnLimit = 64;
+
+  // Validate just under the ColumnLimit.
+  verifyFormat(
+  "namespace foo { namespace bar { namespace baz { class qux; } } }",
+  Style);
+
+  // Validate just over the ColumnLimit.
+  verifyFormat("namespace foo { namespace baar { namespace baaz {\n"
+   "class quux;\n"
+   "}}}",
+   Style);
+
+  verifyFormat(
+  "namespace foo { namespace bar { namespace baz { namespace qux {\n"
+  "class quux;\n"
+  "",
+  Style);
+
+  // Validate that the ColumnLimit logic accounts for trailing content as well.
+  verifyFormat("namespace foo { namespace bar { class qux; } } // extra",
+   Style);
+
+  verifyFormat("namespace foo { namespace bar { namespace baz {\n"
+   "class qux;\n"
+   "}}} // extra",
+   Style);
+
+  // FIXME: Ideally AllowShortNamespacesOnASingleLine would disable the 
trailing
+  // namespace comment from 'FixNamespaceComments', as it's not really 
necessary
+  // in this scenario, but the two options work at very different layers of the
+  // formatter, so I'm not sure how to make them interact.
+  //
+  // As it stands, the trailing comment will be added and likely make the line
+  // too long to fit within the ColumnLimit, reducing the how likely the line
+  // will still fit on a single line. The recommendation for now is to use the
+  // concatenated namespace syntax instead. e.g. 'namespace foo::bar'
+  Style = BaseStyle;
+  Style.FixNamespaceComments = true;
+

owenca wrote:

```suggestion
```

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


[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits


@@ -616,6 +626,71 @@ class LineJoiner {
 return 1;
   }
 
+  unsigned tryMergeNamespace(SmallVectorImpl::const_iterator 
I,
+ SmallVectorImpl::const_iterator 
E,
+ unsigned Limit) {
+if (Limit == 0)
+  return 0;
+assert(I[1]);

owenca wrote:

```suggestion

assert(I[1]);
```

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


[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits

https://github.com/owenca commented:

Final NFC cleanup.

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


[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits


@@ -28314,6 +28320,116 @@ TEST_F(FormatTest, KeepFormFeed) {
Style);
 }
 
+TEST_F(FormatTest, ShortNamespacesOption) {
+  auto BaseStyle = getLLVMStyle();
+  BaseStyle.AllowShortNamespacesOnASingleLine = true;
+  BaseStyle.FixNamespaceComments = false;
+  BaseStyle.CompactNamespaces = true;
+
+  auto Style = BaseStyle;
+
+  // Basic functionality.
+  verifyFormat("namespace foo { class bar; }", Style);
+  verifyFormat("namespace foo::bar { class baz; }", Style);
+  verifyFormat("namespace { class bar; }", Style);
+  verifyFormat("namespace foo {\n"
+   "class bar;\n"
+   "class baz;\n"
+   "}",
+   Style);
+
+  // Trailing comments prevent merging.
+  verifyFormat("namespace foo { namespace baz {\n"
+   "class qux;\n"
+   "} // comment\n"
+   "}",
+   Style);
+
+  // Make sure code doesn't walk too far on unbalanced code.
+  verifyFormat("namespace foo {", Style);
+  verifyFormat("namespace foo {\n"
+   "class baz;",
+   Style);
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }",
+   Style);
+
+  // Nested namespaces.
+  verifyFormat("namespace foo { namespace bar { class baz; } }", Style);
+
+  // Without CompactNamespaces, we won't merge consecutive namespace
+  // declarations
+  Style.CompactNamespaces = false;
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }\n"
+   "}",
+   Style);
+
+  verifyFormat("namespace foo {\n"
+   "namespace bar { class baz; }\n"
+   "namespace qux { class quux; }\n"
+   "}",
+   Style);
+
+  Style = BaseStyle;
+
+  // Varying inner content.
+  verifyFormat("namespace foo {\n"
+   "int f() { return 5; }\n"
+   "}",
+   Style);
+  verifyFormat("namespace foo { template  struct bar; }", Style);
+  verifyFormat("namespace foo { constexpr int num = 42; }", Style);
+
+  // Validate nested namespace wrapping scenarios around the ColumnLimit.
+  Style.ColumnLimit = 64;
+
+  // Validate just under the ColumnLimit.
+  verifyFormat(
+  "namespace foo { namespace bar { namespace baz { class qux; } } }",
+  Style);
+
+  // Validate just over the ColumnLimit.
+  verifyFormat("namespace foo { namespace baar { namespace baaz {\n"
+   "class quux;\n"
+   "}}}",
+   Style);
+
+  verifyFormat(
+  "namespace foo { namespace bar { namespace baz { namespace qux {\n"
+  "class quux;\n"
+  "",
+  Style);
+
+  // Validate that the ColumnLimit logic accounts for trailing content as well.
+  verifyFormat("namespace foo { namespace bar { class qux; } } // extra",
+   Style);
+
+  verifyFormat("namespace foo { namespace bar { namespace baz {\n"
+   "class qux;\n"
+   "}}} // extra",
+   Style);
+
+  // FIXME: Ideally AllowShortNamespacesOnASingleLine would disable the 
trailing
+  // namespace comment from 'FixNamespaceComments', as it's not really 
necessary
+  // in this scenario, but the two options work at very different layers of the
+  // formatter, so I'm not sure how to make them interact.
+  //
+  // As it stands, the trailing comment will be added and likely make the line
+  // too long to fit within the ColumnLimit, reducing the how likely the line
+  // will still fit on a single line. The recommendation for now is to use the
+  // concatenated namespace syntax instead. e.g. 'namespace foo::bar'
+  Style = BaseStyle;

owenca wrote:

```suggestion
```

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


[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits

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

>From 93eb3d89652607173f4f68fce7dcc5b2bd33f266 Mon Sep 17 00:00:00 2001
From: Galen Elias 
Date: Wed, 21 Aug 2024 16:33:42 -0700
Subject: [PATCH 01/17] clang-format: Add "AllowShortNamespacesOnASingleLine"
 option

This addresses: https://github.com/llvm/llvm-project/issues/101363
which is a resurrection of a previously opened but never completed
review: https://reviews.llvm.org/D11851

The feature is to allow code like the following not to be broken across
multiple lines:

```
namespace foo { class bar; }
namespace foo { namespace bar { class baz; } }
```

Code like this is commonly used for forward declarations, which are
ideally kept compact. This is also apparently the format that
include-what-you-use will insert for forward declarations.
---
 clang/include/clang/Format/Format.h |   5 +
 clang/lib/Format/Format.cpp |   3 +
 clang/lib/Format/UnwrappedLineFormatter.cpp |  82 ++
 clang/unittests/Format/FormatTest.cpp   | 112 
 4 files changed, 202 insertions(+)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..26cd673685942e 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -988,6 +988,11 @@ struct FormatStyle {
   /// \version 3.7
   bool AllowShortLoopsOnASingleLine;
 
+  /// If ``true``, ``namespace a { class b; }`` can be put on a single a single
+  /// line.
+  /// \version 19
+  bool AllowShortNamespacesOnASingleLine;
+
   /// Different ways to break after the function definition return type.
   /// This option is **deprecated** and is retained for backwards 
compatibility.
   enum DefinitionReturnTypeBreakingStyle : int8_t {
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..8f44e9f00212cf 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -975,6 +975,8 @@ template <> struct MappingTraits {
Style.AllowShortLambdasOnASingleLine);
 IO.mapOptional("AllowShortLoopsOnASingleLine",
Style.AllowShortLoopsOnASingleLine);
+IO.mapOptional("AllowShortNamespacesOnASingleLine",
+   Style.AllowShortNamespacesOnASingleLine);
 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
Style.AlwaysBreakAfterDefinitionReturnType);
 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
@@ -1480,6 +1482,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
   LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
   LLVMStyle.AllowShortLoopsOnASingleLine = false;
+  LLVMStyle.AllowShortNamespacesOnASingleLine = false;
   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
   LLVMStyle.AttributeMacros.push_back("__capability");
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 1804c1437fd41d..971eac1978bb71 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -420,6 +420,15 @@ class LineJoiner {
 TheLine->First != LastNonComment) {
   return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
 }
+
+if (TheLine->Last->is(tok::l_brace)) {
+  if (Style.AllowShortNamespacesOnASingleLine &&
+  TheLine->First->is(tok::kw_namespace)) {
+if (unsigned result = tryMergeNamespace(I, E, Limit))
+  return result;
+  }
+}
+
 // Try to merge a control statement block with left brace unwrapped.
 if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
 FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
@@ -616,6 +625,62 @@ class LineJoiner {
 return 1;
   }
 
+  unsigned tryMergeNamespace(SmallVectorImpl::const_iterator 
I,
+ SmallVectorImpl::const_iterator 
E,
+ unsigned Limit) {
+if (Limit == 0)
+  return 0;
+if (I[1]->InPPDirective != (*I)->InPPDirective ||
+(I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
+  return 0;
+}
+if (I + 2 == E || I[2]->Type == LT_Invalid)
+  return 0;
+
+Limit = limitConsideringMacros(I + 1, E, Limit);
+
+if (!nextTwoLinesFitInto(I, Limit))
+  return 0;
+
+// Check if it's a namespace inside a namespace, and call recursively if so
+// '3' is the sizes of the whitespace and closing brace for " _inner_ }"
+if (I[1]->First->is(tok::kw_namespace)) {
+  if (I[1]->Last->is(TT_LineComment))
+return 0;
+
+  unsigned inner_limit = Limit - I[1]->Last->TotalLength - 3;
+  unsigned inner_result = tryMergeNamespace(I + 1, E, inner_limit);
+  if (!inner_result)
+  

[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits

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

>From 93eb3d89652607173f4f68fce7dcc5b2bd33f266 Mon Sep 17 00:00:00 2001
From: Galen Elias 
Date: Wed, 21 Aug 2024 16:33:42 -0700
Subject: [PATCH 01/18] clang-format: Add "AllowShortNamespacesOnASingleLine"
 option

This addresses: https://github.com/llvm/llvm-project/issues/101363
which is a resurrection of a previously opened but never completed
review: https://reviews.llvm.org/D11851

The feature is to allow code like the following not to be broken across
multiple lines:

```
namespace foo { class bar; }
namespace foo { namespace bar { class baz; } }
```

Code like this is commonly used for forward declarations, which are
ideally kept compact. This is also apparently the format that
include-what-you-use will insert for forward declarations.
---
 clang/include/clang/Format/Format.h |   5 +
 clang/lib/Format/Format.cpp |   3 +
 clang/lib/Format/UnwrappedLineFormatter.cpp |  82 ++
 clang/unittests/Format/FormatTest.cpp   | 112 
 4 files changed, 202 insertions(+)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..26cd673685942e 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -988,6 +988,11 @@ struct FormatStyle {
   /// \version 3.7
   bool AllowShortLoopsOnASingleLine;
 
+  /// If ``true``, ``namespace a { class b; }`` can be put on a single a single
+  /// line.
+  /// \version 19
+  bool AllowShortNamespacesOnASingleLine;
+
   /// Different ways to break after the function definition return type.
   /// This option is **deprecated** and is retained for backwards 
compatibility.
   enum DefinitionReturnTypeBreakingStyle : int8_t {
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..8f44e9f00212cf 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -975,6 +975,8 @@ template <> struct MappingTraits {
Style.AllowShortLambdasOnASingleLine);
 IO.mapOptional("AllowShortLoopsOnASingleLine",
Style.AllowShortLoopsOnASingleLine);
+IO.mapOptional("AllowShortNamespacesOnASingleLine",
+   Style.AllowShortNamespacesOnASingleLine);
 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
Style.AlwaysBreakAfterDefinitionReturnType);
 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
@@ -1480,6 +1482,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
   LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
   LLVMStyle.AllowShortLoopsOnASingleLine = false;
+  LLVMStyle.AllowShortNamespacesOnASingleLine = false;
   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
   LLVMStyle.AttributeMacros.push_back("__capability");
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 1804c1437fd41d..971eac1978bb71 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -420,6 +420,15 @@ class LineJoiner {
 TheLine->First != LastNonComment) {
   return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
 }
+
+if (TheLine->Last->is(tok::l_brace)) {
+  if (Style.AllowShortNamespacesOnASingleLine &&
+  TheLine->First->is(tok::kw_namespace)) {
+if (unsigned result = tryMergeNamespace(I, E, Limit))
+  return result;
+  }
+}
+
 // Try to merge a control statement block with left brace unwrapped.
 if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
 FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
@@ -616,6 +625,62 @@ class LineJoiner {
 return 1;
   }
 
+  unsigned tryMergeNamespace(SmallVectorImpl::const_iterator 
I,
+ SmallVectorImpl::const_iterator 
E,
+ unsigned Limit) {
+if (Limit == 0)
+  return 0;
+if (I[1]->InPPDirective != (*I)->InPPDirective ||
+(I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
+  return 0;
+}
+if (I + 2 == E || I[2]->Type == LT_Invalid)
+  return 0;
+
+Limit = limitConsideringMacros(I + 1, E, Limit);
+
+if (!nextTwoLinesFitInto(I, Limit))
+  return 0;
+
+// Check if it's a namespace inside a namespace, and call recursively if so
+// '3' is the sizes of the whitespace and closing brace for " _inner_ }"
+if (I[1]->First->is(tok::kw_namespace)) {
+  if (I[1]->Last->is(TT_LineComment))
+return 0;
+
+  unsigned inner_limit = Limit - I[1]->Last->TotalLength - 3;
+  unsigned inner_result = tryMergeNamespace(I + 1, E, inner_limit);
+  if (!inner_result)
+  

[clang] [Clang][ASTMatcher] Add `dependentNameType` Matcher (PR #121263)

2024-12-30 Thread Amr Hesham via cfe-commits

AmrDeveloper wrote:

> ~@AmrDeveloper if you're not tired of these yet, I have one final one: 
> #121307~
> 
> (Update: that one's been taken by another contributor.)

Thank you, if you found another one, I will be interested to work on it, you 
can assign me directly :D

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


[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2024-12-30 Thread Owen Pan via cfe-commits

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


[clang] 486ec4b - [clang-format] Add `AllowShortNamespacesOnASingleLine` option (#105597)

2024-12-30 Thread via cfe-commits

Author: Galen Elias
Date: 2024-12-30T01:28:03-08:00
New Revision: 486ec4bd7466cda444a7da6386a1bbb2db89a33f

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

LOG: [clang-format] Add `AllowShortNamespacesOnASingleLine` option (#105597)

This fixes #101363 which is a resurrection of a previously opened but
never completed review: https://reviews.llvm.org/D11851

The feature is to allow code like the following not to be broken across
multiple lines:

```
namespace foo { class bar; }
namespace foo { namespace bar { class baz; } }
```

Code like this is commonly used for forward declarations, which are
ideally kept compact. This is also apparently the format that
include-what-you-use will insert for forward declarations.

Also, fix an off-by-one error in `CompactNamespaces` code. For nested
namespaces with 3 or more namespaces, it was incorrectly compacting
lines which were 1 or two spaces over the `ColumnLimit`, leading to
incorrect formatting results.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/unittests/Format/ConfigParseTest.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..c175436a2817a9 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2088,6 +2088,11 @@ the configuration (without a prefix: ``Auto``).
   If ``true``, ``while (true) continue;`` can be put on a single
   line.
 
+.. _AllowShortNamespacesOnASingleLine:
+
+**AllowShortNamespacesOnASingleLine** (``Boolean``) 
:versionbadge:`clang-format 20` :ref:`¶ `
+  If ``true``, ``namespace a { class b; }`` can be put on a single line.
+
 .. _AlwaysBreakAfterDefinitionReturnType:
 
 **AlwaysBreakAfterDefinitionReturnType** 
(``DefinitionReturnTypeBreakingStyle``) :versionbadge:`clang-format 3.7` 
:ref:`¶ `

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 210ccc16eeb4fc..b7da12bcf65818 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1123,6 +1123,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``AllowShortNamespacesOnASingleLine`` option.
 
 libclang
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..eefaabf9392fd7 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -988,6 +988,10 @@ struct FormatStyle {
   /// \version 3.7
   bool AllowShortLoopsOnASingleLine;
 
+  /// If ``true``, ``namespace a { class b; }`` can be put on a single line.
+  /// \version 20
+  bool AllowShortNamespacesOnASingleLine;
+
   /// Different ways to break after the function definition return type.
   /// This option is **deprecated** and is retained for backwards 
compatibility.
   enum DefinitionReturnTypeBreakingStyle : int8_t {
@@ -5168,6 +5172,8 @@ struct FormatStyle {
R.AllowShortIfStatementsOnASingleLine &&
AllowShortLambdasOnASingleLine == R.AllowShortLambdasOnASingleLine 
&&
AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
+   AllowShortNamespacesOnASingleLine ==
+   R.AllowShortNamespacesOnASingleLine &&
AlwaysBreakBeforeMultilineStrings ==
R.AlwaysBreakBeforeMultilineStrings &&
AttributeMacros == R.AttributeMacros &&

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..8f44e9f00212cf 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -975,6 +975,8 @@ template <> struct MappingTraits {
Style.AllowShortLambdasOnASingleLine);
 IO.mapOptional("AllowShortLoopsOnASingleLine",
Style.AllowShortLoopsOnASingleLine);
+IO.mapOptional("AllowShortNamespacesOnASingleLine",
+   Style.AllowShortNamespacesOnASingleLine);
 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
Style.AlwaysBreakAfterDefinitionReturnType);
 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
@@ -1480,6 +1482,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
   LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
   LLVMStyle.AllowShortLoopsOnASingleLine = false;
+  LLVMStyle.AllowShortNamespacesOnASingleLine = false;
   LLVMStyle.AlwaysBr

[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread via cfe-commits

github-actions[bot] wrote:



@galenelias 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 receive 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/105597
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add `AllowShortNamespacesOnASingleLine` option (PR #105597)

2024-12-30 Thread Owen Pan via cfe-commits

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


[clang-tools-extra] [clang-tidy] fix incorrect configuration file path resolving when file paths contain `..` (PR #121323)

2024-12-30 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/121323

`makeAbsolute` will not normalize path. When getting parent folder, `..` will 
go into the subfolder instead of the parent folder.


>From 896db4495ff2c29c2e623d92e004ef64f49c8dd0 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Mon, 30 Dec 2024 16:38:29 +0800
Subject: [PATCH] [clang-tidy] fix incorrect configuration file path resolving
 when file paths contain `..`

`makeAbsolute` will not normalize path. When getting parent folder, `..` will 
go into the subfolder instead of the parent folder.
---
 .../clang-tidy/ClangTidyOptions.cpp   | 32 ---
 .../clang-tidy/ClangTidyOptions.h |  4 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |  3 ++
 .../Inputs/normalized-path/code.cpp   |  0
 .../normalized-path/error-config/.clang-tidy  |  1 +
 .../infrastructure/normalized-path.test   |  3 ++
 6 files changed, 32 insertions(+), 11 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/Inputs/normalized-path/code.cpp
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/Inputs/normalized-path/error-config/.clang-tidy
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/normalized-path.test

diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index 445c7f85c900c6..1ad278e5d9a795 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -12,6 +12,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Errc.h"
+#include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBufferRef.h"
 #include "llvm/Support/Path.h"
@@ -298,12 +299,11 @@ ConfigOptionsProvider::getRawOptions(llvm::StringRef 
FileName) {
   if (ConfigOptions.InheritParentConfig.value_or(false)) {
 LLVM_DEBUG(llvm::dbgs()
<< "Getting options for file " << FileName << "...\n");
-assert(FS && "FS must be set.");
 
-llvm::SmallString<128> AbsoluteFilePath(FileName);
-
-if (!FS->makeAbsolute(AbsoluteFilePath)) {
-  addRawFileOptions(AbsoluteFilePath, RawOptions);
+llvm::ErrorOr> AbsoluteFilePath =
+getNormalizedAbsolutePath(FileName);
+if (AbsoluteFilePath) {
+  addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
 }
   }
   RawOptions.emplace_back(ConfigOptions,
@@ -334,6 +334,17 @@ FileOptionsBaseProvider::FileOptionsBaseProvider(
   OverrideOptions(std::move(OverrideOptions)),
   ConfigHandlers(std::move(ConfigHandlers)) {}
 
+llvm::ErrorOr>
+FileOptionsBaseProvider::getNormalizedAbsolutePath(llvm::StringRef Path) {
+  assert(FS && "FS must be set.");
+  llvm::SmallString<128> NormalizedAbsolutePath = {Path};
+  std::error_code Err = FS->makeAbsolute(NormalizedAbsolutePath);
+  if (Err)
+return Err;
+  llvm::sys::path::remove_dots(NormalizedAbsolutePath, 
/*remove_dot_dot=*/true);
+  return NormalizedAbsolutePath;
+}
+
 void FileOptionsBaseProvider::addRawFileOptions(
 llvm::StringRef AbsolutePath, std::vector &CurOptions) {
   auto CurSize = CurOptions.size();
@@ -396,16 +407,15 @@ std::vector
 FileOptionsProvider::getRawOptions(StringRef FileName) {
   LLVM_DEBUG(llvm::dbgs() << "Getting options for file " << FileName
   << "...\n");
-  assert(FS && "FS must be set.");
-
-  llvm::SmallString<128> AbsoluteFilePath(FileName);
 
-  if (FS->makeAbsolute(AbsoluteFilePath))
+  llvm::ErrorOr> AbsoluteFilePath =
+  getNormalizedAbsolutePath(FileName);
+  if (!AbsoluteFilePath)
 return {};
 
   std::vector RawOptions =
-  DefaultOptionsProvider::getRawOptions(AbsoluteFilePath.str());
-  addRawFileOptions(AbsoluteFilePath, RawOptions);
+  DefaultOptionsProvider::getRawOptions(AbsoluteFilePath->str());
+  addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
   OptionsSource CommandLineOptions(OverrideOptions,
OptionsSourceTypeCheckCommandLineOption);
 
diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.h 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.h
index 85d5a02ebbc1bc..95abe932d56ccf 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H
 
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorOr.h"
@@ -237,6 +238,9 @@ class FileOptionsBaseProvider : public 
DefaultOptionsProvider {
   void addRawFileOptions(llvm::StringRef AbsolutePath,
  std::vector &CurOptions);
 
+  llvm::ErrorOr>
+  getNormalizedAbsolutePath(llvm::StringRef AbsolutePath);
+
   /// Try to read configuration files from \p Directory using reg

[clang-tools-extra] [clang-tidy] fix incorrect configuration file path resolving when file paths contain `..` (PR #121323)

2024-12-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: Congcong Cai (HerrCai0907)


Changes

`makeAbsolute` will not normalize path. When getting parent folder, `..` will 
go into the subfolder instead of the parent folder.


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


6 Files Affected:

- (modified) clang-tools-extra/clang-tidy/ClangTidyOptions.cpp (+21-11) 
- (modified) clang-tools-extra/clang-tidy/ClangTidyOptions.h (+4) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+3) 
- (added) 
clang-tools-extra/test/clang-tidy/infrastructure/Inputs/normalized-path/code.cpp
 () 
- (added) 
clang-tools-extra/test/clang-tidy/infrastructure/Inputs/normalized-path/error-config/.clang-tidy
 (+1) 
- (added) clang-tools-extra/test/clang-tidy/infrastructure/normalized-path.test 
(+3) 


``diff
diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index 445c7f85c900c6..1ad278e5d9a795 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -12,6 +12,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Errc.h"
+#include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBufferRef.h"
 #include "llvm/Support/Path.h"
@@ -298,12 +299,11 @@ ConfigOptionsProvider::getRawOptions(llvm::StringRef 
FileName) {
   if (ConfigOptions.InheritParentConfig.value_or(false)) {
 LLVM_DEBUG(llvm::dbgs()
<< "Getting options for file " << FileName << "...\n");
-assert(FS && "FS must be set.");
 
-llvm::SmallString<128> AbsoluteFilePath(FileName);
-
-if (!FS->makeAbsolute(AbsoluteFilePath)) {
-  addRawFileOptions(AbsoluteFilePath, RawOptions);
+llvm::ErrorOr> AbsoluteFilePath =
+getNormalizedAbsolutePath(FileName);
+if (AbsoluteFilePath) {
+  addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
 }
   }
   RawOptions.emplace_back(ConfigOptions,
@@ -334,6 +334,17 @@ FileOptionsBaseProvider::FileOptionsBaseProvider(
   OverrideOptions(std::move(OverrideOptions)),
   ConfigHandlers(std::move(ConfigHandlers)) {}
 
+llvm::ErrorOr>
+FileOptionsBaseProvider::getNormalizedAbsolutePath(llvm::StringRef Path) {
+  assert(FS && "FS must be set.");
+  llvm::SmallString<128> NormalizedAbsolutePath = {Path};
+  std::error_code Err = FS->makeAbsolute(NormalizedAbsolutePath);
+  if (Err)
+return Err;
+  llvm::sys::path::remove_dots(NormalizedAbsolutePath, 
/*remove_dot_dot=*/true);
+  return NormalizedAbsolutePath;
+}
+
 void FileOptionsBaseProvider::addRawFileOptions(
 llvm::StringRef AbsolutePath, std::vector &CurOptions) {
   auto CurSize = CurOptions.size();
@@ -396,16 +407,15 @@ std::vector
 FileOptionsProvider::getRawOptions(StringRef FileName) {
   LLVM_DEBUG(llvm::dbgs() << "Getting options for file " << FileName
   << "...\n");
-  assert(FS && "FS must be set.");
-
-  llvm::SmallString<128> AbsoluteFilePath(FileName);
 
-  if (FS->makeAbsolute(AbsoluteFilePath))
+  llvm::ErrorOr> AbsoluteFilePath =
+  getNormalizedAbsolutePath(FileName);
+  if (!AbsoluteFilePath)
 return {};
 
   std::vector RawOptions =
-  DefaultOptionsProvider::getRawOptions(AbsoluteFilePath.str());
-  addRawFileOptions(AbsoluteFilePath, RawOptions);
+  DefaultOptionsProvider::getRawOptions(AbsoluteFilePath->str());
+  addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
   OptionsSource CommandLineOptions(OverrideOptions,
OptionsSourceTypeCheckCommandLineOption);
 
diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.h 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.h
index 85d5a02ebbc1bc..95abe932d56ccf 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H
 
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorOr.h"
@@ -237,6 +238,9 @@ class FileOptionsBaseProvider : public 
DefaultOptionsProvider {
   void addRawFileOptions(llvm::StringRef AbsolutePath,
  std::vector &CurOptions);
 
+  llvm::ErrorOr>
+  getNormalizedAbsolutePath(llvm::StringRef AbsolutePath);
+
   /// Try to read configuration files from \p Directory using registered
   /// \c ConfigHandlers.
   std::optional tryReadConfigFile(llvm::StringRef Directory);
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 3cab440155250b..2bbe7324b1f4d4 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -117,6 +117,9 @@ Improvements to clang-tidy
 
 - Improved :program:`clang-tidy` by accepting parameters file in command line.
 
+-

[clang] [Clang] Make passing incomplete types to builtin type-traits a non-sfinae-friendly error (PR #121333)

2024-12-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes

LWG3929 suggests that passing incomplete types to __is_base_of and other 
builtins supporting [meta.unary] should result in a non-sfinaeable error.

This is consistent with GCC's behavior and avoid inconsistency when using a 
builtin instead of a standard trait in a concept-definition.

Fixes #121278

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+1-1) 
- (modified) clang/test/SemaCXX/type-traits.cpp (+15) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b7da12bcf65818..e41d355ac424d6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -886,6 +886,9 @@ Bug Fixes to C++ Support
   out of a module (which is the case e.g. in MSVC's implementation of ``std`` 
module). (#GH118218)
 - Fixed a pack expansion issue in checking unexpanded parameter sizes. 
(#GH17042)
 - Fixed a bug where captured structured bindings were modifiable inside 
non-mutable lambda (#GH95081)
+- Passing incomplete types to ``__is_base_of`` and other builtin type traits 
for which the corresponding
+  standard type trait mandates a complete type is now a hard 
(non-sfinae-friendly) error
+  (`LWG3929 `__.) (#GH121278)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 330ae045616aba..03fb7ca9bc3c3b 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9361,7 +9361,7 @@ def note_inequality_comparison_to_or_assign : Note<
   "use '|=' to turn this inequality comparison into an or-assignment">;
 
 def err_incomplete_type_used_in_type_trait_expr : Error<
-  "incomplete type %0 used in type trait expression">;
+  "incomplete type %0 used in type trait expression">, NoSFINAE;
 
 // C++20 constinit and require_constant_initialization attribute
 def warn_cxx20_compat_constinit : Warning<
diff --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 91ef7786f11bb9..1b9e2ba6ff162f 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -5031,3 +5031,18 @@ void remove_all_extents() {
   using SomeArray = int[1][2];
   static_assert(__is_same(remove_all_extents_t, const int));
 }
+
+namespace GH121278 {
+// https://cplusplus.github.io/LWG/lwg-active.html#3929
+#if __cplusplus >= 202002L
+template 
+concept C = __is_base_of(B, D);
+// expected-error@-1 {{incomplete type 'GH121278::S' used in type trait 
expression}}
+// expected-note@-2 {{while substituting template arguments into constraint 
expression here}}
+
+struct T;
+struct S;
+bool b = C;
+// expected-note@-1 {{while checking the satisfaction of concept 
'C' requested here}}
+#endif
+}

``




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


[clang] [Clang] Diagnose unexpanded packs for NTTP type constraints (PR #121296)

2024-12-30 Thread Younan Zhang via cfe-commits


@@ -305,3 +305,45 @@ 
static_assert(__is_same_as(_Three_way_comparison_result_with_tuple_like,
 0>::type, long));
 
 }
+
+namespace GH88866 {
+
+template  struct index_by;
+
+template 
+concept InitFunc = true;
+
+namespace Invalid {
+
+template  auto... init>
+struct LazyLitMatrix;
+
+template <
+typename...Indices,
+InitFunc> auto... init
+// expected-error@-1 {{type constraint contains unexpanded parameter pack 
'Indices'}}

zyn0217 wrote:

Wow you're right, I was confused by the original case where there's no ellipsis 
in the parameter declaration.

https://godbolt.org/z/9jaazxEqY

(Fun fact that GCC accepts both w/ or w/o ellipsis, which doesn't seem right. 
We crash on both, sadly.)

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


[clang] [Clang] Diagnose unexpanded packs for NTTP type constraints (PR #121296)

2024-12-30 Thread Younan Zhang via cfe-commits

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


[clang-tools-extra] [clang-tidy] bugprone-unhandled-self-assignment: fix smart pointer check against std::unique_ptr type (PR #121266)

2024-12-30 Thread via cfe-commits

https://github.com/flovent updated 
https://github.com/llvm/llvm-project/pull/121266

>From 009178ad073cd76630418e74092907e1d9dc0d85 Mon Sep 17 00:00:00 2001
From: flovent 
Date: Sat, 28 Dec 2024 21:52:53 +0800
Subject: [PATCH 1/2] [clang-tidy] bugprone-unhandled-self-assignment: fix
 smart pointer check against std::unique_ptr type

---
 .../clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp  | 8 +---
 .../checkers/bugprone/unhandled-self-assignment.cpp   | 4 +++-
 2 files changed, 8 insertions(+), 4 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
index 8121a36f803460..1f432c4ccc5f00 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
@@ -74,9 +74,11 @@ void 
UnhandledSelfAssignmentCheck::registerMatchers(MatchFinder *Finder) {
 // Matcher for standard smart pointers.
 const auto SmartPointerType = qualType(hasUnqualifiedDesugaredType(
 recordType(hasDeclaration(classTemplateSpecializationDecl(
-hasAnyName("::std::shared_ptr", "::std::unique_ptr",
-   "::std::weak_ptr", "::std::auto_ptr"),
-templateArgumentCountIs(1));
+anyOf(allOf(hasAnyName("::std::shared_ptr", "::std::weak_ptr",
+   "::std::auto_ptr"),
+templateArgumentCountIs(1)),
+  allOf(hasName("::std::unique_ptr"),
+templateArgumentCountIs(2;
 
 // We will warn only if the class has a pointer or a C array field which
 // probably causes a problem during self-assignment (e.g. first resetting
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
index 14d27855d7c5a6..8610393449f97f 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unhandled-self-assignment.cpp
@@ -10,7 +10,9 @@ template 
 T &&move(T &x) {
 }
 
-template 
+template  class default_delete {};
+
+template >
 class unique_ptr {
 };
 

>From 4de37e9b224bdcf51991779ae49146fd553fe99d Mon Sep 17 00:00:00 2001
From: flovent 
Date: Mon, 30 Dec 2024 19:48:32 +0800
Subject: [PATCH 2/2] add release note for last commit in ReleaseNotes.rst

---
 clang-tools-extra/docs/ReleaseNotes.rst | 4 
 1 file changed, 4 insertions(+)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index fabd0cc78ac645..24b2e61a6f17ee 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -232,6 +232,10 @@ Changes in existing checks
   `bsl::optional` and `bdlb::NullableValue` from
   _.
 
+- Improved :doc:`bugprone-unhandled-self-assignment
+  ` check by fixing smart
+  pointer check against std::unique_ptr type.
+
 - Improved :doc:`bugprone-unsafe-functions
   ` check to allow specifying
   additional functions to match.

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


[clang-tools-extra] [clang-tidy] bugprone-unhandled-self-assignment: fix smart pointer check against std::unique_ptr type (PR #121266)

2024-12-30 Thread via cfe-commits

flovent wrote:

> please add release note in `clang-tools-extra/docs/ReleaseNotes.rst` 
> alphabetically.

done. 
And yes, i don't have write access, can you merge it? @HerrCai0907 

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


[clang-tools-extra] [clang-tidy] add depercation warning for non-whitelisted global options (PR #121057)

2024-12-30 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti approved this pull request.

Looks good from my side.

---

> Perhaps we can just land this as is for now and introduce the escape hatch if 
> we get feedback indicating it's needed?

I think that is totally fine. If this comes up, we can also immediately 
backport the flag so that users don't have to wait, e.g., months for their 
distro (etc.) to update the major version.

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


[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] implement views::concat (PR #120920)

2024-12-30 Thread A. Jiang via cfe-commits

https://github.com/frederick-vs-ja requested changes to this pull request.


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


[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] implement views::concat (PR #120920)

2024-12-30 Thread A. Jiang via cfe-commits


@@ -0,0 +1,626 @@
+// -*- C++ -*-
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _LIBCPP___RANGES_CONCAT_VIEW_H
+#define _LIBCPP___RANGES_CONCAT_VIEW_H
+
+#include <__algorithm/ranges_find_if.h>
+#include <__assert>
+#include <__concepts/common_reference_with.h>
+#include <__concepts/constructible.h>
+#include <__concepts/convertible_to.h>
+#include <__concepts/copyable.h>
+#include <__concepts/derived_from.h>
+#include <__concepts/equality_comparable.h>
+#include <__concepts/swappable.h>
+#include <__config>
+#include <__functional/bind_back.h>
+#include <__functional/invoke.h>
+#include <__functional/reference_wrapper.h>
+#include <__iterator/concepts.h>
+#include <__iterator/default_sentinel.h>
+#include <__iterator/distance.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iter_swap.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/next.h>
+#include <__memory/addressof.h>
+#include <__ranges/access.h>
+#include <__ranges/all.h>
+#include <__ranges/concepts.h>
+#include <__ranges/movable_box.h>
+#include <__ranges/non_propagating_cache.h>
+#include <__ranges/range_adaptor.h>
+#include <__ranges/size.h>
+#include <__ranges/view_interface.h>
+#include <__type_traits/conditional.h>
+#include <__type_traits/decay.h>
+#include <__type_traits/is_nothrow_constructible.h>
+#include <__type_traits/is_nothrow_convertible.h>
+#include <__type_traits/is_object.h>
+#include <__type_traits/make_unsigned.h>
+#include <__type_traits/maybe_const.h>
+#include <__utility/forward.h>
+#include <__utility/in_place.h>
+#include <__utility/move.h>
+#include 
+#include 
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 26
+
+namespace ranges {
+
+template 
+struct __extract_last : __extract_last<_Tp...> {};
+
+template 
+struct __extract_last<_T> {
+  using type = _T;
+};
+
+template 
+struct __derived_from_pack {
+  constexpr static bool value =
+  __derived_from_pack<_T, typename __extract_last<_Tp...>::type>::value && 
__derived_from_pack<_Tp...>::value;
+};
+
+template 
+struct __derived_from_pack<_T, _IterCategory> {
+  constexpr static bool value = derived_from<_T, _IterCategory>;
+};
+
+template 
+struct __last_view : __last_view<_Views...> {};
+
+template 
+struct __last_view<_View> {
+  using type = _View;
+};
+
+template 
+concept __concat_indirectly_readable_impl = requires(const _It it) {
+  { *it } -> convertible_to<_Ref>;
+  { ranges::iter_move(it) } -> convertible_to<_RRef>;
+};
+
+template 
+using __concat_reference_t = common_reference_t...>;
+
+template 
+using __concat_value_t = common_type_t...>;
+
+template 
+using __concat_rvalue_reference_t = 
common_reference_t...>;
+
+template 
+concept __concat_indirectly_readable =
+common_reference_with<__concat_reference_t<_Rs...>&&, 
__concat_value_t<_Rs...>&> &&
+common_reference_with<__concat_reference_t<_Rs...>&&, 
__concat_rvalue_reference_t<_Rs...>&&> &&
+common_reference_with<__concat_rvalue_reference_t<_Rs...>&&, 
__concat_value_t<_Rs...> const&> &&
+(__concat_indirectly_readable_impl<__concat_reference_t<_Rs...>,
+   __concat_rvalue_reference_t<_Rs...>,
+   iterator_t<_Rs>> &&
+ ...);
+
+template 
+concept __concatable = requires {
+  typename __concat_reference_t<_Rs...>;
+  typename __concat_value_t<_Rs...>;
+  typename __concat_rvalue_reference_t<_Rs...>;
+} && __concat_indirectly_readable<_Rs...>;
+
+template 
+concept __concat_is_random_access =
+(random_access_range<__maybe_const<_Const, _Rs>> && ...) && 
(sized_range<__maybe_const<_Const, _Rs>> && ...);
+
+template 
+concept __concat_is_bidirectional =
+((bidirectional_range<__maybe_const<_Const, _Rs>> && ...) && 
(common_range<__maybe_const<_Const, _Rs>> && ...));
+
+template 
+concept __all_forward = (forward_range<__maybe_const<_Const, _Views>> && ...);
+
+template 
+struct __apply_drop_first;
+
+template 
+struct __apply_drop_first<_Const, Head, Tail...> {
+  static constexpr bool value = (sized_range<__maybe_const<_Const, Tail>> && 
...);
+};
+
+template 
+  requires(view<_Views> && ...) && (sizeof...(_Views) > 0) && 
__concatable<_Views...>
+class concat_view : public view_interface> {
+  tuple<_Views...> views_;
+
+  template 
+  class iterator;
+  class sentinel;
+
+public:
+  _LIBCPP_HIDE_FROM_ABI constexpr concat_view() = default;
+
+  _LIBCPP_HIDE_FROM_ABI constexpr explicit concat_view(_Views... views) : 
views_(std::move(views)...) {}
+
+  _LIBCPP_HIDE_FROM_ABI conste

[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] implement views::concat (PR #120920)

2024-12-30 Thread A. Jiang via cfe-commits


@@ -0,0 +1,626 @@
+// -*- C++ -*-
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _LIBCPP___RANGES_CONCAT_VIEW_H
+#define _LIBCPP___RANGES_CONCAT_VIEW_H
+
+#include <__algorithm/ranges_find_if.h>
+#include <__assert>
+#include <__concepts/common_reference_with.h>
+#include <__concepts/constructible.h>
+#include <__concepts/convertible_to.h>
+#include <__concepts/copyable.h>
+#include <__concepts/derived_from.h>
+#include <__concepts/equality_comparable.h>
+#include <__concepts/swappable.h>
+#include <__config>
+#include <__functional/bind_back.h>
+#include <__functional/invoke.h>
+#include <__functional/reference_wrapper.h>
+#include <__iterator/concepts.h>
+#include <__iterator/default_sentinel.h>
+#include <__iterator/distance.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iter_swap.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/next.h>
+#include <__memory/addressof.h>
+#include <__ranges/access.h>
+#include <__ranges/all.h>
+#include <__ranges/concepts.h>
+#include <__ranges/movable_box.h>
+#include <__ranges/non_propagating_cache.h>
+#include <__ranges/range_adaptor.h>
+#include <__ranges/size.h>
+#include <__ranges/view_interface.h>
+#include <__type_traits/conditional.h>
+#include <__type_traits/decay.h>
+#include <__type_traits/is_nothrow_constructible.h>
+#include <__type_traits/is_nothrow_convertible.h>
+#include <__type_traits/is_object.h>
+#include <__type_traits/make_unsigned.h>
+#include <__type_traits/maybe_const.h>
+#include <__utility/forward.h>
+#include <__utility/in_place.h>
+#include <__utility/move.h>
+#include 
+#include 
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 26
+
+namespace ranges {
+
+template 
+struct __extract_last : __extract_last<_Tp...> {};
+
+template 
+struct __extract_last<_T> {
+  using type = _T;
+};
+
+template 
+struct __derived_from_pack {
+  constexpr static bool value =
+  __derived_from_pack<_T, typename __extract_last<_Tp...>::type>::value && 
__derived_from_pack<_Tp...>::value;
+};
+
+template 
+struct __derived_from_pack<_T, _IterCategory> {
+  constexpr static bool value = derived_from<_T, _IterCategory>;
+};
+
+template 
+struct __last_view : __last_view<_Views...> {};
+
+template 
+struct __last_view<_View> {
+  using type = _View;
+};
+
+template 
+concept __concat_indirectly_readable_impl = requires(const _It it) {
+  { *it } -> convertible_to<_Ref>;
+  { ranges::iter_move(it) } -> convertible_to<_RRef>;
+};
+
+template 
+using __concat_reference_t = common_reference_t...>;
+
+template 
+using __concat_value_t = common_type_t...>;
+
+template 
+using __concat_rvalue_reference_t = 
common_reference_t...>;
+
+template 
+concept __concat_indirectly_readable =
+common_reference_with<__concat_reference_t<_Rs...>&&, 
__concat_value_t<_Rs...>&> &&
+common_reference_with<__concat_reference_t<_Rs...>&&, 
__concat_rvalue_reference_t<_Rs...>&&> &&
+common_reference_with<__concat_rvalue_reference_t<_Rs...>&&, 
__concat_value_t<_Rs...> const&> &&
+(__concat_indirectly_readable_impl<__concat_reference_t<_Rs...>,
+   __concat_rvalue_reference_t<_Rs...>,
+   iterator_t<_Rs>> &&
+ ...);
+
+template 
+concept __concatable = requires {
+  typename __concat_reference_t<_Rs...>;
+  typename __concat_value_t<_Rs...>;
+  typename __concat_rvalue_reference_t<_Rs...>;
+} && __concat_indirectly_readable<_Rs...>;
+
+template 
+concept __concat_is_random_access =
+(random_access_range<__maybe_const<_Const, _Rs>> && ...) && 
(sized_range<__maybe_const<_Const, _Rs>> && ...);
+
+template 
+concept __concat_is_bidirectional =
+((bidirectional_range<__maybe_const<_Const, _Rs>> && ...) && 
(common_range<__maybe_const<_Const, _Rs>> && ...));
+
+template 
+concept __all_forward = (forward_range<__maybe_const<_Const, _Views>> && ...);
+
+template 
+struct __apply_drop_first;
+
+template 
+struct __apply_drop_first<_Const, Head, Tail...> {
+  static constexpr bool value = (sized_range<__maybe_const<_Const, Tail>> && 
...);
+};
+
+template 
+  requires(view<_Views> && ...) && (sizeof...(_Views) > 0) && 
__concatable<_Views...>
+class concat_view : public view_interface> {
+  tuple<_Views...> views_;
+
+  template 
+  class iterator;
+  class sentinel;

frederick-vs-ja wrote:

Exposition-only names are not standard, and thus should be __ugly (ditto below).

```suggestion
  template 
  class __iterator;
  class __sentinel;
```

https://github.com/

[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] implement views::concat (PR #120920)

2024-12-30 Thread A. Jiang via cfe-commits


@@ -0,0 +1,626 @@
+// -*- C++ -*-
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _LIBCPP___RANGES_CONCAT_VIEW_H
+#define _LIBCPP___RANGES_CONCAT_VIEW_H
+
+#include <__algorithm/ranges_find_if.h>
+#include <__assert>
+#include <__concepts/common_reference_with.h>
+#include <__concepts/constructible.h>
+#include <__concepts/convertible_to.h>
+#include <__concepts/copyable.h>
+#include <__concepts/derived_from.h>
+#include <__concepts/equality_comparable.h>
+#include <__concepts/swappable.h>
+#include <__config>
+#include <__functional/bind_back.h>
+#include <__functional/invoke.h>
+#include <__functional/reference_wrapper.h>
+#include <__iterator/concepts.h>
+#include <__iterator/default_sentinel.h>
+#include <__iterator/distance.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iter_swap.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/next.h>
+#include <__memory/addressof.h>
+#include <__ranges/access.h>
+#include <__ranges/all.h>
+#include <__ranges/concepts.h>
+#include <__ranges/movable_box.h>
+#include <__ranges/non_propagating_cache.h>
+#include <__ranges/range_adaptor.h>
+#include <__ranges/size.h>
+#include <__ranges/view_interface.h>
+#include <__type_traits/conditional.h>
+#include <__type_traits/decay.h>
+#include <__type_traits/is_nothrow_constructible.h>
+#include <__type_traits/is_nothrow_convertible.h>
+#include <__type_traits/is_object.h>
+#include <__type_traits/make_unsigned.h>
+#include <__type_traits/maybe_const.h>
+#include <__utility/forward.h>
+#include <__utility/in_place.h>
+#include <__utility/move.h>
+#include 
+#include 
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 26
+
+namespace ranges {
+
+template 
+struct __extract_last : __extract_last<_Tp...> {};
+
+template 
+struct __extract_last<_T> {
+  using type = _T;
+};
+
+template 
+struct __derived_from_pack {
+  constexpr static bool value =
+  __derived_from_pack<_T, typename __extract_last<_Tp...>::type>::value && 
__derived_from_pack<_Tp...>::value;
+};
+
+template 
+struct __derived_from_pack<_T, _IterCategory> {
+  constexpr static bool value = derived_from<_T, _IterCategory>;
+};
+
+template 
+struct __last_view : __last_view<_Views...> {};
+
+template 
+struct __last_view<_View> {
+  using type = _View;
+};
+
+template 
+concept __concat_indirectly_readable_impl = requires(const _It it) {
+  { *it } -> convertible_to<_Ref>;
+  { ranges::iter_move(it) } -> convertible_to<_RRef>;
+};
+
+template 
+using __concat_reference_t = common_reference_t...>;
+
+template 
+using __concat_value_t = common_type_t...>;
+
+template 
+using __concat_rvalue_reference_t = 
common_reference_t...>;
+
+template 
+concept __concat_indirectly_readable =
+common_reference_with<__concat_reference_t<_Rs...>&&, 
__concat_value_t<_Rs...>&> &&
+common_reference_with<__concat_reference_t<_Rs...>&&, 
__concat_rvalue_reference_t<_Rs...>&&> &&
+common_reference_with<__concat_rvalue_reference_t<_Rs...>&&, 
__concat_value_t<_Rs...> const&> &&
+(__concat_indirectly_readable_impl<__concat_reference_t<_Rs...>,
+   __concat_rvalue_reference_t<_Rs...>,
+   iterator_t<_Rs>> &&
+ ...);
+
+template 
+concept __concatable = requires {
+  typename __concat_reference_t<_Rs...>;
+  typename __concat_value_t<_Rs...>;
+  typename __concat_rvalue_reference_t<_Rs...>;
+} && __concat_indirectly_readable<_Rs...>;
+
+template 
+concept __concat_is_random_access =
+(random_access_range<__maybe_const<_Const, _Rs>> && ...) && 
(sized_range<__maybe_const<_Const, _Rs>> && ...);
+
+template 
+concept __concat_is_bidirectional =
+((bidirectional_range<__maybe_const<_Const, _Rs>> && ...) && 
(common_range<__maybe_const<_Const, _Rs>> && ...));
+
+template 
+concept __all_forward = (forward_range<__maybe_const<_Const, _Views>> && ...);
+
+template 
+struct __apply_drop_first;
+
+template 
+struct __apply_drop_first<_Const, Head, Tail...> {
+  static constexpr bool value = (sized_range<__maybe_const<_Const, Tail>> && 
...);
+};
+
+template 
+  requires(view<_Views> && ...) && (sizeof...(_Views) > 0) && 
__concatable<_Views...>
+class concat_view : public view_interface> {
+  tuple<_Views...> views_;

frederick-vs-ja wrote:

Member names should be __ugly unless specified by the standard (ditto below).
```suggestion
  tuple<_Views...> __views_;
```

https://github.com/llvm/llvm-project/pull/120920
___
cf

  1   2   >