[clang] [clang-format] Correctly annotate user-defined conversion functions (PR #131434)

2025-03-16 Thread Björn Schäpers via cfe-commits

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


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


[clang] [lld] [llvm] Integrated Distributed ThinLTO (DTLTO): Design Overview (PR #126654)

2025-03-16 Thread Katya Romanova via cfe-commits

romanova-ekaterina wrote:

> Hi Reviewers! Thanks for the feedback here. I wanted to draw attention to 
> something that I mentioned briefly in the description - the possibility of a 
> plugin interface as opposed to invoking an external process that consumes 
> JSON.
> 
> There are some theoretical advantages with plugins. For example, if 
> distribution systems exist/arise that allow data to be passed back and forth 
> between LLVM and a distribution system using memory buffers instead of files, 
> a plugin could perhaps do that more efficiently. But we haven't done anything 
> yet to quantify how much better this would be vs implicitly leaning on e.g. 
> memory mapped files and the OS file cache. The distribution systems we're 
> motivated to support from customer demand don't have such capabilities at 
> this time.
> 
> Does anyone have any opinions on this?

The “No backend DTLTO” branch is ready. Please have a look and let us know what 
you think. 
https://github.com/romanova-ekaterina/llvm-project/pull/new/kromanova/main/integrated-DTLTO-no-backend

This comment 
[https://github.com/llvm/llvm-project/pull/127749#issuecomment-2727266591]

has more details about the differences between “Out of process (DTLTO) backend” 
branch and “No backend” DTLTO branch.

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


[clang] [lld] [llvm] Integrated Distributed ThinLTO (DTLTO): Design Overview (PR #126654)

2025-03-16 Thread Katya Romanova via cfe-commits

romanova-ekaterina wrote:

> > Thanks for the heads up, so I should not do a detailed code review for 
> > PR127749? Is there more info on what you mean by a "no-backend DTLTO"?
> 
> Actually, please review whatever you would like to at this point, Theresa. I 
> don't want to get in the way of hearing what you think - we're keen to your 
> input. I just wanted to point out that since another branch is coming, you 
> may wish to wait until it arrives if you think a side-by-side comparison 
> would be a good way of doing things. To clarify: that other branch won't be 
> put up as a pull request, but we can decide how to proceed here if the 
> general design shown in that other branch is preferred. I also mentioned that 
> it will appear in a few days, but that's really dependent on the results of 
> some more internal review. We're working hard on it!

The “No backend DTLTO” branch is ready. Please have a look and let us know what 
you think. 
https://github.com/romanova-ekaterina/llvm-project/pull/new/kromanova/main/integrated-DTLTO-no-backend

This comment 
[https://github.com/llvm/llvm-project/pull/127749#issuecomment-2727266591]

has more details about the differences between “Out of process (DTLTO) backend” 
branch and “No backend” DTLTO branch.

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


[clang-tools-extra] [clang-tidy] offer option to check sugared types in avoid-c-arrays check (PR #131468)

2025-03-16 Thread via cfe-commits


@@ -0,0 +1,126 @@
+// RUN: %check_clang_tidy -std=c++17 %s modernize-avoid-c-arrays %t -- \

stmuench wrote:

I just followed the approach for all the existing tests where different use 
cases got put into separate .cpp files. Was this not correct?


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


[clang] [clang-format] Correctly annotate user-defined conversion functions (PR #131434)

2025-03-16 Thread Owen Pan via cfe-commits

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

>From 46cde1b7667f36115d746326b78d011511cac738 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sat, 15 Mar 2025 00:37:53 -0700
Subject: [PATCH 1/2] [clang-format] Correctly annotate user-defined conversion
 functions

Also fix/delete existing invalid/redundant test cases.

Fix #130894
---
 clang/lib/Format/TokenAnnotator.cpp   | 27 --
 clang/unittests/Format/FormatTest.cpp | 28 +-
 clang/unittests/Format/TokenAnnotatorTest.cpp | 53 +++
 3 files changed, 89 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 08539de405c67..d618eab1692b3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1639,6 +1639,25 @@ class AnnotatingParser {
 case tok::kw_operator:
   if (Style.isProto())
 break;
+  // C++ user-defined conversion function.
+  if (IsCpp && CurrentToken &&
+  (CurrentToken->is(tok::kw_auto) ||
+   CurrentToken->isTypeName(LangOpts))) {
+FormatToken *LParen;
+if (CurrentToken->startsSequence(tok::kw_decltype, tok::l_paren,
+ tok::kw_auto, tok::r_paren)) {
+  LParen = CurrentToken->Next->Next->Next->Next;
+} else {
+  for (LParen = CurrentToken->Next;
+   LParen && LParen->isNot(tok::l_paren); LParen = LParen->Next) {
+  }
+}
+if (LParen && LParen->startsSequence(tok::l_paren, tok::r_paren)) {
+  Tok->setFinalizedType(TT_FunctionDeclarationName);
+  LParen->setFinalizedType(TT_FunctionDeclarationLParen);
+  break;
+}
+  }
   while (CurrentToken &&
  !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
 if (CurrentToken->isOneOf(tok::star, tok::amp))
@@ -3071,12 +3090,10 @@ class AnnotatingParser {
 if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
   return TT_BinaryOperator;
 
-// "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
-// unary "&".
-if (Tok.is(tok::ampamp) &&
-NextToken->isOneOf(tok::l_paren, tok::star, tok::amp)) {
+// "&&" followed by "*" or "&" is quite unlikely to be two successive unary
+// "&".
+if (Tok.is(tok::ampamp) && NextToken->isOneOf(tok::star, tok::amp))
   return TT_BinaryOperator;
-}
 
 // This catches some cases where evaluation order is used as control flow:
 //   aaa && aaa->f();
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 9864e7ec1b2ec..5df7865f5a629 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10443,27 +10443,17 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
"void\n"
"A::operator->() {}\n"
"void\n"
-   "A::operator void *() {}\n"
+   "A::operator&() {}\n"
"void\n"
-   "A::operator void &() {}\n"
-   "void\n"
-   "A::operator void &&() {}\n"
-   "void\n"
-   "A::operator char *() {}\n"
+   "A::operator&&() {}\n"
"void\n"
"A::operator[]() {}\n"
"void\n"
"A::operator!() {}\n"
"void\n"
-   "A::operator**() {}\n"
-   "void\n"
"A::operator *() {}\n"
"void\n"
-   "A::operator **() {}\n"
-   "void\n"
-   "A::operator &() {}\n"
-   "void\n"
-   "A::operator void **() {}",
+   "A::operator &() {}\n",
Style);
   verifyFormat("constexpr auto\n"
"operator()() const -> reference {}\n"
@@ -10486,7 +10476,7 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
"constexpr auto\n"
"operator void &() const -> reference {}\n"
"constexpr auto\n"
-   "operator void &&() const -> reference {}\n"
+   "operator&&() const -> reference {}\n"
"constexpr auto\n"
"operator char *() const -> reference {}\n"
"constexpr auto\n"
@@ -28032,6 +28022,16 @@ TEST_F(FormatTest, BreakAfterAttributes) {
"  --d;",
CtrlStmtCode, Style);
 
+  verifyFormat("[[nodiscard]]\n"
+   "operator bool();\n"
+   "[[nodiscard]]\n"
+   "operator bool() {\n"
+   "  return true;\n"
+   "}",
+   "[[nodiscard]] operator bool();\n"
+   "[[nodiscard]] operator bool() { return true; }",
+   Style);
+
   constexpr StringRef CtorDtorCode("struct Foo {\n"
"  [[deprecated]] Foo();\n"
 

[clang] [lld] [llvm] Integrated Distributed ThinLTO (DTLTO): Design Overview (PR #126654)

2025-03-16 Thread Katya Romanova via cfe-commits

romanova-ekaterina wrote:

> > Thanks for the heads up, so I should not do a detailed code review for 
> > PR127749? Is there more info on what you mean by a "no-backend DTLTO"?
> 
> Actually, please review whatever you would like to at this point, Theresa. I 
> don't want to get in the way of hearing what you think - we're keen to your 
> input. I just wanted to point out that since another branch is coming, you 
> may wish to wait until it arrives if you think a side-by-side comparison 
> would be a good way of doing things. To clarify: that other branch won't be 
> put up as a pull request, but we can decide how to proceed here if the 
> general design shown in that other branch is preferred. I also mentioned that 
> it will appear in a few days, but that's really dependent on the results of 
> some more internal review. We're working hard on it!

The “No backend DTLTO” branch is ready 
https://github.com/romanova-ekaterina/llvm-project/pull/new/kromanova/main/integrated-DTLTO-no-backend.
 Please have a look and let us know what you think. This comment [[DTLTO][LLVM] 
Integrated Distributed ThinLTO (DTLTO) by bd1976bris · Pull Request #127749 · 
llvm/llvm-project](https://github.com/llvm/llvm-project/pull/127749#issuecomment-2727266591)
 has more details about the differences between “Out of process (DTLTO) 
backend” branch and “No backend” DTLTO branch.

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


[clang] [llvm] [RISCV][MC] Implement MC for Base P extension (PR #123271)

2025-03-16 Thread via cfe-commits


@@ -0,0 +1,1079 @@
+//===-- RISCVInstrInfoP.td - RISC-V 'P' instructions ---*- tablegen 
-*-===//
+//
+// 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
+//
+//===--===//
+//
+// This file describes the RISC-V instructions from the standard 'Base P'
+// Packed SIMD instruction set extension.
+//
+//  This version is still experimental as the 'P' extension hasn't been
+//  ratified yet.
+//
+//===--===//
+
+//===--===//
+// Operand and SDNode transformation definitions.
+//===--===//
+
+def RVPGPRPairRV32 : RegisterOperand {
+  let ParserMatchClass = GPRPairRV32Operand;
+  let EncoderMethod = "getRVPGPRPair";
+  let DecoderMethod = "decodeRVPGPRPair";
+}
+
+def simm10 : RISCVSImmLeafOp<10> {
+  let MCOperandPredicate = [{
+int64_t Imm;
+if (!MCOp.evaluateAsConstantImm(Imm))
+  return false;
+return isInt<10>(Imm);
+  }];
+}
+
+//===--===//
+// Instruction class templates
+//===--===//
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 0 in
+class RVPUnary funct5, bits<7> wuimm,
+   bits<3> funct3, RISCVOpcode opcode,
+   string opcodestr>
+: RVInstIBase {
+  let Inst{31-27} = funct5;
+  let Inst{26-20} = wuimm;
+}
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 0 in
+class RVPUnaryImm9 funct7, string opcodestr>
+: RVInstIBase<0b010, OPC_OP_IMM_32, (outs GPR:$rd), (ins simm10:$simm10),
+  opcodestr, "$rd, $simm10"> {
+  bits<10> simm10;
+
+  let Inst{31-25} = funct7;
+  let Inst{24-15} = simm10;
+}
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 0 in
+class RVPUnaryImm9Rdp funct7, string opcodestr>
+: RVInstIBase<0b010, OPC_OP_IMM_32, (outs RVPGPRPairRV32:$rdp),
+  (ins simm10:$simm10),
+  opcodestr, "$rdp, $simm10"> {
+  bits<10> simm10;
+  bits<4> rdp;
+
+  let Inst{31-25} = funct7;
+  let Inst{24-15} = simm10;
+  let Inst{11-8}  = rdp;
+  let Inst{7} = 0b0;
+}
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 0 in
+class RVPUnaryImm8 funct8, string opcodestr>
+: RVInstIBase<0b010, OPC_OP_IMM_32, (outs GPR:$rd), (ins uimm8:$uimm8),
+  opcodestr, "$rd, $uimm8"> {
+  bits<8> uimm8;
+
+  let Inst{31-24} = funct8;
+  let Inst{23-16} = uimm8;
+  let Inst{15}= 0b0;
+}
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 0 in
+class RVPUnaryImm8Rdp funct8, string opcodestr>
+: RVInstIBase<0b010, OPC_OP_IMM_32, (outs RVPGPRPairRV32:$rdp),
+  (ins uimm8:$uimm8), opcodestr, "$rdp, $uimm8"> {
+  bits<8> uimm8;
+  bits<4> rdp;
+
+  let Inst{31-24} = funct8;
+  let Inst{23-16} = uimm8;
+  let Inst{15}= 0b0;
+  let Inst{11-8}  = rdp;
+  let Inst{7} = 0b0;
+}
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 0 in
+class RVPUnaryWUF w, bits<5> uf, string opcodestr>
+: RVInstIBase<0b010, OPC_OP_IMM_32, (outs GPR:$rd), (ins GPR:$rs1),
+  opcodestr, "$rd, $rs1">  {
+  let Inst{31-27} = 0b11100;
+  let Inst{26-25} = w;
+  let Inst{24-20} = uf;
+}
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 0 in
+class RVPUnaryWUFRs1pRdp w, bits<5> uf, string opcodestr>
+: RVInstIBase<0b010, OPC_OP_IMM_32, (outs RVPGPRPairRV32:$rdp),
+  (ins RVPGPRPairRV32:$rs1p), opcodestr, "$rdp, $rs1p">  {
+  bits<4> rs1p;
+  bits<4> rdp;
+
+  let Inst{31-27} = 0b01100;
+  let Inst{26-25} = w;
+  let Inst{24-20} = uf;
+  let Inst{19-16} = rs1p;
+  let Inst{15}= 0b0;
+  let Inst{11-8}  = rdp;
+  let Inst{7} = 0b0;
+}
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 0 in
+class RVPUnaryF f, bit aft, bits<7> wuimm, string opcodestr,
+bits<3> funct3, dag outs, dag ins, string argstr>
+: RVInstIBase  {
+  let Inst{31}= bfr;
+  let Inst{30-28} = f;
+  let Inst{27}= aft;
+  let Inst{26-20} = wuimm;
+}
+
+class RVPUnary1F0 f, bits<7> wuimm, string opcodestr>
+: RVPUnaryF<1, f, 0, wuimm, opcodestr, 0b100, (outs GPR:$rd),
+(ins GPR:$rs1), "$rd, $rs1">;
+
+class RVPUnary0F0Rdp f, bits<7> wuimm, string opcodestr>
+: RVPUnaryF<0, f, 0, wuimm, opcodestr, 0b010, (outs RVPGPRPairRV32:$rdp),
+   (ins GPR:$rs1), "$rdp, $rs1"> {
+  bits<4> rdp;
+
+  let Inst{11-8} = rdp;
+  let Inst{7}= 0b0;
+}
+
+class RVPUnary0F0Rs1p f, bits<7> wuimm, string opcodestr>
+: RVPUnaryF<0, f, 0, wuimm, opcodestr, 0b100, (outs GPR:$rd),
+(ins RVPGPRPairRV32:$rs1p), "$rd, $rs1p"> {
+  bits<4> rs1p;
+
+  let Inst{19-16} = rs

[clang] [clang] Refine handling of C++20 aggregate initialization (PR #131320)

2025-03-16 Thread via cfe-commits

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


[clang] [clang] Avoid doing C++20 aggregate init during copy-initialization (PR #131320)

2025-03-16 Thread via cfe-commits

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


[clang] [clang] Avoid doing C++20 aggregate init during copy-initialization (PR #131320)

2025-03-16 Thread via cfe-commits

https://github.com/offsetof updated 
https://github.com/llvm/llvm-project/pull/131320

>From 07120d060bf4e5ac447950bfe681deead1ce62ed Mon Sep 17 00:00:00 2001
From: offsetof 
Date: Sun, 16 Mar 2025 09:59:44 +
Subject: [PATCH] [clang] Refine handling of C++20 aggregate initialization

* Move parts of `InitializationSequence::InitializeFrom` corresponding
  to C++ [dcl.init.general] p16.6.1 and p16.6.2 into a separate
  function, `TryConstructorOrParenListInitialization`
* Use it in `TryListInitialization` to implement [dcl.init.list]/3.2
* Fix parenthesized aggregate initialization being attempted in
  copy-initialization contexts or when the constructor call is ambiguous
---
 clang/docs/ReleaseNotes.rst   |   1 +
 clang/lib/Sema/SemaInit.cpp   | 106 --
 .../dcl.init/dcl.init.general/p16-cxx20.cpp   | 132 --
 3 files changed, 183 insertions(+), 56 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a1c5ee2d788e..22ebf86e05f7d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,6 +281,7 @@ Bug Fixes in This Version
 - Fixed a modules crash where exception specifications were not propagated 
properly (#GH121245, relanded in #GH129982)
 - Fixed a problematic case with recursive deserialization within 
``FinishedDeserializing()`` where
   ``PassInterestingDeclsToConsumer()`` was called before the declarations were 
safe to be passed. (#GH129982)
+- Fixed C++20 aggregate initialization rules being incorrectly applied in 
certain contexts (#GH131320)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 56ec33fe37bf3..e612500df5192 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -4633,6 +4633,59 @@ static void TryConstructorInitialization(Sema &S,
   IsListInit | IsInitListCopy, AsInitializerList);
 }
 
+static void TryOrBuildParenListInitialization(
+Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
+ArrayRef Args, InitializationSequence &Sequence, bool VerifyOnly,
+ExprResult *Result = nullptr);
+
+/// Attempt to initialize an object of a class type either by
+/// direct-initialization, or by copy-initialization from an
+/// expression of the same or derived class type. This corresponds
+/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
+///
+/// \param IsAggrListInit Is this non-list-initialization being done as
+///   part of a list-initialization of an aggregate
+///   from a single expression of the same or
+///   derived class type (C++2c [dcl.init.list] p3.2)?
+static void TryConstructorOrParenListInitialization(
+Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
+MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
+bool IsAggrListInit) {
+  // C++2c [dcl.init.general] p16.6:
+  //   * Otherwise, if the destination type is a class type:
+  // * If the initializer expression is a prvalue and
+  //   the cv-unqualified version of the source type is the same
+  //   as the destination type, the initializer expression is used
+  //   to initialize the destination object.
+  // * Otherwise, if the initialization is direct-initialization,
+  //   or if it is copy-initialization where the cv-unqualified
+  //   version of the source type is the same as or is derived from
+  //   the class of the destination type, constructors are considered.
+  //   The applicable constructors are enumerated, and the best one
+  //   is chosen through overload resolution. Then:
+  //   * If overload resolution is successful, the selected
+  // constructor is called to initialize the object, with
+  // the initializer expression or expression-list as its
+  // argument(s).
+  TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
+   Sequence, /*IsListInit=*/false, IsAggrListInit);
+
+  //   * Otherwise, if no constructor is viable, the destination type
+  // is an aggregate class, and the initializer is a parenthesized
+  // expression-list, the object is initialized as follows. [...]
+  // Parenthesized initialization of aggregates is a C++20 feature.
+  if (S.getLangOpts().CPlusPlus20 &&
+  Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
+  Sequence.getFailureKind() ==
+  InitializationSequence::FK_ConstructorOverloadFailed &&
+  Sequence.getFailedOverloadResult() == OR_No_Viable_Function &&
+  (IsAggrListInit || DestType->isAggregateType()))
+TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
+  /*VerifyOnly=*/true);
+
+  //   * Otherwise, the initialization is ill-for

[clang] [clang] Refine handling of C++20 aggregate initialization (PR #131320)

2025-03-16 Thread via cfe-commits


@@ -6714,7 +6714,8 @@ void InitializationSequence::InitializeFrom(Sema &S,
 OverloadCandidateSet::iterator Best;
 OverloadingResult OR = getFailedCandidateSet().BestViableFunction(
 S, Kind.getLocation(), Best);
-if (OR != OverloadingResult::OR_Deleted) {
+if (OR != OverloadingResult::OR_Deleted &&
+Kind.getKind() == InitializationKind::IK_Direct) {

offsetof wrote:

I discovered a couple more issues in this area, and updated the PR with a more 
comprehensive fix, along with more tests and a release note as requested. 


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


[clang] [C++20][Modules] Prevent premature calls to PassInterestingDeclsToConsumer() within FinishedDeserializing(). (PR #129982)

2025-03-16 Thread Michael Park via cfe-commits

mpark wrote:

Fixes #126973

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


[clang] [clang] Refine handling of C++20 aggregate initialization (PR #131320)

2025-03-16 Thread via cfe-commits

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


[clang] [clang] Refine handling of C++20 aggregate initialization (PR #131320)

2025-03-16 Thread via cfe-commits

https://github.com/offsetof updated 
https://github.com/llvm/llvm-project/pull/131320

>From 6840e3be5a8019acdc115160fc748306e8ce384a Mon Sep 17 00:00:00 2001
From: offsetof 
Date: Sun, 16 Mar 2025 09:59:44 +
Subject: [PATCH] [clang] Refine handling of C++20 aggregate initialization

* Move parts of `InitializationSequence::InitializeFrom` corresponding
  to C++ [dcl.init.general] p16.6.1 and p16.6.2 into a separate
  function, `TryConstructorOrParenListInitialization`
* Use it in `TryListInitialization` to implement [dcl.init.list] p3.2
* Fix parenthesized aggregate initialization being attempted in
  copy-initialization contexts or when the constructor call is ambiguous
---
 clang/docs/ReleaseNotes.rst   |   1 +
 clang/lib/Sema/SemaInit.cpp   | 106 --
 .../dcl.init/dcl.init.general/p16-cxx20.cpp   | 132 --
 3 files changed, 183 insertions(+), 56 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a1c5ee2d788e..22ebf86e05f7d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,6 +281,7 @@ Bug Fixes in This Version
 - Fixed a modules crash where exception specifications were not propagated 
properly (#GH121245, relanded in #GH129982)
 - Fixed a problematic case with recursive deserialization within 
``FinishedDeserializing()`` where
   ``PassInterestingDeclsToConsumer()`` was called before the declarations were 
safe to be passed. (#GH129982)
+- Fixed C++20 aggregate initialization rules being incorrectly applied in 
certain contexts (#GH131320)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 56ec33fe37bf3..56b6cafe5c53d 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -4633,6 +4633,59 @@ static void TryConstructorInitialization(Sema &S,
   IsListInit | IsInitListCopy, AsInitializerList);
 }
 
+static void TryOrBuildParenListInitialization(
+Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
+ArrayRef Args, InitializationSequence &Sequence, bool VerifyOnly,
+ExprResult *Result = nullptr);
+
+/// Attempt to initialize an object of a class type either by
+/// direct-initialization, or by copy-initialization from an
+/// expression of the same or derived class type. This corresponds
+/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
+///
+/// \param IsAggrListInit Is this non-list-initialization being done as
+///   part of a list-initialization of an aggregate
+///   from a single expression of the same or
+///   derived class type (C++2c [dcl.init.list] p3.2)?
+static void TryConstructorOrParenListInitialization(
+Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
+MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
+bool IsAggrListInit) {
+  // C++2c [dcl.init.general] p16.6:
+  //   * Otherwise, if the destination type is a class type:
+  // * If the initializer expression is a prvalue and
+  //   the cv-unqualified version of the source type is the same
+  //   as the destination type, the initializer expression is used
+  //   to initialize the destination object.
+  // * Otherwise, if the initialization is direct-initialization,
+  //   or if it is copy-initialization where the cv-unqualified
+  //   version of the source type is the same as or is derived from
+  //   the class of the destination type, constructors are considered.
+  //   The applicable constructors are enumerated, and the best one
+  //   is chosen through overload resolution. Then:
+  //   * If overload resolution is successful, the selected
+  // constructor is called to initialize the object, with
+  // the initializer expression or expression-list as its
+  // argument(s).
+  TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
+   Sequence, /*IsListInit=*/false, IsAggrListInit);
+
+  //   * Otherwise, if no constructor is viable, the destination type
+  // is an aggregate class, and the initializer is a parenthesized
+  // expression-list, the object is initialized as follows. [...]
+  // Parenthesized initialization of aggregates is a C++20 feature.
+  if (S.getLangOpts().CPlusPlus20 &&
+  Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
+  Sequence.getFailureKind() ==
+  InitializationSequence::FK_ConstructorOverloadFailed &&
+  Sequence.getFailedOverloadResult() == OR_No_Viable_Function &&
+  (IsAggrListInit || DestType->isAggregateType()))
+TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
+  /*VerifyOnly=*/true);
+
+  //   * Otherwise, the initialization is ill-fo

[clang] [llvm] [BPF] Make -mcpu=v3 as the default (PR #107008)

2025-03-16 Thread Yuval Deutscher via cfe-commits

yuvald-sweet-security wrote:

Hey,

I didn't see this change on the [LLVM 20.1.0 Release 
Notes](https://releases.llvm.org/20.1.0/docs/ReleaseNotes.html) - it would be 
nice if you could add those in the future as a heads up.

Anyway, I got here after tracing a regression introduced in Clang 20 with 
sub-par eBPF codegen which results in dramatically larger kernel verifier 
states (and eventually causes the verifier to give up with sufficiently large 
functions). This culprit does indeed seem to be BPF v3 - my guess is that 
branching according to 32-bit registers provides less refutability for the 
verifier which ends up carrying more possible states as a result.

FYI

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


[clang] [Clang][RFC] Intrododuce a builtin to determine the number of (PR #131515)

2025-03-16 Thread via cfe-commits

cor3ntin wrote:

Please look at the doc/tests and confirm this would be suitable to implement 
[`std::exec::tag_of_t`](https://eel.is/c++draft/exec#snd.concepts-5) / P2300

@ldionne @jwakely @StephanTLavavej @philnik777 @ericniebler 

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


[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread via cfe-commits

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


[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread via cfe-commits

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


[clang] Reapply "[analyzer] Delay the checker constructions after parsing" (PR #128369)

2025-03-16 Thread Balazs Benics via cfe-commits

https://github.com/steakhal updated 
https://github.com/llvm/llvm-project/pull/128369

>From ca3c1fb4e9aebb750ac5ed2b0451114ea0c6738c Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Sat, 22 Feb 2025 12:07:23 +0100
Subject: [PATCH] Reapply "[analyzer] Delay the checker constructions after
 parsing" (#128350)

This reverts commit db836edf47f36ed04cab919a7a2c4414f4d0d7e6.
---
 .../Checkers/UnixAPIChecker.cpp   | 61 ++-
 .../Frontend/AnalysisConsumer.cpp | 18 +++---
 2 files changed, 40 insertions(+), 39 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
index a05361f89ed89..897e654f3bbc2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -40,17 +40,28 @@ enum class OpenVariant {
   OpenAt
 };
 
+static std::optional getCreateFlagValue(const ASTContext &Ctx,
+ const Preprocessor &PP) {
+  std::optional MacroVal = tryExpandAsInteger("O_CREAT", PP);
+  if (MacroVal.has_value())
+return MacroVal;
+
+  // If we failed, fall-back to known values.
+  if (Ctx.getTargetInfo().getTriple().getVendor() == llvm::Triple::Apple)
+return {0x0200};
+  return MacroVal;
+}
+
 namespace {
 
-class UnixAPIMisuseChecker
-: public Checker> {
+class UnixAPIMisuseChecker : public Checker {
   const BugType BT_open{this, "Improper use of 'open'", categories::UnixAPI};
   const BugType BT_getline{this, "Improper use of getdelim",
categories::UnixAPI};
   const BugType BT_pthreadOnce{this, "Improper use of 'pthread_once'",
categories::UnixAPI};
   const BugType BT_ArgumentNull{this, "NULL pointer", categories::UnixAPI};
-  mutable std::optional Val_O_CREAT;
+  const std::optional Val_O_CREAT;
 
   ProgramStateRef
   EnsurePtrNotNull(SVal PtrVal, const Expr *PtrExpr, CheckerContext &C,
@@ -63,6 +74,9 @@ class UnixAPIMisuseChecker
   const Expr *SizePtrExpr, CheckerContext &C, ProgramStateRef State) const;
 
 public:
+  UnixAPIMisuseChecker(const ASTContext &Ctx, const Preprocessor &PP)
+  : Val_O_CREAT(getCreateFlagValue(Ctx, PP)) {}
+
   void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager &Mgr,
 BugReporter &BR) const;
 
@@ -134,20 +148,6 @@ ProgramStateRef UnixAPIMisuseChecker::EnsurePtrNotNull(
   return PtrNotNull;
 }
 
-void UnixAPIMisuseChecker::checkASTDecl(const TranslationUnitDecl *TU,
-AnalysisManager &Mgr,
-BugReporter &) const {
-  // The definition of O_CREAT is platform specific.
-  // Try to get the macro value from the preprocessor.
-  Val_O_CREAT = tryExpandAsInteger("O_CREAT", Mgr.getPreprocessor());
-  // If we failed, fall-back to known values.
-  if (!Val_O_CREAT) {
-if (TU->getASTContext().getTargetInfo().getTriple().getVendor() ==
-llvm::Triple::Apple)
-  Val_O_CREAT = 0x0200;
-  }
-}
-
 
//===--===//
 // "open" (man 2 open)
 //===--===/
@@ -262,7 +262,7 @@ void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext 
&C,
 return;
   }
 
-  if (!Val_O_CREAT) {
+  if (!Val_O_CREAT.has_value()) {
 return;
   }
 
@@ -276,7 +276,7 @@ void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext 
&C,
   }
   NonLoc oflags = V.castAs();
   NonLoc ocreateFlag = C.getSValBuilder()
-   .makeIntVal(*Val_O_CREAT, oflagsEx->getType())
+   .makeIntVal(Val_O_CREAT.value(), 
oflagsEx->getType())
.castAs();
   SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
   oflags, ocreateFlag,
@@ -621,14 +621,17 @@ void UnixAPIPortabilityChecker::checkPreStmt(const 
CallExpr *CE,
 // Registration.
 
//===--===//
 
-#define REGISTER_CHECKER(CHECKERNAME)  
\
-  void ento::register##CHECKERNAME(CheckerManager &mgr) {  
\
-mgr.registerChecker();
\
-  }
\
-   
\
-  bool ento::shouldRegister##CHECKERNAME(const CheckerManager &mgr) {  
\
-return true;   
\
-  }
+void ento::registerUnixAPIMisuseChecker(CheckerManager &Mgr) {
+  Mgr.registerChecker(Mgr.getASTContext(),
+Mgr.getPreprocessor());
+}
+bool ento::shouldRegisterUnixAPIMisuseChecker(const CheckerManager &Mgr) {
+  return true;
+}

[clang] Reapply "[analyzer] Delay the checker constructions after parsing" (PR #128369)

2025-03-16 Thread Balazs Benics via cfe-commits

steakhal wrote:

Ping @Xazax-hun @NagyDonat 

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


[clang] [Clang] Implement Wpointer-bool-conversion-strict (PR #131523)

2025-03-16 Thread Yutong Zhu via cfe-commits

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


[clang] [clang][CIR] Add missing dependency on MLIR headers (PR #131057)

2025-03-16 Thread via cfe-commits

https://github.com/darkbuck updated 
https://github.com/llvm/llvm-project/pull/131057

>From 255050e6d1e3ebbf25b30c17a10be14d29e5dae7 Mon Sep 17 00:00:00 2001
From: Michael Liao 
Date: Tue, 4 Mar 2025 12:47:24 -0500
Subject: [PATCH] [clang][CIR] Add missing dependency on MLIR headers

- Add dependency on MLIRBuiltinOpsIncGen as
  "clang/CIR/FrontendAction/CIRGenAction.h" needs to include
  "mlir/IR/BuiltinOps.h"
---
 clang/lib/CIR/FrontendAction/CMakeLists.txt | 1 +
 clang/lib/FrontendTool/CMakeLists.txt   | 3 +++
 2 files changed, 4 insertions(+)

diff --git a/clang/lib/CIR/FrontendAction/CMakeLists.txt 
b/clang/lib/CIR/FrontendAction/CMakeLists.txt
index 6d5a8758468f6..1ebac07f44662 100644
--- a/clang/lib/CIR/FrontendAction/CMakeLists.txt
+++ b/clang/lib/CIR/FrontendAction/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_library(clangCIRFrontendAction
   DEPENDS
   MLIRCIROpsIncGen
   MLIRCIROpInterfacesIncGen
+  MLIRBuiltinOpsIncGen
 
   LINK_LIBS
   clangAST
diff --git a/clang/lib/FrontendTool/CMakeLists.txt 
b/clang/lib/FrontendTool/CMakeLists.txt
index d7a3699361f0a..7c83086a7da3b 100644
--- a/clang/lib/FrontendTool/CMakeLists.txt
+++ b/clang/lib/FrontendTool/CMakeLists.txt
@@ -15,6 +15,9 @@ set(link_libs
 set(deps)
 
 if(CLANG_ENABLE_CIR)
+  list(APPEND deps
+MLIRBuiltinOpsIncGen
+  )
   list(APPEND link_libs
 clangCIRFrontendAction
 MLIRIR

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


[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread Younan Zhang via cfe-commits


@@ -4160,6 +4160,54 @@ static bool CheckVecStepTraitOperandType(Sema &S, 
QualType T,
   return false;
 }
 
+static ExprResult BuildStructuredBindingSizeTraitImpl(Sema &S, QualType T,
+  Expr *E,
+  TypeSourceInfo *TInfo,
+  SourceLocation Loc,
+  SourceRange ArgRange) {
+  assert(!!E != !!TInfo);
+  assert(!T->isDependentType());
+  std::optional Size =
+  S.GetDecompositionElementCount(T, ArgRange.getBegin());
+  if (!Size) {
+return S.Diag(Loc, diag::err_arg_is_not_destructurable) << T << ArgRange;

zyn0217 wrote:

Looking closer I'm surprised a SemaDiagnosticBuilder could be implicitly 
converted to ExprResult. Is that due to the implicit operator bool()?

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


[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread Younan Zhang via cfe-commits


@@ -4160,6 +4160,54 @@ static bool CheckVecStepTraitOperandType(Sema &S, 
QualType T,
   return false;
 }
 
+static ExprResult BuildStructuredBindingSizeTraitImpl(Sema &S, QualType T,
+  Expr *E,
+  TypeSourceInfo *TInfo,
+  SourceLocation Loc,
+  SourceRange ArgRange) {
+  assert(!!E != !!TInfo);
+  assert(!T->isDependentType());
+  std::optional Size =
+  S.GetDecompositionElementCount(T, ArgRange.getBegin());
+  if (!Size) {
+return S.Diag(Loc, diag::err_arg_is_not_destructurable) << T << ArgRange;

zyn0217 wrote:

```suggestion
S.Diag(Loc, diag::err_arg_is_not_destructurable) << T << ArgRange;
```

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


[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread Younan Zhang via cfe-commits


@@ -0,0 +1,168 @@
+// RUN: %clang_cc1 %s -std=c++2c -fsyntax-only -verify
+
+struct S0 {};
+struct S1 {int a;};
+struct S2 {int a; int b;};
+struct S3 {double a; int b; int c;};
+
+
+
+struct SD : S1 {};
+struct SE1 : S1 { int b;};
+
+class  P1 {int a;}; // #note-private
+
+
+template 
+concept is_destructurable = requires {
+{ __builtin_structured_binding_size(T) };
+};
+
+static_assert(__builtin_structured_binding_size(S0) == 0);
+static_assert(__is_same_as(decltype(__builtin_structured_binding_size(S0)), 
decltype(sizeof(void*;
+
+static_assert(__builtin_structured_binding_size(S1) == 0);
+// expected-error@-1 {{static assertion failed due to requirement 
'__builtin_structured_binding_size(S1) == 0'}} \
+// expected-note@-1 {{expression evaluates to '1 == 0'}}
+static_assert(__builtin_structured_binding_size(S1) == 1);
+static_assert(__builtin_structured_binding_size(SD) == 1);
+static_assert(__builtin_structured_binding_size(SE1) == 1);
+// expected-error@-1 {{cannot decompose class type 'SE1': both it and its base 
class 'S1' have non-static data members}} \
+// expected-error@-1 {{type 'SE1' is not destructurable}}
+
+
+static_assert(__builtin_structured_binding_size(int[0]) == 0);
+static_assert(__builtin_structured_binding_size(int[1]) == 1);
+static_assert(__builtin_structured_binding_size(int[42]) == 42);
+
+using vec2 = int __attribute__((__vector_size__(2 * sizeof(int;
+using vec3 = int __attribute__((__vector_size__(3 * sizeof(int;
+static_assert(__builtin_structured_binding_size(vec2) == 2);
+static_assert(__builtin_structured_binding_size(vec3) == 3);
+static_assert(__builtin_structured_binding_size(__builtin_complex(0., 0.)) == 
2);
+static_assert(__builtin_structured_binding_size(decltype(__builtin_complex(0., 
0.))) == 2);
+
+
+int VLASize; // expected-note {{declared here}}
+static_assert(__builtin_structured_binding_size(int[VLASize]) == 42);
+// expected-error@-1 {{type 'int[VLASize]' is not destructurable}} \
+// expected-warning@-1 {{variable length arrays in C++ are a Clang extension}} 
\
+// expected-note@-1 {{read of non-const variable 'VLASize' is not allowed in a 
constant expression}}
+
+
+struct Incomplete; // expected-note {{forward declaration of 'Incomplete'}}
+static_assert(__builtin_structured_binding_size(Incomplete) == 1);
+// expected-error@-1 {{incomplete type 'Incomplete' where a complete type is 
required}} \
+// expected-error@-1 {{type 'Incomplete' is not destructurable}}
+static_assert(__builtin_structured_binding_size(Incomplete[]) == 1);
+// expected-error@-1 {{type 'Incomplete[]' is not destructurable}}
+static_assert(__builtin_structured_binding_size(Incomplete[0]) == 0);
+static_assert(__builtin_structured_binding_size(Incomplete[1]) == 1);
+static_assert(__builtin_structured_binding_size(Incomplete[42]) == 42);
+
+
+static_assert(__builtin_structured_binding_size(P1) == 0);
+// expected-error@-1 {{static assertion failed due to requirement 
'__builtin_structured_binding_size(P1) == 0'}} \
+// expected-note@-1 {{expression evaluates to '1 == 0'}} \
+// expected-error@-1 {{cannot decompose private member 'a' of 'P1}} \
+// expected-note@#note-private {{implicitly declared private here}}
+
+
+static_assert(is_destructurable);
+static_assert(is_destructurable);
+static_assert(!is_destructurable);
+static_assert(!is_destructurable);
+static_assert(!is_destructurable);
+static_assert(is_destructurable);
+static_assert(!is_destructurable);
+
+template 
+constexpr int f() {return 0;};
+template 
+requires is_destructurable
+constexpr int f() {return 1;};
+
+static_assert(f() == 0);
+static_assert(f()  == 1);
+
+struct T0;
+struct T1;
+struct T42;
+struct TSizeError;
+
+namespace std {
+
+template 
+struct tuple_size;
+
+template <>
+struct tuple_size {
+static constexpr int value = 0;
+};
+
+template <>
+struct tuple_size {
+static constexpr int value = 1;
+};
+
+template <>
+struct tuple_size {
+static constexpr int value = 42;
+};
+
+template <>
+struct tuple_size {
+static constexpr void* value = nullptr;
+};
+
+static_assert(__builtin_structured_binding_size(T0) == 0);
+static_assert(__builtin_structured_binding_size(T1) == 1);
+static_assert(__builtin_structured_binding_size(T42) == 42);
+static_assert(__builtin_structured_binding_size(TSizeError) == 42);
+// expected-error@-1 {{cannot decompose this type; 
'std::tuple_size::value' is not a valid integral constant 
expression}} \
+// expected-error@-1 {{type 'TSizeError' is not destructurable}}
+static_assert(!is_destructurable);
+}
+
+
+void test_expr(S1 & s1, S2 && s2, T0 & t0, int i, const S1 & s1c, int arr[2]) {
+static_assert(__builtin_structured_binding_size(s1) == 1);
+static_assert(__builtin_structured_binding_size(s1c) == 1);
+static_assert(__builtin_structured_binding_size(s2) == 2);
+static_assert(__builtin_structured_binding_size(t0) == 0);
+static_assert(__builtin_structured_binding_size(i));
+// expected-error@-1 {{type 'in

[clang] [llvm] [flang-rt] Pass the whole path of libflang_rt.runtime.a to linker on AIX (PR #131041)

2025-03-16 Thread Daniel Chen via cfe-commits

https://github.com/DanielCChen updated 
https://github.com/llvm/llvm-project/pull/131041

>From 9d3e16f3e7c5adf4b5e0c1c6ba861d9e0ffea23b Mon Sep 17 00:00:00 2001
From: Daniel Chen 
Date: Wed, 12 Mar 2025 18:23:14 -0400
Subject: [PATCH 1/8] [flang-rt] Pass the whole path of libflang_rt.runtime.a
 to linker on AIX.

---
 clang/lib/Driver/ToolChains/CommonArgs.cpp | 11 ++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index b43472a52038b..21f934cdba468 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1345,7 +1345,16 @@ void tools::addFortranRuntimeLibs(const ToolChain &TC, 
const ArgList &Args,
   if (AsNeeded)
 addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false);
 }
-CmdArgs.push_back("-lflang_rt.runtime");
+if (TC.getTriple().isOSAIX()) {
+  // On AIX, pass the whole path of flang_rt.runtime.a to be consistent
+  // with clang.
+  std::string CRTBasename = "libflang_rt.runtime.a";
+  SmallString<128> Path(TC.getCompilerRTPath());
+  llvm::sys::path::append(Path, CRTBasename);
+  if (TC.getVFS().exists(Path))
+CmdArgs.push_back(Args.MakeArgString(std::string(Path)));
+} else
+  CmdArgs.push_back("-lflang_rt.runtime");
 addArchSpecificRPath(TC, Args, CmdArgs);
 
 // needs libexecinfo for backtrace functions

>From 0cc486e4dda5aec6a3330758767709bedc69c186 Mon Sep 17 00:00:00 2001
From: Daniel Chen 
Date: Sat, 15 Mar 2025 16:27:08 -0400
Subject: [PATCH 2/8] [flang-rt] Re-implement driver code of how flang-rt path
 is built.

---
 clang/include/clang/Driver/ToolChain.h| 23 --
 clang/lib/Driver/ToolChain.cpp| 80 ---
 clang/lib/Driver/ToolChains/AIX.cpp   | 27 ++-
 clang/lib/Driver/ToolChains/AIX.h |  7 ++
 clang/lib/Driver/ToolChains/AVR.cpp   |  3 +-
 clang/lib/Driver/ToolChains/AVR.h |  3 +-
 clang/lib/Driver/ToolChains/CommonArgs.cpp| 64 ---
 clang/lib/Driver/ToolChains/CommonArgs.h  |  9 ---
 clang/lib/Driver/ToolChains/Darwin.cpp|  8 +-
 clang/lib/Driver/ToolChains/Darwin.h  |  6 +-
 clang/lib/Driver/ToolChains/DragonFly.cpp |  4 +-
 clang/lib/Driver/ToolChains/FreeBSD.cpp   |  4 +-
 clang/lib/Driver/ToolChains/Gnu.cpp   |  4 +-
 clang/lib/Driver/ToolChains/Haiku.cpp |  4 +-
 clang/lib/Driver/ToolChains/MSVC.cpp  |  4 +-
 clang/lib/Driver/ToolChains/MinGW.cpp |  4 +-
 clang/lib/Driver/ToolChains/MipsLinux.cpp |  3 +-
 clang/lib/Driver/ToolChains/MipsLinux.h   |  3 +-
 clang/lib/Driver/ToolChains/NetBSD.cpp|  4 +-
 clang/lib/Driver/ToolChains/OHOS.cpp  |  2 +-
 clang/lib/Driver/ToolChains/OHOS.h|  3 +-
 clang/lib/Driver/ToolChains/OpenBSD.cpp   | 11 +--
 clang/lib/Driver/ToolChains/OpenBSD.h |  3 +-
 clang/lib/Driver/ToolChains/PPCLinux.cpp  | 35 
 clang/lib/Driver/ToolChains/PPCLinux.h|  7 ++
 clang/lib/Driver/ToolChains/Solaris.cpp   |  4 +-
 flang-rt/cmake/modules/GetToolchainDirs.cmake |  2 +
 27 files changed, 206 insertions(+), 125 deletions(-)

diff --git a/clang/include/clang/Driver/ToolChain.h 
b/clang/include/clang/Driver/ToolChain.h
index 90004c64a694a..dc23bdf2ffd05 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -216,8 +216,8 @@ class ToolChain {
 
   virtual std::string buildCompilerRTBasename(const llvm::opt::ArgList &Args,
   StringRef Component,
-  FileType Type,
-  bool AddArch) const;
+  FileType Type, bool AddArch,
+  bool IsFortran = false) const;
 
   /// Find the target-specific subdirectory for the current target triple under
   /// \p BaseDir, doing fallback triple searches as necessary.
@@ -509,11 +509,22 @@ class ToolChain {
 
   virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
 StringRef Component,
-FileType Type = ToolChain::FT_Static) 
const;
+FileType Type = ToolChain::FT_Static,
+bool IsFortran = false) const;
+
+  /// Adds Fortran runtime libraries to \p CmdArgs.
+  virtual void addFortranRuntimeLibs(const llvm::opt::ArgList &Args,
+ llvm::opt::ArgStringList &CmdArgs) const;
+
+  /// Adds the path for the Fortran runtime libraries to \p CmdArgs.
+  virtual void
+  addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args,
+   llvm::opt::ArgStringList &CmdArgs) const;
 
-  const char *
-  getCompilerRTArgStri

[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread Eric Niebler via cfe-commits


@@ -434,6 +434,36 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+.. _builtin_structured_binding_size-doc:
+
+__builtin_structured_binding_size (C++)
+---
+``__builtin_structured_binding_size`` returns the *structured binding size*
+([dcl.struct.bind]) of the type ``T`` (or unevaluate expression ``arg``)
+passed as argument.
+
+This is equivalent to the size of the pack ``p`` in ``auto&& [...p] = arg;``.
+If the argument is not destructurable (ie not an array, vector, complex,

ericniebler wrote:

Is `vector` really destructurable?

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


[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread via cfe-commits


@@ -434,6 +434,36 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+.. _builtin_structured_binding_size-doc:
+
+__builtin_structured_binding_size (C++)
+---
+``__builtin_structured_binding_size`` returns the *structured binding size*
+([dcl.struct.bind]) of the type ``T`` (or unevaluate expression ``arg``)
+passed as argument.
+
+This is equivalent to the size of the pack ``p`` in ``auto&& [...p] = arg;``.
+If the argument is not destructurable (ie not an array, vector, complex,

cor3ntin wrote:

I guess I should be more specific here.
I meant built in arrays and simd vectors, not the STL types
https://clang.llvm.org/docs/LanguageExtensions.html#vectors-and-extended-vectors

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


[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread Eric Niebler via cfe-commits


@@ -434,6 +434,36 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+.. _builtin_structured_binding_size-doc:
+
+__builtin_structured_binding_size (C++)
+---
+``__builtin_structured_binding_size`` returns the *structured binding size*
+([dcl.struct.bind]) of the type ``T`` (or unevaluate expression ``arg``)

ericniebler wrote:

```suggestion
([dcl.struct.bind]) of the type ``T`` (or unevaluated expression ``arg``)
```


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


[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread A. Jiang via cfe-commits


@@ -434,6 +434,36 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+.. _builtin_structured_binding_size-doc:
+
+__builtin_structured_binding_size (C++)
+---
+``__builtin_structured_binding_size`` returns the *structured binding size*
+([dcl.struct.bind]) of the type ``T`` (or unevaluate expression ``arg``)
+passed as argument.
+
+This is equivalent to the size of the pack ``p`` in ``auto&& [...p] = arg;``.
+If the argument is not destructurable (ie not an array, vector, complex,

frederick-vs-ja wrote:

I guess we should mention built-in array here.

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


[clang-tools-extra] [clang-tidy] offer option to check sugared types in avoid-c-arrays check (PR #131468)

2025-03-16 Thread via cfe-commits


@@ -72,3 +72,9 @@ can be either ``char* argv[]`` or ``char** argv``, but cannot 
be
   .. code:: c++
 
 const char name[] = "Some name";
+
+.. option:: CheckSugaredTypes
+
+  When set to `true` (default is `false`), type aliases, decltypes as well as

EugeneZelenko wrote:

Please make `Default is false` dedicated sentence at the end of option 
description.

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


[clang-tools-extra] [clang-tidy] offer option to check sugared types in avoid-c-arrays check (PR #131468)

2025-03-16 Thread Baranov Victor via cfe-commits


@@ -72,3 +72,9 @@ can be either ``char* argv[]`` or ``char** argv``, but cannot 
be
   .. code:: c++
 
 const char name[] = "Some name";
+
+.. option:: CheckSugaredTypes
+
+  When set to `true` (default is `false`), type aliases, decltypes as well as

vbvictor wrote:

Also, previous option `AllowStringArrays` should also be transformed, imo

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


[clang] [clang][opencl] Allow passing all zeros to reqd_work_group_size (PR #131543)

2025-03-16 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov created 
https://github.com/llvm/llvm-project/pull/131543

Allow passing all zeros to reqd_work_group_size.

Quote from 
https://rocm.docs.amd.com/projects/llvm-project/en/latest/LLVM/llvm/html/AMDGPUUsage.html#amdgpu-amdhsa-code-object-kernel-argument-metadata-map-v2-table:
"If not 0, 0, 0 then all values must be >=1 and the dispatch work-group size X, 
Y, Z must correspond to the specified values. Defaults to 0, 0, 0."

Supporting these default values is a small ergonomic improvement, particularly 
for generic/templated code.

Test plan: ninja check-all

>From eed71b8c5a5ae670fa33ce4c20c9cbb72bbcf511 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Sun, 16 Mar 2025 22:27:05 +
Subject: [PATCH] [clang][opencl] Allow passing all zeros to
 reqd_work_group_size

---
 clang/lib/Sema/SemaDeclAttr.cpp   | 12 +---
 clang/test/CodeGenCUDASPIRV/spirv-attrs.cu|  6 ++
 clang/test/SemaOpenCL/invalid-kernel-attrs.cl |  2 ++
 3 files changed, 17 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index bc858c63f69b6..c664ae30d2faf 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2923,10 +2923,16 @@ static void handleWorkGroupSize(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 if (!S.checkUInt32Argument(AL, E, WGSize[i], i,
/*StrictlyUnsigned=*/true))
   return;
-if (WGSize[i] == 0) {
-  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
+  }
+
+  if (!llvm::all_of(WGSize,  [](uint32_t Size) { return Size == 0; })) {
+for (unsigned i = 0; i < 3; ++i) {
+  const Expr *E = AL.getArgAsExpr(i);
+  if (WGSize[i] == 0) {
+S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
   << AL << E->getSourceRange();
-  return;
+return;
+  }
 }
   }
 
diff --git a/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu 
b/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
index 466aee00717a0..727e0e233329c 100644
--- a/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
+++ b/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
@@ -3,6 +3,9 @@
 
 #define __global__ __attribute__((global))
 
+__attribute__((reqd_work_group_size(0, 0, 0)))
+__global__ void reqd_work_group_size_0_0_0() {}
+
 __attribute__((reqd_work_group_size(128, 1, 1)))
 __global__ void reqd_work_group_size_128_1_1() {}
 
@@ -15,6 +18,8 @@ __global__ void vec_type_hint_int() {}
 __attribute__((intel_reqd_sub_group_size(64)))
 __global__ void intel_reqd_sub_group_size_64() {}
 
+
+// CHECK: define spir_kernel void @_Z26reqd_work_group_size_0_0_0v() 
#[[ATTR:[0-9]+]] !reqd_work_group_size ![[WG_SIZE_ZEROS:[0-9]+]]
 // CHECK: define spir_kernel void @_Z28reqd_work_group_size_128_1_1v() 
#[[ATTR:[0-9]+]] !reqd_work_group_size ![[WG_SIZE:[0-9]+]]
 // CHECK: define spir_kernel void @_Z26work_group_size_hint_2_2_2v() #[[ATTR]] 
!work_group_size_hint ![[WG_HINT:[0-9]+]]
 // CHECK: define spir_kernel void @_Z17vec_type_hint_intv() #[[ATTR]] 
!vec_type_hint ![[VEC_HINT:[0-9]+]]
@@ -22,6 +27,7 @@ __global__ void intel_reqd_sub_group_size_64() {}
 
 // CHECK: attributes #[[ATTR]] = { {{.*}} }
 
+// CHECK: ![[WG_SIZE_ZEROS]] = !{i32 0, i32 0, i32 0}
 // CHECK: ![[WG_SIZE]] = !{i32 128, i32 1, i32 1}
 // CHECK: ![[WG_HINT]] = !{i32 2, i32 2, i32 2}
 // CHECK: ![[VEC_HINT]] = !{i32 undef, i32 1}
diff --git a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl 
b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
index 0883379601ef2..e913e363ef4a1 100644
--- a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
+++ b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
@@ -44,3 +44,5 @@ __kernel __attribute__((reqd_work_group_size(8,16,-32))) void 
neg2(){} // expect
 // 4294967294 is a negative integer if treated as signed.
 // Should compile successfully, since we expect an unsigned.
 __kernel __attribute__((reqd_work_group_size(8,16,4294967294))) void ok1(){}
+
+__kernel __attribute__((reqd_work_group_size(0,0,0))) void ok_zeros(){}

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


[clang] [clang][opencl] Allow passing all zeros to reqd_work_group_size (PR #131543)

2025-03-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alexander Shaposhnikov (alexander-shaposhnikov)


Changes

Allow passing all zeros to reqd_work_group_size.

Quote from 
https://rocm.docs.amd.com/projects/llvm-project/en/latest/LLVM/llvm/html/AMDGPUUsage.html#amdgpu-amdhsa-code-object-kernel-argument-metadata-map-v2-table:
"If not 0, 0, 0 then all values must be >=1 and the dispatch work-group size 
X, Y, Z must correspond to the specified values. Defaults to 0, 0, 0."

Supporting these default values is a small ergonomic improvement, particularly 
for generic/templated code.

Test plan: ninja check-all

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


3 Files Affected:

- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+9-3) 
- (modified) clang/test/CodeGenCUDASPIRV/spirv-attrs.cu (+6) 
- (modified) clang/test/SemaOpenCL/invalid-kernel-attrs.cl (+2) 


``diff
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index bc858c63f69b6..c664ae30d2faf 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2923,10 +2923,16 @@ static void handleWorkGroupSize(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 if (!S.checkUInt32Argument(AL, E, WGSize[i], i,
/*StrictlyUnsigned=*/true))
   return;
-if (WGSize[i] == 0) {
-  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
+  }
+
+  if (!llvm::all_of(WGSize,  [](uint32_t Size) { return Size == 0; })) {
+for (unsigned i = 0; i < 3; ++i) {
+  const Expr *E = AL.getArgAsExpr(i);
+  if (WGSize[i] == 0) {
+S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
   << AL << E->getSourceRange();
-  return;
+return;
+  }
 }
   }
 
diff --git a/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu 
b/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
index 466aee00717a0..727e0e233329c 100644
--- a/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
+++ b/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
@@ -3,6 +3,9 @@
 
 #define __global__ __attribute__((global))
 
+__attribute__((reqd_work_group_size(0, 0, 0)))
+__global__ void reqd_work_group_size_0_0_0() {}
+
 __attribute__((reqd_work_group_size(128, 1, 1)))
 __global__ void reqd_work_group_size_128_1_1() {}
 
@@ -15,6 +18,8 @@ __global__ void vec_type_hint_int() {}
 __attribute__((intel_reqd_sub_group_size(64)))
 __global__ void intel_reqd_sub_group_size_64() {}
 
+
+// CHECK: define spir_kernel void @_Z26reqd_work_group_size_0_0_0v() 
#[[ATTR:[0-9]+]] !reqd_work_group_size ![[WG_SIZE_ZEROS:[0-9]+]]
 // CHECK: define spir_kernel void @_Z28reqd_work_group_size_128_1_1v() 
#[[ATTR:[0-9]+]] !reqd_work_group_size ![[WG_SIZE:[0-9]+]]
 // CHECK: define spir_kernel void @_Z26work_group_size_hint_2_2_2v() #[[ATTR]] 
!work_group_size_hint ![[WG_HINT:[0-9]+]]
 // CHECK: define spir_kernel void @_Z17vec_type_hint_intv() #[[ATTR]] 
!vec_type_hint ![[VEC_HINT:[0-9]+]]
@@ -22,6 +27,7 @@ __global__ void intel_reqd_sub_group_size_64() {}
 
 // CHECK: attributes #[[ATTR]] = { {{.*}} }
 
+// CHECK: ![[WG_SIZE_ZEROS]] = !{i32 0, i32 0, i32 0}
 // CHECK: ![[WG_SIZE]] = !{i32 128, i32 1, i32 1}
 // CHECK: ![[WG_HINT]] = !{i32 2, i32 2, i32 2}
 // CHECK: ![[VEC_HINT]] = !{i32 undef, i32 1}
diff --git a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl 
b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
index 0883379601ef2..e913e363ef4a1 100644
--- a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
+++ b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
@@ -44,3 +44,5 @@ __kernel __attribute__((reqd_work_group_size(8,16,-32))) void 
neg2(){} // expect
 // 4294967294 is a negative integer if treated as signed.
 // Should compile successfully, since we expect an unsigned.
 __kernel __attribute__((reqd_work_group_size(8,16,4294967294))) void ok1(){}
+
+__kernel __attribute__((reqd_work_group_size(0,0,0))) void ok_zeros(){}

``




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


[clang] [clang][opencl] Allow passing all zeros to reqd_work_group_size (PR #131543)

2025-03-16 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/131543

>From e1781606a72e86a13b032928f35403a2859f38b2 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Sun, 16 Mar 2025 22:27:05 +
Subject: [PATCH] [clang][opencl] Allow passing all zeros to
 reqd_work_group_size

---
 clang/lib/Sema/SemaDeclAttr.cpp   | 14 ++
 clang/test/CodeGenCUDASPIRV/spirv-attrs.cu|  6 ++
 clang/test/SemaOpenCL/invalid-kernel-attrs.cl |  2 ++
 3 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index bc858c63f69b6..769f5316ed934 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2923,10 +2923,16 @@ static void handleWorkGroupSize(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 if (!S.checkUInt32Argument(AL, E, WGSize[i], i,
/*StrictlyUnsigned=*/true))
   return;
-if (WGSize[i] == 0) {
-  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
-  << AL << E->getSourceRange();
-  return;
+  }
+
+  if (!llvm::all_of(WGSize, [](uint32_t Size) { return Size == 0; })) {
+for (unsigned i = 0; i < 3; ++i) {
+  const Expr *E = AL.getArgAsExpr(i);
+  if (WGSize[i] == 0) {
+S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
+<< AL << E->getSourceRange();
+return;
+  }
 }
   }
 
diff --git a/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu 
b/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
index 466aee00717a0..727e0e233329c 100644
--- a/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
+++ b/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
@@ -3,6 +3,9 @@
 
 #define __global__ __attribute__((global))
 
+__attribute__((reqd_work_group_size(0, 0, 0)))
+__global__ void reqd_work_group_size_0_0_0() {}
+
 __attribute__((reqd_work_group_size(128, 1, 1)))
 __global__ void reqd_work_group_size_128_1_1() {}
 
@@ -15,6 +18,8 @@ __global__ void vec_type_hint_int() {}
 __attribute__((intel_reqd_sub_group_size(64)))
 __global__ void intel_reqd_sub_group_size_64() {}
 
+
+// CHECK: define spir_kernel void @_Z26reqd_work_group_size_0_0_0v() 
#[[ATTR:[0-9]+]] !reqd_work_group_size ![[WG_SIZE_ZEROS:[0-9]+]]
 // CHECK: define spir_kernel void @_Z28reqd_work_group_size_128_1_1v() 
#[[ATTR:[0-9]+]] !reqd_work_group_size ![[WG_SIZE:[0-9]+]]
 // CHECK: define spir_kernel void @_Z26work_group_size_hint_2_2_2v() #[[ATTR]] 
!work_group_size_hint ![[WG_HINT:[0-9]+]]
 // CHECK: define spir_kernel void @_Z17vec_type_hint_intv() #[[ATTR]] 
!vec_type_hint ![[VEC_HINT:[0-9]+]]
@@ -22,6 +27,7 @@ __global__ void intel_reqd_sub_group_size_64() {}
 
 // CHECK: attributes #[[ATTR]] = { {{.*}} }
 
+// CHECK: ![[WG_SIZE_ZEROS]] = !{i32 0, i32 0, i32 0}
 // CHECK: ![[WG_SIZE]] = !{i32 128, i32 1, i32 1}
 // CHECK: ![[WG_HINT]] = !{i32 2, i32 2, i32 2}
 // CHECK: ![[VEC_HINT]] = !{i32 undef, i32 1}
diff --git a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl 
b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
index 0883379601ef2..e913e363ef4a1 100644
--- a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
+++ b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
@@ -44,3 +44,5 @@ __kernel __attribute__((reqd_work_group_size(8,16,-32))) void 
neg2(){} // expect
 // 4294967294 is a negative integer if treated as signed.
 // Should compile successfully, since we expect an unsigned.
 __kernel __attribute__((reqd_work_group_size(8,16,4294967294))) void ok1(){}
+
+__kernel __attribute__((reqd_work_group_size(0,0,0))) void ok_zeros(){}

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


[clang] 91328db - [clang-format] Correctly annotate user-defined conversion functions (#131434)

2025-03-16 Thread via cfe-commits

Author: Owen Pan
Date: 2025-03-16T16:11:39-07:00
New Revision: 91328dbae986dfa93cf2acef0a93361fd5ced66d

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

LOG: [clang-format] Correctly annotate user-defined conversion functions 
(#131434)

Also fix/delete existing invalid/redundant test cases.

Fix #130894

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 77935e75d4b4c..3808872d227a9 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -746,6 +746,10 @@ struct FormatToken {
 return isOneOf(tok::star, tok::amp, tok::ampamp);
   }
 
+  bool isPlacementOperator() const {
+return isOneOf(tok::kw_new, tok::kw_delete);
+  }
+
   bool isUnaryOperator() const {
 switch (Tok.getKind()) {
 case tok::plus:

diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 16f0a76f3a954..eed54a11684b5 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -610,9 +610,9 @@ bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
   tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
   tok::colon, tok::question, tok::tilde) ||
  Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
-  tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
-  tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) 
||
- Tok->isBinaryOperator();
+  tok::kw_else, tok::kw_void, tok::kw_typeof,
+  Keywords.kw_instanceof, Keywords.kw_in) ||
+ Tok->isPlacementOperator() || Tok->isBinaryOperator();
 }
 
 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 08539de405c67..35577cd6db7a1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1639,6 +1639,31 @@ class AnnotatingParser {
 case tok::kw_operator:
   if (Style.isProto())
 break;
+  // Handle C++ user-defined conversion function.
+  if (IsCpp && CurrentToken) {
+const auto *Info = CurrentToken->Tok.getIdentifierInfo();
+// What follows Tok is an identifier or a non-operator keyword.
+if (Info && !(CurrentToken->isPlacementOperator() ||
+  CurrentToken->is(tok::kw_co_await) ||
+  Info->isCPlusPlusOperatorKeyword())) {
+  FormatToken *LParen;
+  if (CurrentToken->startsSequence(tok::kw_decltype, tok::l_paren,
+   tok::kw_auto, tok::r_paren)) {
+// Skip `decltype(auto)`.
+LParen = CurrentToken->Next->Next->Next->Next;
+  } else {
+// Skip to l_paren.
+for (LParen = CurrentToken->Next;
+ LParen && LParen->isNot(tok::l_paren); LParen = LParen->Next) 
{
+}
+  }
+  if (LParen && LParen->is(tok::l_paren)) {
+Tok->setFinalizedType(TT_FunctionDeclarationName);
+LParen->setFinalizedType(TT_FunctionDeclarationLParen);
+break;
+  }
+}
+  }
   while (CurrentToken &&
  !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
 if (CurrentToken->isOneOf(tok::star, tok::amp))
@@ -2999,7 +3024,7 @@ class AnnotatingParser {
   return TT_UnaryOperator;
 if (PrevToken->is(TT_TypeName))
   return TT_PointerOrReference;
-if (PrevToken->isOneOf(tok::kw_new, tok::kw_delete) && Tok.is(tok::ampamp))
+if (PrevToken->isPlacementOperator() && Tok.is(tok::ampamp))
   return TT_BinaryOperator;
 
 const FormatToken *NextToken = Tok.getNextNonComment();
@@ -3071,12 +3096,10 @@ class AnnotatingParser {
 if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
   return TT_BinaryOperator;
 
-// "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
-// unary "&".
-if (Tok.is(tok::ampamp) &&
-NextToken->isOneOf(tok::l_paren, tok::star, tok::amp)) {
+// "&&" followed by "*" or "&" is quite unlikely to be two successive unary
+// "&".
+if (Tok.is(tok::ampamp) && NextToken->isOneOf(tok::star, tok::amp))
   return TT_BinaryOperator;
-}
 
 // This catches some cases where evaluation order is used as control flow:
 //   aaa && aaa->f();
@@ -3791,7 +3814,7 @@ static bool is

[clang] [clang-format] Correctly annotate user-defined conversion functions (PR #131434)

2025-03-16 Thread Owen Pan via cfe-commits

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


[clang] [clang][opencl] Allow passing all zeros to reqd_work_group_size (PR #131543)

2025-03-16 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 3e6f618e86f5fbad2c2d5802416ec3d3366a2837 
eed71b8c5a5ae670fa33ce4c20c9cbb72bbcf511 --extensions cpp -- 
clang/lib/Sema/SemaDeclAttr.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index c664ae30d2..769f5316ed 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2925,12 +2925,12 @@ static void handleWorkGroupSize(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   return;
   }
 
-  if (!llvm::all_of(WGSize,  [](uint32_t Size) { return Size == 0; })) {
+  if (!llvm::all_of(WGSize, [](uint32_t Size) { return Size == 0; })) {
 for (unsigned i = 0; i < 3; ++i) {
   const Expr *E = AL.getArgAsExpr(i);
   if (WGSize[i] == 0) {
 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
-  << AL << E->getSourceRange();
+<< AL << E->getSourceRange();
 return;
   }
 }

``




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


[clang] 2dc123b - [clang][opencl] Allow passing all zeros to reqd_work_group_size (#131543)

2025-03-16 Thread via cfe-commits

Author: Alexander Shaposhnikov
Date: 2025-03-16T16:21:46-07:00
New Revision: 2dc123b33d51fcccb9e1af7230bc6573f77b3ccc

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

LOG: [clang][opencl] Allow passing all zeros to reqd_work_group_size (#131543)

Allow passing all zeros to reqd_work_group_size.

Test plan: ninja check-all

Added: 


Modified: 
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
clang/test/SemaOpenCL/invalid-kernel-attrs.cl

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index bc858c63f69b6..769f5316ed934 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2923,10 +2923,16 @@ static void handleWorkGroupSize(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 if (!S.checkUInt32Argument(AL, E, WGSize[i], i,
/*StrictlyUnsigned=*/true))
   return;
-if (WGSize[i] == 0) {
-  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
-  << AL << E->getSourceRange();
-  return;
+  }
+
+  if (!llvm::all_of(WGSize, [](uint32_t Size) { return Size == 0; })) {
+for (unsigned i = 0; i < 3; ++i) {
+  const Expr *E = AL.getArgAsExpr(i);
+  if (WGSize[i] == 0) {
+S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
+<< AL << E->getSourceRange();
+return;
+  }
 }
   }
 

diff  --git a/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu 
b/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
index 466aee00717a0..727e0e233329c 100644
--- a/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
+++ b/clang/test/CodeGenCUDASPIRV/spirv-attrs.cu
@@ -3,6 +3,9 @@
 
 #define __global__ __attribute__((global))
 
+__attribute__((reqd_work_group_size(0, 0, 0)))
+__global__ void reqd_work_group_size_0_0_0() {}
+
 __attribute__((reqd_work_group_size(128, 1, 1)))
 __global__ void reqd_work_group_size_128_1_1() {}
 
@@ -15,6 +18,8 @@ __global__ void vec_type_hint_int() {}
 __attribute__((intel_reqd_sub_group_size(64)))
 __global__ void intel_reqd_sub_group_size_64() {}
 
+
+// CHECK: define spir_kernel void @_Z26reqd_work_group_size_0_0_0v() 
#[[ATTR:[0-9]+]] !reqd_work_group_size ![[WG_SIZE_ZEROS:[0-9]+]]
 // CHECK: define spir_kernel void @_Z28reqd_work_group_size_128_1_1v() 
#[[ATTR:[0-9]+]] !reqd_work_group_size ![[WG_SIZE:[0-9]+]]
 // CHECK: define spir_kernel void @_Z26work_group_size_hint_2_2_2v() #[[ATTR]] 
!work_group_size_hint ![[WG_HINT:[0-9]+]]
 // CHECK: define spir_kernel void @_Z17vec_type_hint_intv() #[[ATTR]] 
!vec_type_hint ![[VEC_HINT:[0-9]+]]
@@ -22,6 +27,7 @@ __global__ void intel_reqd_sub_group_size_64() {}
 
 // CHECK: attributes #[[ATTR]] = { {{.*}} }
 
+// CHECK: ![[WG_SIZE_ZEROS]] = !{i32 0, i32 0, i32 0}
 // CHECK: ![[WG_SIZE]] = !{i32 128, i32 1, i32 1}
 // CHECK: ![[WG_HINT]] = !{i32 2, i32 2, i32 2}
 // CHECK: ![[VEC_HINT]] = !{i32 undef, i32 1}

diff  --git a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl 
b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
index 0883379601ef2..e913e363ef4a1 100644
--- a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
+++ b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
@@ -44,3 +44,5 @@ __kernel __attribute__((reqd_work_group_size(8,16,-32))) void 
neg2(){} // expect
 // 4294967294 is a negative integer if treated as signed.
 // Should compile successfully, since we expect an unsigned.
 __kernel __attribute__((reqd_work_group_size(8,16,4294967294))) void ok1(){}
+
+__kernel __attribute__((reqd_work_group_size(0,0,0))) void ok_zeros(){}



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


[clang] [clang][opencl] Allow passing all zeros to reqd_work_group_size (PR #131543)

2025-03-16 Thread Alexander Shaposhnikov via cfe-commits

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


[clang] 4b86a7f - [clang-format] Update the minimum python version requirement

2025-03-16 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2025-03-16T16:42:19-07:00
New Revision: 4b86a7f3860a3cb0368e308494f65c103c02fa18

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

LOG: [clang-format] Update the minimum python version requirement

See https://llvm.org/docs/GettingStarted.html#software

Fix #131456

Added: 


Modified: 
clang/tools/clang-format/git-clang-format

Removed: 




diff  --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index da271bbe6e3a0..85eff4761e289 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -19,7 +19,7 @@ clang-format on the changes in current files or a specific 
commit.
 For further details, run:
 git clang-format -h
 
-Requires Python 2.7 or Python 3
+Requires Python version >=3.8
 """
 
 from __future__ import absolute_import, division, print_function



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


[clang] Implement Wpointer-bool-conversion-strict (PR #131523)

2025-03-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Yutong Zhu (YutongZhuu)


Changes

This PR implements the feature request from issue #9500. From the 
original issue:

```c
_Bool foo(void) {
  _Bool x = (void *)0; // warn on this
  return (void *)0; // warn on this
}
```

However, I believe that using null checks like if ``(!p) return;`` is a common 
practice in C/C++ code. Because of this, I made the option ignored by default.

Additionally, the issue creator appears to be requesting more than just 
pointer-to-bool conversion checks. Please let me know your thoughts on this.

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


6 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/include/clang/Basic/DiagnosticGroups.td (+1) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+4) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+3) 
- (added) clang/test/Sema/warn-pointer-bool-conversion-strict.c (+13) 
- (added) clang/test/Sema/warn-pointer-bool-conversion-strict.cpp (+12) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7859871b0493a..5c9783d051de5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -136,6 +136,8 @@ New Compiler Flags
   The feature has `existed 
`_)
   for a while and this is just a user facing option.
 
+- New Option ``-Wpointer-bool-conversion-strict`` has been added to warn about 
all implicit pointer-to-bool conversions (#GH9500). This option is ignored by 
default.
+
 Deprecated Compiler Flags
 -
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index fac80fb4009aa..4b2baa898a918 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -74,6 +74,7 @@ def LiteralConversion : DiagGroup<"literal-conversion">;
 def StringConversion : DiagGroup<"string-conversion">;
 def SignConversion : DiagGroup<"sign-conversion">;
 def PointerBoolConversion : DiagGroup<"pointer-bool-conversion">;
+def PointerBoolConversionStrict : DiagGroup<"pointer-bool-conversion-strict">;
 def UndefinedBoolConversion : DiagGroup<"undefined-bool-conversion">;
 def BitwiseInsteadOfLogical : DiagGroup<"bitwise-instead-of-logical">;
 def BoolOperation : DiagGroup<"bool-operation", [BitwiseInsteadOfLogical]>;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 14b0051709625..7f81b8ece55b5 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4337,6 +4337,10 @@ def warn_impcast_pointer_to_bool : Warning<
 "address of %select{'%1'|function '%1'|array '%1'|lambda function pointer "
 "conversion operator}0 will always evaluate to 'true'">,
 InGroup;
+def warn_impcast_pointer_to_bool_strict: Warning<
+"implicit conversion of pointer to bool">,
+InGroup,
+DefaultIgnore;
 def warn_cast_nonnull_to_bool : Warning<
 "nonnull %select{function call|parameter}0 '%1' will evaluate to "
 "'true' on first encounter">,
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 9cac9cf5c4df7..fee5611873232 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -11699,6 +11699,9 @@ void Sema::CheckImplicitConversion(Expr *E, QualType T, 
SourceLocation CC,
   DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
SourceRange(CC));
 }
+if (Source->isPointerType()) {
+  Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool_strict);
+}
   }
 
   // If the we're converting a constant to an ObjC BOOL on a platform where 
BOOL
diff --git a/clang/test/Sema/warn-pointer-bool-conversion-strict.c 
b/clang/test/Sema/warn-pointer-bool-conversion-strict.c
new file mode 100644
index 0..5620f054d4354
--- /dev/null
+++ b/clang/test/Sema/warn-pointer-bool-conversion-strict.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fsyntax-only -Wpointer-bool-conversion %s
+#include 
+_Bool f() {
+  int *p;
+  if (p) {} // expected-warning {{implicit conversion of pointer to bool}}
+  return (void *)0; // expected-warning {{implicit conversion of pointer to 
bool}}
+}
+
+_Bool g() {
+  int *p = (void *)0;
+  if (p == NULL) {} // no-warning
+  return (void *)0 == NULL; // no-warning
+}
diff --git a/clang/test/Sema/warn-pointer-bool-conversion-strict.cpp 
b/clang/test/Sema/warn-pointer-bool-conversion-strict.cpp
new file mode 100644
index 0..8e612d2459705
--- /dev/null
+++ b/clang/test/Sema/warn-pointer-bool-conversion-strict.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -fsyntax-only -Wpointer-bool-conversion %s
+bool f() {
+int *p;
+if (p) {} // expected-warning {{implicit conversion of poin

[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread via cfe-commits


@@ -5389,6 +5389,15 @@ void CXXNameMangler::mangleExpression(const Expr *E, 
unsigned Arity,
   Diags.Report(DiagID);
   return;
 }
+case UETT_StructuredBindingSize:
+  Out << "u11__builtin_structured_binding_size";

halbi2 wrote:

```suggestion
  Out << "u33__builtin_structured_binding_size";
```

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


[clang] [Clang][RFC] Intrododuce a builtin to determine the structure binding size (PR #131515)

2025-03-16 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/131515

>From ae66e1cc48c721badc234ff5bc5a89aeb6cd2ea3 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Sun, 16 Mar 2025 14:04:15 +0100
Subject: [PATCH 1/2] [Clang][RFC] Intrododuce a builtin to determine the
 number of bindings that would be produced by

```cpp

   auto [...p] = expr;

```

This is necessary to implement P2300 
(https://eel.is/c++draft/exec#snd.concepts-5),
but can also be used to implement a general get
function that supports aggregates

__builtin_structured_binding_size works like sizeof in that it supports both
type and expression arguments.

If the argument cannot be destructured, a sfinae-friendly error is produced.

A type is considered a valid tuple if `std::tuple_size_v`
is a valid expression, even if there is no valid `std::tuple_element`
specialization or suitable `get` function for that type.

This is modeled as a UnaryExprOrTypeTraitExpr, but it is wrapped
in a ConstantExpr because the structured binding size can only be
established during sema.
---
 clang/docs/LanguageExtensions.rst |  30 
 clang/docs/ReleaseNotes.rst   |   3 +
 .../clang/Basic/DiagnosticSemaKinds.td|   2 +
 clang/include/clang/Basic/TokenKinds.def  |   2 +-
 clang/include/clang/Sema/Sema.h   |   3 +-
 clang/lib/AST/ByteCode/Compiler.cpp   |   2 +
 clang/lib/AST/ExprConstant.cpp|   5 +
 clang/lib/AST/ItaniumMangle.cpp   |   9 +
 clang/lib/Parse/ParseExpr.cpp |  13 +-
 clang/lib/Sema/SemaDeclCXX.cpp| 123 +
 clang/lib/Sema/SemaExpr.cpp   |  69 ++-
 clang/test/CodeGenCXX/builtins.cpp|   6 +
 .../mangle-structured-binding-size.cpp|  12 ++
 .../builtin-structured-binding-size.cpp   | 168 ++
 14 files changed, 405 insertions(+), 42 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/mangle-structured-binding-size.cpp
 create mode 100644 clang/test/SemaCXX/builtin-structured-binding-size.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index cc12ff5bad353..9a5cd8f1e5f5d 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -434,6 +434,36 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+.. _builtin_structured_binding_size-doc:
+
+__builtin_structured_binding_size (C++)
+---
+``__builtin_structured_binding_size`` returns the *structured binding size*
+([dcl.struct.bind]) of the type ``T`` (or unevaluate expression ``arg``)
+passed as argument.
+
+This is equivalent to the size of the pack ``p`` in ``auto&& [...p] = arg;``.
+If the argument is not destructurable (ie not an array, vector, complex,
+*tuple-like* type or destructurable class type), 
``__builtin_structured_binding_size(T)``
+is not a valid expression (``__builtin_structured_binding_size`` is 
SFINEA-friendly).
+
+A type is considered a valid tuple if ``std::tuple_size_v`` is a valid 
expression,
+even if there is no valid ``std::tuple_element`` specialization or suitable
+``get`` function for that type.
+
+.. code-block:: c++
+
+  template
+  requires (Idx < __builtin_structured_binding_size(T))
+  decltype(auto) constexpr get_binding(T&& obj) {
+  auto && [...p] = std::forward(obj);
+  return p...[Idx];
+  }
+  struct S { int a = 0, b = 42; };
+  static_assert(__builtin_structured_binding_size(S) == 2);
+  static_assert(get_binding<1>(S{}) == 42);
+
+
 _BitInt, _ExtInt
 
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a1c5ee2d788e..f49e389773e4e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -74,6 +74,9 @@ What's New in Clang |release|?
 C++ Language Changes
 
 
+- Added a :ref:`__builtin_structured_binding_size 
` (T)
+  builtin that returns the number of structured bindings that would be 
produced by destructuring ``T``.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 86c9c955c1c78..fad826c1c6336 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -591,6 +591,8 @@ def err_decomp_decl_std_tuple_size_not_constant : Error<
   "is not a valid integral constant expression">;
 def note_in_binding_decl_init : Note<
   "in implicit initialization of binding declaration %0">;
+def err_arg_is_not_destructurable : Error<
+  "type %0 is not destructurable">;
 
 def err_std_type_trait_not_class_template : Error<
   "unsupported standard library implementation: "
diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 397a5d95709fb..bad9387673ef9 100644
--- a/c

[clang] [NFC][analyzer] Framework for multipart checkers (PR #130985)

2025-03-16 Thread Donát Nagy via cfe-commits

NagyDonat wrote:

> I'm somewhat unsatisfied, but it's not because of this PR. This is an 
> excellent way forward, I just wish we had a better abstraction.

I agree that the architecture that's being formalized by this commit is not 
perfect.

If I would be reimplementing a static analyzer from zero, I would probably 
separate:
- small "Reporter" classes which
  - have a user-facing name,
  - can be enabled/disabled by the user,
  - have `reportBug(...)` methods that produce a bug report if the Reporter is 
enabled;
  - implement unique logic (e.g. message formatting) that is only relevant for 
one sub-checker;
- big "Modeler" classes which
  - own one or several (or perhaps zero) Reporters,
  - are active if any of their Reporters is enabled (or if some other Modeler 
depends on them),
  - implement various callbacks (`check::XXX`, `eval::Call` etc.) and update 
the `State` and call `MyReporter::reportBug(...)` methods from these callbacks;
  - implement the shared logic of a group of related Reporters (i.e. what is 
currently represented by a single multipart checker class).

However, given the existing codebase I don't think that it's feasible to 
suddenly switch to an architecture like this. However, we could gradually 
approach this transition, e.g. if we gradually replace `CheckerNameRef` with a 
richer and more complex class that can become our `Reporter`.

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


[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov created 
https://github.com/llvm/llvm-project/pull/131546

Allow using integral non-type template parameters as attribute arguments of 
reqd_work_group_size and work_group_size_hint.

Test plan:
ninja check-all

>From 11495fcca75e25b6b89c991fed97d7d254b080c9 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Mon, 17 Mar 2025 00:39:24 +
Subject: [PATCH] [CudaSPIRV] Allow using integral non-type template parameters
 as reqd_work_group_size arguments

---
 .../altera/SingleWorkItemBarrierCheck.cpp |  8 +-
 clang/include/clang/Basic/Attr.td |  7 +-
 clang/lib/CodeGen/CodeGenFunction.cpp | 18 +++--
 clang/lib/CodeGen/Targets/AMDGPU.cpp  | 14 +++-
 clang/lib/CodeGen/Targets/TCE.cpp | 18 ++---
 clang/lib/Sema/SemaDeclAttr.cpp   | 79 ---
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 32 
 clang/test/SemaCUDA/spirv-attrs-diag.cu   | 38 +
 clang/test/SemaCUDA/spirv-attrs.cu| 16 
 9 files changed, 196 insertions(+), 34 deletions(-)
 create mode 100644 clang/test/SemaCUDA/spirv-attrs-diag.cu

diff --git a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
index df21c425ea956..c5da66a1f28b6 100644
--- a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
@@ -54,8 +54,12 @@ void SingleWorkItemBarrierCheck::check(const 
MatchFinder::MatchResult &Result) {
 bool IsNDRange = false;
 if (MatchedDecl->hasAttr()) {
   const auto *Attribute = MatchedDecl->getAttr();
-  if (Attribute->getXDim() > 1 || Attribute->getYDim() > 1 ||
-  Attribute->getZDim() > 1)
+  auto Eval = [&](Expr *E) {
+return E->EvaluateKnownConstInt(MatchedDecl->getASTContext())
+.getExtValue();
+  };
+  if (Eval(Attribute->getXDim()) > 1 || Eval(Attribute->getYDim()) > 1 ||
+  Eval(Attribute->getZDim()) > 1)
 IsNDRange = true;
 }
 if (IsNDRange) // No warning if kernel is treated as an NDRange.
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 4d34346460561..cceb4085d523d 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3044,8 +3044,7 @@ def NoDeref : TypeAttr {
 def ReqdWorkGroupSize : InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"reqd_work_group_size">];
-  let Args = [UnsignedArgument<"XDim">, UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
@@ -3053,9 +3052,7 @@ def ReqdWorkGroupSize : InheritableAttr {
 def WorkGroupSizeHint :  InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"work_group_size_hint">];
-  let Args = [UnsignedArgument<"XDim">,
-  UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 447192bc7f60c..de1e04a7982fa 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -649,18 +649,24 @@ void CodeGenFunction::EmitKernelMetadata(const 
FunctionDecl *FD,
   }
 
   if (const WorkGroupSizeHintAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim(};
 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, 
AttrMDArgs));
   }
 
   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getI

[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alexander Shaposhnikov (alexander-shaposhnikov)


Changes

Allow using integral non-type template parameters as attribute arguments of 
reqd_work_group_size and work_group_size_hint.

Test plan:
ninja check-all

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


9 Files Affected:

- (modified) clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
(+6-2) 
- (modified) clang/include/clang/Basic/Attr.td (+2-5) 
- (modified) clang/lib/CodeGen/CodeGenFunction.cpp (+12-6) 
- (modified) clang/lib/CodeGen/Targets/AMDGPU.cpp (+11-3) 
- (modified) clang/lib/CodeGen/Targets/TCE.cpp (+9-9) 
- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+70-9) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+32) 
- (added) clang/test/SemaCUDA/spirv-attrs-diag.cu (+38) 
- (modified) clang/test/SemaCUDA/spirv-attrs.cu (+16) 


``diff
diff --git a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
index df21c425ea956..c5da66a1f28b6 100644
--- a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
@@ -54,8 +54,12 @@ void SingleWorkItemBarrierCheck::check(const 
MatchFinder::MatchResult &Result) {
 bool IsNDRange = false;
 if (MatchedDecl->hasAttr()) {
   const auto *Attribute = MatchedDecl->getAttr();
-  if (Attribute->getXDim() > 1 || Attribute->getYDim() > 1 ||
-  Attribute->getZDim() > 1)
+  auto Eval = [&](Expr *E) {
+return E->EvaluateKnownConstInt(MatchedDecl->getASTContext())
+.getExtValue();
+  };
+  if (Eval(Attribute->getXDim()) > 1 || Eval(Attribute->getYDim()) > 1 ||
+  Eval(Attribute->getZDim()) > 1)
 IsNDRange = true;
 }
 if (IsNDRange) // No warning if kernel is treated as an NDRange.
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 4d34346460561..cceb4085d523d 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3044,8 +3044,7 @@ def NoDeref : TypeAttr {
 def ReqdWorkGroupSize : InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"reqd_work_group_size">];
-  let Args = [UnsignedArgument<"XDim">, UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
@@ -3053,9 +3052,7 @@ def ReqdWorkGroupSize : InheritableAttr {
 def WorkGroupSizeHint :  InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"work_group_size_hint">];
-  let Args = [UnsignedArgument<"XDim">,
-  UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 447192bc7f60c..de1e04a7982fa 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -649,18 +649,24 @@ void CodeGenFunction::EmitKernelMetadata(const 
FunctionDecl *FD,
   }
 
   if (const WorkGroupSizeHintAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim(};
 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, 
AttrMDArgs));
   }
 
   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim(};
 Fn->setMetadata("reqd_work_group_size", llvm::MD

[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Alexander Shaposhnikov (alexander-shaposhnikov)


Changes

Allow using integral non-type template parameters as attribute arguments of 
reqd_work_group_size and work_group_size_hint.

Test plan:
ninja check-all

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


9 Files Affected:

- (modified) clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
(+6-2) 
- (modified) clang/include/clang/Basic/Attr.td (+2-5) 
- (modified) clang/lib/CodeGen/CodeGenFunction.cpp (+12-6) 
- (modified) clang/lib/CodeGen/Targets/AMDGPU.cpp (+11-3) 
- (modified) clang/lib/CodeGen/Targets/TCE.cpp (+9-9) 
- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+70-9) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+32) 
- (added) clang/test/SemaCUDA/spirv-attrs-diag.cu (+38) 
- (modified) clang/test/SemaCUDA/spirv-attrs.cu (+16) 


``diff
diff --git a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
index df21c425ea956..c5da66a1f28b6 100644
--- a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
@@ -54,8 +54,12 @@ void SingleWorkItemBarrierCheck::check(const 
MatchFinder::MatchResult &Result) {
 bool IsNDRange = false;
 if (MatchedDecl->hasAttr()) {
   const auto *Attribute = MatchedDecl->getAttr();
-  if (Attribute->getXDim() > 1 || Attribute->getYDim() > 1 ||
-  Attribute->getZDim() > 1)
+  auto Eval = [&](Expr *E) {
+return E->EvaluateKnownConstInt(MatchedDecl->getASTContext())
+.getExtValue();
+  };
+  if (Eval(Attribute->getXDim()) > 1 || Eval(Attribute->getYDim()) > 1 ||
+  Eval(Attribute->getZDim()) > 1)
 IsNDRange = true;
 }
 if (IsNDRange) // No warning if kernel is treated as an NDRange.
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 4d34346460561..cceb4085d523d 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3044,8 +3044,7 @@ def NoDeref : TypeAttr {
 def ReqdWorkGroupSize : InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"reqd_work_group_size">];
-  let Args = [UnsignedArgument<"XDim">, UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
@@ -3053,9 +3052,7 @@ def ReqdWorkGroupSize : InheritableAttr {
 def WorkGroupSizeHint :  InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"work_group_size_hint">];
-  let Args = [UnsignedArgument<"XDim">,
-  UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 447192bc7f60c..de1e04a7982fa 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -649,18 +649,24 @@ void CodeGenFunction::EmitKernelMetadata(const 
FunctionDecl *FD,
   }
 
   if (const WorkGroupSizeHintAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim(};
 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, 
AttrMDArgs));
   }
 
   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim(};
 Fn->setMetadata("reqd_work_group_size", 

[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread via cfe-commits

llvmbot wrote:




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

Author: Alexander Shaposhnikov (alexander-shaposhnikov)


Changes

Allow using integral non-type template parameters as attribute arguments of 
reqd_work_group_size and work_group_size_hint.

Test plan:
ninja check-all

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


9 Files Affected:

- (modified) clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
(+6-2) 
- (modified) clang/include/clang/Basic/Attr.td (+2-5) 
- (modified) clang/lib/CodeGen/CodeGenFunction.cpp (+12-6) 
- (modified) clang/lib/CodeGen/Targets/AMDGPU.cpp (+11-3) 
- (modified) clang/lib/CodeGen/Targets/TCE.cpp (+9-9) 
- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+70-9) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+32) 
- (added) clang/test/SemaCUDA/spirv-attrs-diag.cu (+38) 
- (modified) clang/test/SemaCUDA/spirv-attrs.cu (+16) 


``diff
diff --git a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
index df21c425ea956..c5da66a1f28b6 100644
--- a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
@@ -54,8 +54,12 @@ void SingleWorkItemBarrierCheck::check(const 
MatchFinder::MatchResult &Result) {
 bool IsNDRange = false;
 if (MatchedDecl->hasAttr()) {
   const auto *Attribute = MatchedDecl->getAttr();
-  if (Attribute->getXDim() > 1 || Attribute->getYDim() > 1 ||
-  Attribute->getZDim() > 1)
+  auto Eval = [&](Expr *E) {
+return E->EvaluateKnownConstInt(MatchedDecl->getASTContext())
+.getExtValue();
+  };
+  if (Eval(Attribute->getXDim()) > 1 || Eval(Attribute->getYDim()) > 1 ||
+  Eval(Attribute->getZDim()) > 1)
 IsNDRange = true;
 }
 if (IsNDRange) // No warning if kernel is treated as an NDRange.
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 4d34346460561..cceb4085d523d 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3044,8 +3044,7 @@ def NoDeref : TypeAttr {
 def ReqdWorkGroupSize : InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"reqd_work_group_size">];
-  let Args = [UnsignedArgument<"XDim">, UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
@@ -3053,9 +3052,7 @@ def ReqdWorkGroupSize : InheritableAttr {
 def WorkGroupSizeHint :  InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"work_group_size_hint">];
-  let Args = [UnsignedArgument<"XDim">,
-  UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 447192bc7f60c..de1e04a7982fa 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -649,18 +649,24 @@ void CodeGenFunction::EmitKernelMetadata(const 
FunctionDecl *FD,
   }
 
   if (const WorkGroupSizeHintAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim(};
 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, 
AttrMDArgs));
   }
 
   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim(};
 Fn->setMetadata("reqd_work_group_siz

[clang] [clang] Change placeholder from `undef` to `poison` (PR #131533)

2025-03-16 Thread Pedro Lobo via cfe-commits

https://github.com/pedroclobo created 
https://github.com/llvm/llvm-project/pull/131533

Return a `poison` value, instead of `undef`, if there is no available SEH info.

>From 6c231b0dba091d6f7c5b79a92dedeeb56166fd8f Mon Sep 17 00:00:00 2001
From: Pedro Lobo 
Date: Wed, 15 Jan 2025 20:14:30 +
Subject: [PATCH] [clang] Change placeholder from `undef` to `poison`

Return a `poison` value, instead of `undef`, if there is no available
SEH info.
---
 clang/lib/CodeGen/CGException.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 5a395c924333e..b4b8c2952b02b 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -2145,7 +2145,7 @@ llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
   // Sema should diagnose calling this builtin outside of a filter context, but
   // don't crash if we screw up.
   if (!SEHInfo)
-return llvm::UndefValue::get(Int8PtrTy);
+return llvm::PoisonValue::get(Int8PtrTy);
   assert(SEHInfo->getType() == Int8PtrTy);
   return SEHInfo;
 }

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


[clang] [clang] Change placeholder from `undef` to `poison` (PR #131533)

2025-03-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Pedro Lobo (pedroclobo)


Changes

Return a `poison` value, instead of `undef`, if there is no available SEH info.

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGException.cpp (+1-1) 


``diff
diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 5a395c924333e..b4b8c2952b02b 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -2145,7 +2145,7 @@ llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
   // Sema should diagnose calling this builtin outside of a filter context, but
   // don't crash if we screw up.
   if (!SEHInfo)
-return llvm::UndefValue::get(Int8PtrTy);
+return llvm::PoisonValue::get(Int8PtrTy);
   assert(SEHInfo->getType() == Int8PtrTy);
   return SEHInfo;
 }

``




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


[clang] [clang] Change placeholder from `undef` to `poison` (PR #131533)

2025-03-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Pedro Lobo (pedroclobo)


Changes

Return a `poison` value, instead of `undef`, if there is no available SEH info.

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGException.cpp (+1-1) 


``diff
diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 5a395c924333e..b4b8c2952b02b 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -2145,7 +2145,7 @@ llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
   // Sema should diagnose calling this builtin outside of a filter context, but
   // don't crash if we screw up.
   if (!SEHInfo)
-return llvm::UndefValue::get(Int8PtrTy);
+return llvm::PoisonValue::get(Int8PtrTy);
   assert(SEHInfo->getType() == Int8PtrTy);
   return SEHInfo;
 }

``




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


[clang] [Clang]Implement Wpointer-bool-conversion-strict (PR #131523)

2025-03-16 Thread Yutong Zhu via cfe-commits

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


[clang] [clang][opencl] Allow passing all zeros to reqd_work_group_size (PR #131543)

2025-03-16 Thread Shangwu Yao via cfe-commits

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

Cool!

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


[clang] [clang] Fix UEFI Target info (PR #127290)

2025-03-16 Thread Petr Hosek via cfe-commits


@@ -835,19 +835,39 @@ class LLVM_LIBRARY_VISIBILITY UEFIX86_64TargetInfo
 public:
   UEFIX86_64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
   : UEFITargetInfo(Triple, Opts) {
+LongWidth = LongAlign = 32;
+DoubleAlign = LongLongAlign = 64;
+IntMaxType = SignedLongLong;
+Int64Type = SignedLongLong;
+SizeType = UnsignedLongLong;
+PtrDiffType = SignedLongLong;
+IntPtrType = SignedLongLong;
+LongDoubleWidth = LongDoubleAlign = 64;
+LongDoubleFormat = &llvm::APFloat::IEEEdouble();
+WCharType = UnsignedShort;
+WIntType = UnsignedShort;
 this->TheCXXABI.set(TargetCXXABI::Microsoft);
-this->MaxTLSAlign = 8192u * this->getCharWidth();
 this->resetDataLayout("e-m:w-p270:32:32-p271:32:32-p272:64:64-"
   "i64:64-i128:128-f80:128-n8:16:32:64-S128");
   }
 
-  BuiltinVaListKind getBuiltinVaListKind() const override {
-return TargetInfo::CharPtrBuiltinVaList;
-  }
-
   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override 
{
 switch (CC) {
+case CC_X86StdCall:
+case CC_X86ThisCall:
+case CC_X86FastCall:
+  return CCCR_Ignore;
 case CC_C:
+case CC_X86VectorCall:
+case CC_IntelOclBicc:
+case CC_PreserveMost:
+case CC_PreserveAll:
+case CC_PreserveNone:
+case CC_X86_64SysV:
+case CC_Swift:
+case CC_SwiftAsync:
+case CC_X86RegCall:
+case CC_OpenCLKernel:

petrhosek wrote:

What's the reason for including all of these? I doubt we're ever going to want 
to use e.g. an OpenCL kernel calling convention with UEFI.

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


[clang] [clang-format] Correctly annotate user-defined conversion functions (PR #131434)

2025-03-16 Thread Owen Pan via cfe-commits

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

>From 46cde1b7667f36115d746326b78d011511cac738 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sat, 15 Mar 2025 00:37:53 -0700
Subject: [PATCH 1/3] [clang-format] Correctly annotate user-defined conversion
 functions

Also fix/delete existing invalid/redundant test cases.

Fix #130894
---
 clang/lib/Format/TokenAnnotator.cpp   | 27 --
 clang/unittests/Format/FormatTest.cpp | 28 +-
 clang/unittests/Format/TokenAnnotatorTest.cpp | 53 +++
 3 files changed, 89 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 08539de405c67..d618eab1692b3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1639,6 +1639,25 @@ class AnnotatingParser {
 case tok::kw_operator:
   if (Style.isProto())
 break;
+  // C++ user-defined conversion function.
+  if (IsCpp && CurrentToken &&
+  (CurrentToken->is(tok::kw_auto) ||
+   CurrentToken->isTypeName(LangOpts))) {
+FormatToken *LParen;
+if (CurrentToken->startsSequence(tok::kw_decltype, tok::l_paren,
+ tok::kw_auto, tok::r_paren)) {
+  LParen = CurrentToken->Next->Next->Next->Next;
+} else {
+  for (LParen = CurrentToken->Next;
+   LParen && LParen->isNot(tok::l_paren); LParen = LParen->Next) {
+  }
+}
+if (LParen && LParen->startsSequence(tok::l_paren, tok::r_paren)) {
+  Tok->setFinalizedType(TT_FunctionDeclarationName);
+  LParen->setFinalizedType(TT_FunctionDeclarationLParen);
+  break;
+}
+  }
   while (CurrentToken &&
  !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
 if (CurrentToken->isOneOf(tok::star, tok::amp))
@@ -3071,12 +3090,10 @@ class AnnotatingParser {
 if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
   return TT_BinaryOperator;
 
-// "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
-// unary "&".
-if (Tok.is(tok::ampamp) &&
-NextToken->isOneOf(tok::l_paren, tok::star, tok::amp)) {
+// "&&" followed by "*" or "&" is quite unlikely to be two successive unary
+// "&".
+if (Tok.is(tok::ampamp) && NextToken->isOneOf(tok::star, tok::amp))
   return TT_BinaryOperator;
-}
 
 // This catches some cases where evaluation order is used as control flow:
 //   aaa && aaa->f();
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 9864e7ec1b2ec..5df7865f5a629 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10443,27 +10443,17 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
"void\n"
"A::operator->() {}\n"
"void\n"
-   "A::operator void *() {}\n"
+   "A::operator&() {}\n"
"void\n"
-   "A::operator void &() {}\n"
-   "void\n"
-   "A::operator void &&() {}\n"
-   "void\n"
-   "A::operator char *() {}\n"
+   "A::operator&&() {}\n"
"void\n"
"A::operator[]() {}\n"
"void\n"
"A::operator!() {}\n"
"void\n"
-   "A::operator**() {}\n"
-   "void\n"
"A::operator *() {}\n"
"void\n"
-   "A::operator **() {}\n"
-   "void\n"
-   "A::operator &() {}\n"
-   "void\n"
-   "A::operator void **() {}",
+   "A::operator &() {}\n",
Style);
   verifyFormat("constexpr auto\n"
"operator()() const -> reference {}\n"
@@ -10486,7 +10476,7 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
"constexpr auto\n"
"operator void &() const -> reference {}\n"
"constexpr auto\n"
-   "operator void &&() const -> reference {}\n"
+   "operator&&() const -> reference {}\n"
"constexpr auto\n"
"operator char *() const -> reference {}\n"
"constexpr auto\n"
@@ -28032,6 +28022,16 @@ TEST_F(FormatTest, BreakAfterAttributes) {
"  --d;",
CtrlStmtCode, Style);
 
+  verifyFormat("[[nodiscard]]\n"
+   "operator bool();\n"
+   "[[nodiscard]]\n"
+   "operator bool() {\n"
+   "  return true;\n"
+   "}",
+   "[[nodiscard]] operator bool();\n"
+   "[[nodiscard]] operator bool() { return true; }",
+   Style);
+
   constexpr StringRef CtorDtorCode("struct Foo {\n"
"  [[deprecated]] Foo();\n"
 

[clang] [Clang]Implement Wpointer-bool-conversion-strict (PR #131523)

2025-03-16 Thread Yutong Zhu via cfe-commits

https://github.com/YutongZhuu updated 
https://github.com/llvm/llvm-project/pull/131523

>From f99d61ef3353e8559450e91ad8201f8fe7592a86 Mon Sep 17 00:00:00 2001
From: Yutong Zhu 
Date: Sun, 16 Mar 2025 11:15:31 -0400
Subject: [PATCH 1/2] Implement Wpointer-bool-conversion-strict

---
 clang/docs/ReleaseNotes.rst |  2 ++
 clang/include/clang/Basic/DiagnosticGroups.td   |  1 +
 clang/include/clang/Basic/DiagnosticSemaKinds.td|  4 
 clang/lib/Sema/SemaChecking.cpp |  3 +++
 .../test/Sema/warn-pointer-bool-conversion-strict.c | 13 +
 .../Sema/warn-pointer-bool-conversion-strict.cpp| 12 
 6 files changed, 35 insertions(+)
 create mode 100644 clang/test/Sema/warn-pointer-bool-conversion-strict.c
 create mode 100644 clang/test/Sema/warn-pointer-bool-conversion-strict.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7859871b0493a..5c9783d051de5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -136,6 +136,8 @@ New Compiler Flags
   The feature has `existed 
`_)
   for a while and this is just a user facing option.
 
+- New Option ``-Wpointer-bool-conversion-strict`` has been added to warn about 
all implicit pointer-to-bool conversions (#GH9500). This option is ignored by 
default.
+
 Deprecated Compiler Flags
 -
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index fac80fb4009aa..4b2baa898a918 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -74,6 +74,7 @@ def LiteralConversion : DiagGroup<"literal-conversion">;
 def StringConversion : DiagGroup<"string-conversion">;
 def SignConversion : DiagGroup<"sign-conversion">;
 def PointerBoolConversion : DiagGroup<"pointer-bool-conversion">;
+def PointerBoolConversionStrict : DiagGroup<"pointer-bool-conversion-strict">;
 def UndefinedBoolConversion : DiagGroup<"undefined-bool-conversion">;
 def BitwiseInsteadOfLogical : DiagGroup<"bitwise-instead-of-logical">;
 def BoolOperation : DiagGroup<"bool-operation", [BitwiseInsteadOfLogical]>;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 14b0051709625..7f81b8ece55b5 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4337,6 +4337,10 @@ def warn_impcast_pointer_to_bool : Warning<
 "address of %select{'%1'|function '%1'|array '%1'|lambda function pointer "
 "conversion operator}0 will always evaluate to 'true'">,
 InGroup;
+def warn_impcast_pointer_to_bool_strict: Warning<
+"implicit conversion of pointer to bool">,
+InGroup,
+DefaultIgnore;
 def warn_cast_nonnull_to_bool : Warning<
 "nonnull %select{function call|parameter}0 '%1' will evaluate to "
 "'true' on first encounter">,
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 9cac9cf5c4df7..fee5611873232 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -11699,6 +11699,9 @@ void Sema::CheckImplicitConversion(Expr *E, QualType T, 
SourceLocation CC,
   DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
SourceRange(CC));
 }
+if (Source->isPointerType()) {
+  Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool_strict);
+}
   }
 
   // If the we're converting a constant to an ObjC BOOL on a platform where 
BOOL
diff --git a/clang/test/Sema/warn-pointer-bool-conversion-strict.c 
b/clang/test/Sema/warn-pointer-bool-conversion-strict.c
new file mode 100644
index 0..5620f054d4354
--- /dev/null
+++ b/clang/test/Sema/warn-pointer-bool-conversion-strict.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fsyntax-only -Wpointer-bool-conversion %s
+#include 
+_Bool f() {
+  int *p;
+  if (p) {} // expected-warning {{implicit conversion of pointer to bool}}
+  return (void *)0; // expected-warning {{implicit conversion of pointer to 
bool}}
+}
+
+_Bool g() {
+  int *p = (void *)0;
+  if (p == NULL) {} // no-warning
+  return (void *)0 == NULL; // no-warning
+}
diff --git a/clang/test/Sema/warn-pointer-bool-conversion-strict.cpp 
b/clang/test/Sema/warn-pointer-bool-conversion-strict.cpp
new file mode 100644
index 0..8e612d2459705
--- /dev/null
+++ b/clang/test/Sema/warn-pointer-bool-conversion-strict.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -fsyntax-only -Wpointer-bool-conversion %s
+bool f() {
+int *p;
+if (p) {} // expected-warning {{implicit conversion of pointer to bool}}
+return (void *)0; // expected-warning {{implicit conversion of pointer to 
bool}}
+}
+
+bool g() {
+int *p = nullptr;
+if (p == nullptr) {} // no-warning
+return (void *)0 == nullpt

[clang] [Clang][RFC] Intrododuce a builtin to determine the number of (PR #131515)

2025-03-16 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/131515

bindings that would be produced by

```cpp

   auto [...p] = expr;

```

This is necessary to implement P2300 
(https://eel.is/c++draft/exec#snd.concepts-5), but can also be used to 
implement a general get function that supports aggregates

__builtin_structured_binding_size works like sizeof in that it supports both 
type and expression arguments.

If the argument cannot be destructured, a sfinae-friendly error is produced.

A type is considered a valid tuple if `std::tuple_size_v` is a valid 
expression, even if there is no valid `std::tuple_element` specialization or 
suitable `get` function for that type.

This is modeled as a UnaryExprOrTypeTraitExpr, but it is wrapped in a 
ConstantExpr because the structured binding size can only be established during 
sema.

>From ae66e1cc48c721badc234ff5bc5a89aeb6cd2ea3 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Sun, 16 Mar 2025 14:04:15 +0100
Subject: [PATCH] [Clang][RFC] Intrododuce a builtin to determine the number of
 bindings that would be produced by

```cpp

   auto [...p] = expr;

```

This is necessary to implement P2300 
(https://eel.is/c++draft/exec#snd.concepts-5),
but can also be used to implement a general get
function that supports aggregates

__builtin_structured_binding_size works like sizeof in that it supports both
type and expression arguments.

If the argument cannot be destructured, a sfinae-friendly error is produced.

A type is considered a valid tuple if `std::tuple_size_v`
is a valid expression, even if there is no valid `std::tuple_element`
specialization or suitable `get` function for that type.

This is modeled as a UnaryExprOrTypeTraitExpr, but it is wrapped
in a ConstantExpr because the structured binding size can only be
established during sema.
---
 clang/docs/LanguageExtensions.rst |  30 
 clang/docs/ReleaseNotes.rst   |   3 +
 .../clang/Basic/DiagnosticSemaKinds.td|   2 +
 clang/include/clang/Basic/TokenKinds.def  |   2 +-
 clang/include/clang/Sema/Sema.h   |   3 +-
 clang/lib/AST/ByteCode/Compiler.cpp   |   2 +
 clang/lib/AST/ExprConstant.cpp|   5 +
 clang/lib/AST/ItaniumMangle.cpp   |   9 +
 clang/lib/Parse/ParseExpr.cpp |  13 +-
 clang/lib/Sema/SemaDeclCXX.cpp| 123 +
 clang/lib/Sema/SemaExpr.cpp   |  69 ++-
 clang/test/CodeGenCXX/builtins.cpp|   6 +
 .../mangle-structured-binding-size.cpp|  12 ++
 .../builtin-structured-binding-size.cpp   | 168 ++
 14 files changed, 405 insertions(+), 42 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/mangle-structured-binding-size.cpp
 create mode 100644 clang/test/SemaCXX/builtin-structured-binding-size.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index cc12ff5bad353..9a5cd8f1e5f5d 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -434,6 +434,36 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+.. _builtin_structured_binding_size-doc:
+
+__builtin_structured_binding_size (C++)
+---
+``__builtin_structured_binding_size`` returns the *structured binding size*
+([dcl.struct.bind]) of the type ``T`` (or unevaluate expression ``arg``)
+passed as argument.
+
+This is equivalent to the size of the pack ``p`` in ``auto&& [...p] = arg;``.
+If the argument is not destructurable (ie not an array, vector, complex,
+*tuple-like* type or destructurable class type), 
``__builtin_structured_binding_size(T)``
+is not a valid expression (``__builtin_structured_binding_size`` is 
SFINEA-friendly).
+
+A type is considered a valid tuple if ``std::tuple_size_v`` is a valid 
expression,
+even if there is no valid ``std::tuple_element`` specialization or suitable
+``get`` function for that type.
+
+.. code-block:: c++
+
+  template
+  requires (Idx < __builtin_structured_binding_size(T))
+  decltype(auto) constexpr get_binding(T&& obj) {
+  auto && [...p] = std::forward(obj);
+  return p...[Idx];
+  }
+  struct S { int a = 0, b = 42; };
+  static_assert(__builtin_structured_binding_size(S) == 2);
+  static_assert(get_binding<1>(S{}) == 42);
+
+
 _BitInt, _ExtInt
 
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a1c5ee2d788e..f49e389773e4e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -74,6 +74,9 @@ What's New in Clang |release|?
 C++ Language Changes
 
 
+- Added a :ref:`__builtin_structured_binding_size 
` (T)
+  builtin that returns the number of structured bindings that would be 
produced by destructuring ``T``.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Basic/DiagnosticSema

[clang] [Clang][RFC] Intrododuce a builtin to determine the number of (PR #131515)

2025-03-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes

bindings that would be produced by

```cpp

   auto [...p] = expr;

```

This is necessary to implement P2300 
(https://eel.is/c++draft/exec#snd.concepts-5), but can also be used to 
implement a general get function that supports aggregates

__builtin_structured_binding_size works like sizeof in that it supports both 
type and expression arguments.

If the argument cannot be destructured, a sfinae-friendly error is produced.

A type is considered a valid tuple if `std::tuple_size_v` is a valid 
expression, even if there is no valid `std::tuple_element` specialization or 
suitable `get` function for that type.

This is modeled as a UnaryExprOrTypeTraitExpr, but it is wrapped in a 
ConstantExpr because the structured binding size can only be established during 
sema.

---

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


14 Files Affected:

- (modified) clang/docs/LanguageExtensions.rst (+30) 
- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2) 
- (modified) clang/include/clang/Basic/TokenKinds.def (+1-1) 
- (modified) clang/include/clang/Sema/Sema.h (+2-1) 
- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+2) 
- (modified) clang/lib/AST/ExprConstant.cpp (+5) 
- (modified) clang/lib/AST/ItaniumMangle.cpp (+9) 
- (modified) clang/lib/Parse/ParseExpr.cpp (+10-3) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+93-30) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+62-7) 
- (modified) clang/test/CodeGenCXX/builtins.cpp (+6) 
- (added) clang/test/CodeGenCXX/mangle-structured-binding-size.cpp (+12) 
- (added) clang/test/SemaCXX/builtin-structured-binding-size.cpp (+168) 


``diff
diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index cc12ff5bad353..9a5cd8f1e5f5d 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -434,6 +434,36 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+.. _builtin_structured_binding_size-doc:
+
+__builtin_structured_binding_size (C++)
+---
+``__builtin_structured_binding_size`` returns the *structured binding size*
+([dcl.struct.bind]) of the type ``T`` (or unevaluate expression ``arg``)
+passed as argument.
+
+This is equivalent to the size of the pack ``p`` in ``auto&& [...p] = arg;``.
+If the argument is not destructurable (ie not an array, vector, complex,
+*tuple-like* type or destructurable class type), 
``__builtin_structured_binding_size(T)``
+is not a valid expression (``__builtin_structured_binding_size`` is 
SFINEA-friendly).
+
+A type is considered a valid tuple if ``std::tuple_size_v`` is a valid 
expression,
+even if there is no valid ``std::tuple_element`` specialization or suitable
+``get`` function for that type.
+
+.. code-block:: c++
+
+  template
+  requires (Idx < __builtin_structured_binding_size(T))
+  decltype(auto) constexpr get_binding(T&& obj) {
+  auto && [...p] = std::forward(obj);
+  return p...[Idx];
+  }
+  struct S { int a = 0, b = 42; };
+  static_assert(__builtin_structured_binding_size(S) == 2);
+  static_assert(get_binding<1>(S{}) == 42);
+
+
 _BitInt, _ExtInt
 
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a1c5ee2d788e..f49e389773e4e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -74,6 +74,9 @@ What's New in Clang |release|?
 C++ Language Changes
 
 
+- Added a :ref:`__builtin_structured_binding_size 
` (T)
+  builtin that returns the number of structured bindings that would be 
produced by destructuring ``T``.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 86c9c955c1c78..fad826c1c6336 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -591,6 +591,8 @@ def err_decomp_decl_std_tuple_size_not_constant : Error<
   "is not a valid integral constant expression">;
 def note_in_binding_decl_init : Note<
   "in implicit initialization of binding declaration %0">;
+def err_arg_is_not_destructurable : Error<
+  "type %0 is not destructurable">;
 
 def err_std_type_trait_not_class_template : Error<
   "unsupported standard library implementation: "
diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 397a5d95709fb..bad9387673ef9 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -553,8 +553,8 @@ TYPE_TRAIT_2(__reference_converts_from_temporary, 
ReferenceConvertsFromTemporary
 // IsDeducible is only used internally by clang for CTAD implementation and
 

[clang] Implement Wpointer-bool-conversion-strict (PR #131523)

2025-03-16 Thread Yutong Zhu via cfe-commits

https://github.com/YutongZhuu created 
https://github.com/llvm/llvm-project/pull/131523

This PR implements the feature request from issue #9500. From the original 
issue:

```c
_Bool foo(void) {
  _Bool x = (void *)0; // warn on this
  return (void *)0; // warn on this
}
```

However, I believe that using null checks like if ``(!p) return;`` is a common 
practice in C/C++ code. Because of this, I made the option ignored by default.

Additionally, the issue creator appears to be requesting more than just 
pointer-to-bool conversion checks. Please let me know your thoughts on this.

>From f99d61ef3353e8559450e91ad8201f8fe7592a86 Mon Sep 17 00:00:00 2001
From: Yutong Zhu 
Date: Sun, 16 Mar 2025 11:15:31 -0400
Subject: [PATCH] Implement Wpointer-bool-conversion-strict

---
 clang/docs/ReleaseNotes.rst |  2 ++
 clang/include/clang/Basic/DiagnosticGroups.td   |  1 +
 clang/include/clang/Basic/DiagnosticSemaKinds.td|  4 
 clang/lib/Sema/SemaChecking.cpp |  3 +++
 .../test/Sema/warn-pointer-bool-conversion-strict.c | 13 +
 .../Sema/warn-pointer-bool-conversion-strict.cpp| 12 
 6 files changed, 35 insertions(+)
 create mode 100644 clang/test/Sema/warn-pointer-bool-conversion-strict.c
 create mode 100644 clang/test/Sema/warn-pointer-bool-conversion-strict.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7859871b0493a..5c9783d051de5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -136,6 +136,8 @@ New Compiler Flags
   The feature has `existed 
`_)
   for a while and this is just a user facing option.
 
+- New Option ``-Wpointer-bool-conversion-strict`` has been added to warn about 
all implicit pointer-to-bool conversions (#GH9500). This option is ignored by 
default.
+
 Deprecated Compiler Flags
 -
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index fac80fb4009aa..4b2baa898a918 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -74,6 +74,7 @@ def LiteralConversion : DiagGroup<"literal-conversion">;
 def StringConversion : DiagGroup<"string-conversion">;
 def SignConversion : DiagGroup<"sign-conversion">;
 def PointerBoolConversion : DiagGroup<"pointer-bool-conversion">;
+def PointerBoolConversionStrict : DiagGroup<"pointer-bool-conversion-strict">;
 def UndefinedBoolConversion : DiagGroup<"undefined-bool-conversion">;
 def BitwiseInsteadOfLogical : DiagGroup<"bitwise-instead-of-logical">;
 def BoolOperation : DiagGroup<"bool-operation", [BitwiseInsteadOfLogical]>;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 14b0051709625..7f81b8ece55b5 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4337,6 +4337,10 @@ def warn_impcast_pointer_to_bool : Warning<
 "address of %select{'%1'|function '%1'|array '%1'|lambda function pointer "
 "conversion operator}0 will always evaluate to 'true'">,
 InGroup;
+def warn_impcast_pointer_to_bool_strict: Warning<
+"implicit conversion of pointer to bool">,
+InGroup,
+DefaultIgnore;
 def warn_cast_nonnull_to_bool : Warning<
 "nonnull %select{function call|parameter}0 '%1' will evaluate to "
 "'true' on first encounter">,
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 9cac9cf5c4df7..fee5611873232 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -11699,6 +11699,9 @@ void Sema::CheckImplicitConversion(Expr *E, QualType T, 
SourceLocation CC,
   DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
SourceRange(CC));
 }
+if (Source->isPointerType()) {
+  Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool_strict);
+}
   }
 
   // If the we're converting a constant to an ObjC BOOL on a platform where 
BOOL
diff --git a/clang/test/Sema/warn-pointer-bool-conversion-strict.c 
b/clang/test/Sema/warn-pointer-bool-conversion-strict.c
new file mode 100644
index 0..5620f054d4354
--- /dev/null
+++ b/clang/test/Sema/warn-pointer-bool-conversion-strict.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fsyntax-only -Wpointer-bool-conversion %s
+#include 
+_Bool f() {
+  int *p;
+  if (p) {} // expected-warning {{implicit conversion of pointer to bool}}
+  return (void *)0; // expected-warning {{implicit conversion of pointer to 
bool}}
+}
+
+_Bool g() {
+  int *p = (void *)0;
+  if (p == NULL) {} // no-warning
+  return (void *)0 == NULL; // no-warning
+}
diff --git a/clang/test/Sema/warn-pointer-bool-conversion-strict.cpp 
b/clang/test/Sema/warn-pointer-bool-conversion-strict.cpp
new file mode 100

[clang] [NFC][analyzer] Framework for multipart checkers (PR #130985)

2025-03-16 Thread Balazs Benics via cfe-commits
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy 
Message-ID:
In-Reply-To: 


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

I'm somewhat unsatisfied, but it's not because of this PR.
This is an excellent way forward, I just wish we had a better abstraction.
Thanks for cleaning this up.

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


[clang] [clang-format] Correctly annotate user-defined conversion functions (PR #131434)

2025-03-16 Thread Owen Pan via cfe-commits


@@ -1639,6 +1639,31 @@ class AnnotatingParser {
 case tok::kw_operator:
   if (Style.isProto())
 break;
+  // Handle C++ user-defined conversion function.
+  if (IsCpp && CurrentToken) {
+const auto *Info = CurrentToken->Tok.getIdentifierInfo();
+// What follows Tok is an identifier or a non-operator keyword.
+if (Info && !(Info->isCPlusPlusOperatorKeyword() ||
+  CurrentToken->isPlacementOperator() ||
+  CurrentToken->is(tok::kw_co_await))) {

owenca wrote:

```suggestion
if (Info && !(CurrentToken->isPlacementOperator() ||
  CurrentToken->is(tok::kw_co_await) ||
  Info->isCPlusPlusOperatorKeyword())) {
```

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


[clang] [Clang] Implement Wpointer-bool-conversion-strict (PR #131523)

2025-03-16 Thread via cfe-commits

MagentaTreehouse wrote:

We should not flag [contextual 
conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion#Contextual_conversions)
 to `bool`. This is supported by C++ Core Guidelines [ES.87: Don’t add 
redundant `==` or `!=` 
conditions](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es87-dont-add-redundant--or--to-conditions):

> ```c++
> // These all mean "if p is not nullptr"
> if (p) { ... }// good
> if (p != nullptr) { ... } // redundant !=nullptr, not recommended
> ```

> ```c++
> // These all mean "if p is nullptr"
> if (!p) { ... }   // good
> if (p == nullptr) { ... } // redundant == nullptr, not recommended
> ```

It looks like we can interpret the issue request to be an implemenation of a 
specific case of [ES.46: Avoid lossy (narrowing, truncating) arithmetic 
conversions](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es46-avoid-lossy-narrowing-truncating-arithmetic-conversions):

> **Note** This rule does not apply to [contextual conversions to 
> bool](https://en.cppreference.com/w/cpp/language/implicit_conversion#Contextual_conversions):
> ```c++
> if (ptr) do_something(*ptr);   // OK: ptr is used as a condition
> bool b = ptr;  // bad: narrowing
> ```

(Side note: I think it is good to be a Clang-Tidy check under the 
`cppcoreguidelines` group)


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


[clang] [Clang] Implement Wpointer-bool-conversion-strict (PR #131523)

2025-03-16 Thread via cfe-commits

hstk30-hw wrote:

We have so many conversion from ptr to bool like null check stmt `if (!p) ...` .
Open the option will get many warnings, and can't figure out the real case from 
it.



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


[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/131546

>From 86eefd7db18252d74f7b5891e7490653b6378eb0 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Mon, 17 Mar 2025 00:39:24 +
Subject: [PATCH] [CudaSPIRV] Allow using integral non-type template parameters
 as reqd_work_group_size arguments

---
 .../altera/SingleWorkItemBarrierCheck.cpp |  8 +-
 clang/include/clang/Basic/Attr.td |  7 +-
 clang/lib/CodeGen/CodeGenFunction.cpp | 18 +++--
 clang/lib/CodeGen/Targets/AMDGPU.cpp  | 14 +++-
 clang/lib/CodeGen/Targets/TCE.cpp | 18 ++---
 clang/lib/Sema/SemaDeclAttr.cpp   | 79 ---
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 32 
 clang/test/SemaCUDA/spirv-attrs-diag.cu   | 34 
 clang/test/SemaCUDA/spirv-attrs.cu| 14 
 9 files changed, 190 insertions(+), 34 deletions(-)
 create mode 100644 clang/test/SemaCUDA/spirv-attrs-diag.cu

diff --git a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
index df21c425ea956..c5da66a1f28b6 100644
--- a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
@@ -54,8 +54,12 @@ void SingleWorkItemBarrierCheck::check(const 
MatchFinder::MatchResult &Result) {
 bool IsNDRange = false;
 if (MatchedDecl->hasAttr()) {
   const auto *Attribute = MatchedDecl->getAttr();
-  if (Attribute->getXDim() > 1 || Attribute->getYDim() > 1 ||
-  Attribute->getZDim() > 1)
+  auto Eval = [&](Expr *E) {
+return E->EvaluateKnownConstInt(MatchedDecl->getASTContext())
+.getExtValue();
+  };
+  if (Eval(Attribute->getXDim()) > 1 || Eval(Attribute->getYDim()) > 1 ||
+  Eval(Attribute->getZDim()) > 1)
 IsNDRange = true;
 }
 if (IsNDRange) // No warning if kernel is treated as an NDRange.
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 4d34346460561..cceb4085d523d 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3044,8 +3044,7 @@ def NoDeref : TypeAttr {
 def ReqdWorkGroupSize : InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"reqd_work_group_size">];
-  let Args = [UnsignedArgument<"XDim">, UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
@@ -3053,9 +3052,7 @@ def ReqdWorkGroupSize : InheritableAttr {
 def WorkGroupSizeHint :  InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"work_group_size_hint">];
-  let Args = [UnsignedArgument<"XDim">,
-  UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 447192bc7f60c..de1e04a7982fa 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -649,18 +649,24 @@ void CodeGenFunction::EmitKernelMetadata(const 
FunctionDecl *FD,
   }
 
   if (const WorkGroupSizeHintAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim(};
 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, 
AttrMDArgs));
   }
 
   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.ge

[clang] [C++20][Modules] Prevent premature calls to PassInterestingDeclsToConsumer() within FinishedDeserializing(). (PR #129982)

2025-03-16 Thread Shafik Yaghmour via cfe-commits


@@ -10792,47 +10822,54 @@ void ASTReader::FinishedDeserializing() {
   --NumCurrentElementsDeserializing;
 
   if (NumCurrentElementsDeserializing == 0) {
-// Propagate exception specification and deduced type updates along
-// redeclaration chains.
-//
-// We do this now rather than in finishPendingActions because we want to
-// be able to walk the complete redeclaration chains of the updated decls.
-while (!PendingExceptionSpecUpdates.empty() ||
-   !PendingDeducedTypeUpdates.empty() ||
-   !PendingUndeducedFunctionDecls.empty()) {
-  auto ESUpdates = std::move(PendingExceptionSpecUpdates);
-  PendingExceptionSpecUpdates.clear();
-  for (auto Update : ESUpdates) {
-ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
-auto *FPT = Update.second->getType()->castAs();
-auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
-if (auto *Listener = getContext().getASTMutationListener())
-  Listener->ResolvedExceptionSpec(cast(Update.second));
-for (auto *Redecl : Update.second->redecls())
-  getContext().adjustExceptionSpec(cast(Redecl), ESI);
-  }
+{
+  // Guard variable to avoid recursively entering the process of passing
+  // decls to consumer.
+  SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer, 
false);

shafik wrote:

nitpick `false` -> `/*NewValue=*/false`

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


[clang] [C++20][Modules] Prevent premature calls to PassInterestingDeclsToConsumer() within FinishedDeserializing(). (PR #129982)

2025-03-16 Thread Shafik Yaghmour via cfe-commits


@@ -4309,12 +4309,12 @@ Decl *ASTReader::ReadDeclRecord(GlobalDeclID ID) {
 void ASTReader::PassInterestingDeclsToConsumer() {
   assert(Consumer);
 
-  if (PassingDeclsToConsumer)
+  if (!CanPassDeclsToConsumer)
 return;
 
   // Guard variable to avoid recursively redoing the process of passing
   // decls to consumer.
-  SaveAndRestore GuardPassingDeclsToConsumer(PassingDeclsToConsumer, true);
+  SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer, false);

shafik wrote:

nitpick `false` -> `/*NewValue=*/false`

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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Matt Arsenault via cfe-commits


@@ -32,9 +32,9 @@ static const char *const DataLayoutStringR600 =
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
 
 static const char *const DataLayoutStringAMDGCN =
-"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
-"-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:"
-"32-v48:64-v96:128"
+"e-p:64:64-p1:64:64-p2:32:32-p3:32:32:32:32:f-p4:64:64-p5:32:32:32:32:f"

arsenm wrote:

Doesn't matter what HSA says about it. Graphics uses it and it exists 

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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Matt Arsenault via cfe-commits


@@ -32,9 +32,9 @@ static const char *const DataLayoutStringR600 =
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
 
 static const char *const DataLayoutStringAMDGCN =
-"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
-"-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:"
-"32-v48:64-v96:128"
+"e-p:64:64-p1:64:64-p2:32:32-p3:32:32:32:32:f-p4:64:64-p5:32:32:32:32:f"
+"-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16"
+"-v24:32-v32:32-v48:64-v96:128"

arsenm wrote:

Not sure about the interaction with fat pointers. It only applies to a subset 
of the bits. But also not that important, we probably can't do much with that 
information 

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


[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -triple spirv64 -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+#include "Inputs/cuda.h"

arsenm wrote:

Probably should just locally define __global__ instead of depending on the full 
input header 

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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Matt Arsenault via cfe-commits


@@ -32,9 +32,9 @@ static const char *const DataLayoutStringR600 =
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
 
 static const char *const DataLayoutStringAMDGCN =
-"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
-"-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:"
-"32-v48:64-v96:128"
+"e-p:64:64-p1:64:64-p2:32:32-p3:32:32:32:32:f-p4:64:64-p5:32:32:32:32:f"

arsenm wrote:

p2 should also be -1 

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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Shilei Tian via cfe-commits


@@ -32,9 +32,9 @@ static const char *const DataLayoutStringR600 =
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
 
 static const char *const DataLayoutStringAMDGCN =
-"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
-"-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:"
-"32-v48:64-v96:128"
+"e-p:64:64-p1:64:64-p2:32:32-p3:32:32:32:32:f-p4:64:64-p5:32:32:32:32:f"
+"-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16"
+"-v24:32-v32:32-v48:64-v96:128"

shiltian wrote:

Right, that's why I didn't try to add that information to the fat pointer at 
the moment, and it is all-zero anyway.

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


[clang] [clang] Mark some language options as benign. (PR #131569)

2025-03-16 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/131569
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Fix a segfault when M is a nullptr (PR #130712)

2025-03-16 Thread via cfe-commits

https://github.com/matts1 updated 
https://github.com/llvm/llvm-project/pull/130712

>From 2c0dc1e7ee6a7ec499f4fcb88c79dc1aff8ce2ca Mon Sep 17 00:00:00 2001
From: Matt Stark 
Date: Mon, 10 Mar 2025 13:07:29 +1100
Subject: [PATCH] [clang] Fix a segfault when M is a nullptr

---
 clang/docs/ReleaseNotes.rst|  1 +
 clang/include/clang/Basic/Module.h |  2 +-
 clang/test/Modules/pr130712.cppm   | 31 ++
 3 files changed, 33 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Modules/pr130712.cppm

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a1c5ee2d788e..c7f8a564fe63a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -318,6 +318,7 @@ Bug Fixes to C++ Support
 - Fixed an assertion failure affecting code that uses C++23 "deducing this". 
(#GH130272)
 - Clang now properly instantiates destructors for initialized members within 
non-delegating constructors. (#GH93251)
 - Correctly diagnoses if unresolved using declarations shadows template 
paramters (#GH129411)
+- Clang no longer segfaults when there is a configuration mismatch between 
modules and their users (http://crbug.com/400353616).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Basic/Module.h 
b/clang/include/clang/Basic/Module.h
index 62cc8acf9588b..3d035f0a5f787 100644
--- a/clang/include/clang/Basic/Module.h
+++ b/clang/include/clang/Basic/Module.h
@@ -888,7 +888,7 @@ class VisibleModuleSet {
 
   /// Get the location at which the import of a module was triggered.
   SourceLocation getImportLoc(const Module *M) const {
-return M->getVisibilityID() < ImportLocs.size()
+return M && M->getVisibilityID() < ImportLocs.size()
? ImportLocs[M->getVisibilityID()]
: SourceLocation();
   }
diff --git a/clang/test/Modules/pr130712.cppm b/clang/test/Modules/pr130712.cppm
new file mode 100644
index 0..f908f1cb50bca
--- /dev/null
+++ b/clang/test/Modules/pr130712.cppm
@@ -0,0 +1,31 @@
+// RUN: split-file %s %t
+
+// There are two requirements here to result in the owner of a macro being 
null.
+// 1) There must be a configuration mismatch between a header and a file it 
depends on
+// 2) -fmodules-local-submodule-visibility must be enabled.
+
+// RUN: %clang_cc1 -I%t -emit-module -o %t/a.pcm -fmodules %t/module.modulemap 
-fmodule-name=a -fmodules-local-submodule-visibility 
+// RUN: %clang_cc1 -fexceptions -Wno-module-file-config-mismatch -I%t 
-emit-module -o %t/b.pcm -fmodules %t/module.modulemap -fmodule-name=b 
-fmodules-local-submodule-visibility -fmodule-file=%t/a.pcm
+// RUN: %clang_cc1 -fexceptions -Wno-module-file-config-mismatch -I%t 
-emit-module -o %t/c.pcm -fmodules %t/module.modulemap -fmodule-name=c 
-fmodules-local-submodule-visibility -fmodule-file=%t/a.pcm 
-fmodule-file=%t/b.pcm
+
+//--- module.modulemap
+module a { header "a.h" }
+module b { header "b.h" }
+module c { header "c.h" }
+
+//--- a.h
+#ifndef A_H
+#define A_H
+#endif
+
+//--- b.h
+#ifndef B_H
+#define B_H
+
+#include 
+
+#endif
+
+//--- c.h
+#include 
+#include 

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


[clang] [clang] Mark some language options as benign. (PR #131569)

2025-03-16 Thread via cfe-commits

https://github.com/matts1 created 
https://github.com/llvm/llvm-project/pull/131569

I'm  fairly certain that the options in this CL are benign, as I don't believe 
they affect the AST.
* RTTI - shouldn't affect the AST, should only affect codegen
* Trivial var init - also should only affect codegen
* Stack protector - also codegen
* Exceptions - Since exceptions do allow new things in the AST, but I'm pretty 
sure that they can differ in parent and child safely, I marked it as compatible 
instead.

I welcome any input from someone more familiar with this than me, as I might be 
wrong.

>From e32d927354eec4c9b029e84a45744f5fbf840b5f Mon Sep 17 00:00:00 2001
From: Matt Stark 
Date: Mon, 10 Mar 2025 12:09:49 +1100
Subject: [PATCH] [clang] Mark some language options as benign.

I'm  fairly certain that the options in this CL are benign, as I don't believe 
they affect the AST.
* RTTI - shouldn't affect the AST, should only affect codegen
* Trivial var init - also should only affect codegen
* Stack protector - also codegen
* Exceptions - Since exceptions do allow new things in the AST, but I'm pretty 
sure that they can differ in parent and child safely, I marked it as compatible 
instead.

I welcome any input from someone more familiar with this than me, as I might be 
wrong.
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Basic/LangOptions.def | 18 +-
 2 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 372a95c80717c..bcd5df2f2edc0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -295,6 +295,7 @@ Bug Fixes to C++ Support
 - Clang no longer crashes when a coroutine is declared ``[[noreturn]]``. 
(#GH127327)
 - Clang now uses the parameter location for abbreviated function templates in 
``extern "C"``. (#GH46386)
 - Clang now correctly parses ``if constexpr`` expressions in immediate 
function context. (#GH123524)
+- Clang modules now allow a module and its user to have a larger variety of 
configurations.
 
 Improvements to C++ diagnostics
 ^^^
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 383440ddbc0ea..beefc944959a1 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -139,9 +139,9 @@ ENUM_LANGOPT(AltivecSrcCompat, AltivecSrcCompatKind, 2,
 LANGOPT(ConvergentFunctions, 1, 1, "Assume convergent functions")
 LANGOPT(AltiVec   , 1, 0, "AltiVec-style vector initializers")
 LANGOPT(ZVector   , 1, 0, "System z vector extensions")
-LANGOPT(Exceptions, 1, 0, "exception handling")
-LANGOPT(ObjCExceptions, 1, 0, "Objective-C exceptions")
-LANGOPT(CXXExceptions , 1, 0, "C++ exceptions")
+COMPATIBLE_LANGOPT(Exceptions, 1, 0, "exception handling")
+COMPATIBLE_LANGOPT(ObjCExceptions, 1, 0, "Objective-C exceptions")
+COMPATIBLE_LANGOPT(CXXExceptions , 1, 0, "C++ exceptions")
 LANGOPT(EHAsynch  , 1, 0, "C/C++ EH Asynch exceptions")
 ENUM_LANGOPT(ExceptionHandling, ExceptionHandlingKind, 3,
  ExceptionHandlingKind::None, "exception handling")
@@ -149,8 +149,8 @@ LANGOPT(IgnoreExceptions  , 1, 0, "ignore exceptions")
 LANGOPT(ExternCNoUnwind   , 1, 0, "Assume extern C functions don't unwind")
 LANGOPT(AssumeNothrowExceptionDtor , 1, 0, "Assume exception object's 
destructor is nothrow")
 LANGOPT(TraditionalCPP, 1, 0, "traditional CPP emulation")
-LANGOPT(RTTI  , 1, 1, "run-time type information")
-LANGOPT(RTTIData  , 1, 1, "emit run-time type information data")
+BENIGN_LANGOPT(RTTI  , 1, 1, "run-time type information")
+BENIGN_LANGOPT(RTTIData  , 1, 1, "emit run-time type information data")
 LANGOPT(MSBitfields   , 1, 0, "Microsoft-compatible structure layout")
 LANGOPT(MSVolatile, 1, 0, "Microsoft-compatible volatile loads and 
stores")
 LANGOPT(Freestanding, 1, 0, "freestanding implementation")
@@ -397,13 +397,13 @@ 
BENIGN_ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, VisibilityFromDLLStor
 BENIGN_LANGOPT(SemanticInterposition, 1, 0, "semantic interposition")
 BENIGN_LANGOPT(HalfNoSemanticInterposition, 1, 0,
"Like -fno-semantic-interposition but don't use local aliases")
-ENUM_LANGOPT(StackProtector, StackProtectorMode, 2, SSPOff,
+BENIGN_ENUM_LANGOPT(StackProtector, StackProtectorMode, 2, SSPOff,
  "stack protector mode")
-ENUM_LANGOPT(TrivialAutoVarInit, TrivialAutoVarInitKind, 2, 
TrivialAutoVarInitKind::Uninitialized,
+BENIGN_ENUM_LANGOPT(TrivialAutoVarInit, TrivialAutoVarInitKind, 2, 
TrivialAutoVarInitKind::Uninitialized,
  "trivial automatic variable initialization")
-VALUE_LANGOPT(TrivialAutoVarInitStopAfter, 32, 0,
+BENIGN_VALUE_LANGOPT(TrivialAutoVarInitStopAfter, 32, 0,
  "stop trivial automatic variable initialization after the 
specified

[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-llvm-ir

Author: Shilei Tian (shiltian)


Changes

The value of a null pointer is not always `0`. For example, on AMDGPU, the null
pointer in address spaces 3 and 5 is `0x`. Currently, there is no
target-independent way to get this information, making it difficult and
error-prone to handle null pointers in target-agnostic code.

We do have `ConstantPointerNull`, but it might be a little confusing and
misleading. It represents a pointer with an all-zero value rather than
necessarily a real `nullptr`.

This PR introduces the concept of a *sentinel pointer value* to `DataLayout`,
representing the actual `nullptr` value for a given address space. The changes
include:

- A new interface function:
  ```
  APInt getSentinelPointerValue(unsigned AS)
  ```
  This function returns an `APInt` representing the sentinel pointer value for
  the given address space `AS`. An `APInt` is used instead of a literal integer
  to support cases where pointers are wider than 64 bits (e.g., AMDGPU’s address
  space 8).

- An extension to the data layout string format:
  ```
  p[n]::[:[:[:]]]
  ```
  The new `` component specifies the sentinel value for the
  corresponding pointer. It currently supports two values:
- `0` for an all-zero value
- `f` for a full-bit set value

  These two values are the most common representations of `nullptr`. It is
  unlikely that any target would define `nullptr` as a random value.

A follow-up patch series will introduce an equivalent of `ConstantPointerNull`
that represents the actual `nullptr`, built on top of this PR.

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


5 Files Affected:

- (modified) clang/lib/Basic/Targets/AMDGPU.cpp (+3-3) 
- (modified) llvm/docs/LangRef.rst (+7-4) 
- (modified) llvm/include/llvm/IR/DataLayout.h (+7-1) 
- (modified) llvm/lib/IR/DataLayout.cpp (+44-10) 
- (modified) llvm/unittests/IR/DataLayoutTest.cpp (+17-3) 


``diff
diff --git a/clang/lib/Basic/Targets/AMDGPU.cpp 
b/clang/lib/Basic/Targets/AMDGPU.cpp
index a42b4589fb5ac..1506387a41d96 100644
--- a/clang/lib/Basic/Targets/AMDGPU.cpp
+++ b/clang/lib/Basic/Targets/AMDGPU.cpp
@@ -32,9 +32,9 @@ static const char *const DataLayoutStringR600 =
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
 
 static const char *const DataLayoutStringAMDGCN =
-"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
-"-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:"
-"32-v48:64-v96:128"
+"e-p:64:64-p1:64:64-p2:32:32-p3:32:32:32:32:f-p4:64:64-p5:32:32:32:32:f"
+"-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16"
+"-v24:32-v32:32-v48:64-v96:128"
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1"
 "-ni:7:8:9";
 
diff --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index c0567090fdd2a..a22020da38f83 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -3134,7 +3134,7 @@ as follows:
 ``A``
 Specifies the address space of objects created by '``alloca``'.
 Defaults to the default address space of 0.
-``p[n]::[:][:]``
+``p[]::[:[:[:]]]``
 This specifies the *size* of a pointer and its  and
 \erred alignments for address space ``n``.  is optional
 and defaults to . The fourth parameter  is the size of 
the
@@ -3143,7 +3143,10 @@ as follows:
 specified, the default index size is equal to the pointer size. All sizes
 are in bits. The address space, ``n``, is optional, and if not specified,
 denotes the default address space 0. The value of ``n`` must be
-in the range [1,2^24).
+in the range [1,2^24). The fifth parameter  specifies the
+sentinel value of the pointer for the corresponding address space. It
+currently accepts two values: ``0`` for an all-zero value and ``f`` for a
+full-bit set value. The default sentinel pointer value is all-zero.
 ``i:[:]``
 This specifies the alignment for an integer type of a given bit
 . The value of  must be in the range [1,2^24).
@@ -13045,9 +13048,9 @@ This instruction requires several arguments:
-  Caller and callee both have the calling convention ``fastcc`` or 
``tailcc``.
-  The call is in tail position (ret immediately follows call and ret
   uses value of call or is void).
-   -  Option ``-tailcallopt`` is enabled, ``llvm::GuaranteedTailCallOpt`` is 
+   -  Option ``-tailcallopt`` is enabled, ``llvm::GuaranteedTailCallOpt`` is
   ``true``, or the calling convention is ``tailcc``.
-   -  `Platform-specific constraints are met. 
+   -  `Platform-specific constraints are met.
   `_
 
 #. The optional ``notail`` marker indicates that the optimizers should not add
diff --git a/llvm/include/llvm/IR/DataLayout.h 
b/llvm/include/llvm/IR/DataLayout.h
index 2ad080e6d0cd2..1257ffb32a4df 100644
--

[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 4fde8c341f9166e6ec6dff6e7704be175e382f5b 
c966236e1ec99fbd45063e0363873c8d8abe4c50 --extensions h,cpp -- 
clang/lib/Basic/Targets/AMDGPU.cpp llvm/include/llvm/IR/DataLayout.h 
llvm/lib/IR/DataLayout.cpp llvm/unittests/IR/DataLayoutTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/unittests/IR/DataLayoutTest.cpp 
b/llvm/unittests/IR/DataLayoutTest.cpp
index 79d46ebfd7..a775c7417b 100644
--- a/llvm/unittests/IR/DataLayoutTest.cpp
+++ b/llvm/unittests/IR/DataLayoutTest.cpp
@@ -312,8 +312,8 @@ TEST(DataLayout, ParsePointerSpec) {
 "p16777215:32:32:64:8", "p16777215:16777215:32768:32768:16777215"})
 EXPECT_THAT_EXPECTED(DataLayout::parse(Str), Succeeded());
 
-  for (StringRef Str :
-   {"p", "p0", "p:32", "p0:32", "p:32:32:32:32:32:0", 
"p0:32:32:32:32:32:0"})
+  for (StringRef Str : {"p", "p0", "p:32", "p0:32", "p:32:32:32:32:32:0",
+"p0:32:32:32:32:32:0"})
 EXPECT_THAT_EXPECTED(
 DataLayout::parse(Str),
 FailedWithMessage(

``




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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Matt Arsenault via cfe-commits


@@ -13045,9 +13048,9 @@ This instruction requires several arguments:
-  Caller and callee both have the calling convention ``fastcc`` or 
``tailcc``.
-  The call is in tail position (ret immediately follows call and ret
   uses value of call or is void).
-   -  Option ``-tailcallopt`` is enabled, ``llvm::GuaranteedTailCallOpt`` is 
+   -  Option ``-tailcallopt`` is enabled, ``llvm::GuaranteedTailCallOpt`` is

arsenm wrote:

Unrelated whitespace changes 

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


[clang] [clang] Mark some language options as benign. (PR #131569)

2025-03-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Matt (matts1)


Changes

I'm  fairly certain that the options in this CL are benign, as I don't believe 
they affect the AST.
* RTTI - shouldn't affect the AST, should only affect codegen
* Trivial var init - also should only affect codegen
* Stack protector - also codegen
* Exceptions - Since exceptions do allow new things in the AST, but I'm pretty 
sure that they can differ in parent and child safely, I marked it as compatible 
instead.

I welcome any input from someone more familiar with this than me, as I might be 
wrong.

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


2 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1) 
- (modified) clang/include/clang/Basic/LangOptions.def (+9-9) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 372a95c80717c..bcd5df2f2edc0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -295,6 +295,7 @@ Bug Fixes to C++ Support
 - Clang no longer crashes when a coroutine is declared ``[[noreturn]]``. 
(#GH127327)
 - Clang now uses the parameter location for abbreviated function templates in 
``extern "C"``. (#GH46386)
 - Clang now correctly parses ``if constexpr`` expressions in immediate 
function context. (#GH123524)
+- Clang modules now allow a module and its user to have a larger variety of 
configurations.
 
 Improvements to C++ diagnostics
 ^^^
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 383440ddbc0ea..beefc944959a1 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -139,9 +139,9 @@ ENUM_LANGOPT(AltivecSrcCompat, AltivecSrcCompatKind, 2,
 LANGOPT(ConvergentFunctions, 1, 1, "Assume convergent functions")
 LANGOPT(AltiVec   , 1, 0, "AltiVec-style vector initializers")
 LANGOPT(ZVector   , 1, 0, "System z vector extensions")
-LANGOPT(Exceptions, 1, 0, "exception handling")
-LANGOPT(ObjCExceptions, 1, 0, "Objective-C exceptions")
-LANGOPT(CXXExceptions , 1, 0, "C++ exceptions")
+COMPATIBLE_LANGOPT(Exceptions, 1, 0, "exception handling")
+COMPATIBLE_LANGOPT(ObjCExceptions, 1, 0, "Objective-C exceptions")
+COMPATIBLE_LANGOPT(CXXExceptions , 1, 0, "C++ exceptions")
 LANGOPT(EHAsynch  , 1, 0, "C/C++ EH Asynch exceptions")
 ENUM_LANGOPT(ExceptionHandling, ExceptionHandlingKind, 3,
  ExceptionHandlingKind::None, "exception handling")
@@ -149,8 +149,8 @@ LANGOPT(IgnoreExceptions  , 1, 0, "ignore exceptions")
 LANGOPT(ExternCNoUnwind   , 1, 0, "Assume extern C functions don't unwind")
 LANGOPT(AssumeNothrowExceptionDtor , 1, 0, "Assume exception object's 
destructor is nothrow")
 LANGOPT(TraditionalCPP, 1, 0, "traditional CPP emulation")
-LANGOPT(RTTI  , 1, 1, "run-time type information")
-LANGOPT(RTTIData  , 1, 1, "emit run-time type information data")
+BENIGN_LANGOPT(RTTI  , 1, 1, "run-time type information")
+BENIGN_LANGOPT(RTTIData  , 1, 1, "emit run-time type information data")
 LANGOPT(MSBitfields   , 1, 0, "Microsoft-compatible structure layout")
 LANGOPT(MSVolatile, 1, 0, "Microsoft-compatible volatile loads and 
stores")
 LANGOPT(Freestanding, 1, 0, "freestanding implementation")
@@ -397,13 +397,13 @@ 
BENIGN_ENUM_LANGOPT(ExternDeclNoDLLStorageClassVisibility, VisibilityFromDLLStor
 BENIGN_LANGOPT(SemanticInterposition, 1, 0, "semantic interposition")
 BENIGN_LANGOPT(HalfNoSemanticInterposition, 1, 0,
"Like -fno-semantic-interposition but don't use local aliases")
-ENUM_LANGOPT(StackProtector, StackProtectorMode, 2, SSPOff,
+BENIGN_ENUM_LANGOPT(StackProtector, StackProtectorMode, 2, SSPOff,
  "stack protector mode")
-ENUM_LANGOPT(TrivialAutoVarInit, TrivialAutoVarInitKind, 2, 
TrivialAutoVarInitKind::Uninitialized,
+BENIGN_ENUM_LANGOPT(TrivialAutoVarInit, TrivialAutoVarInitKind, 2, 
TrivialAutoVarInitKind::Uninitialized,
  "trivial automatic variable initialization")
-VALUE_LANGOPT(TrivialAutoVarInitStopAfter, 32, 0,
+BENIGN_VALUE_LANGOPT(TrivialAutoVarInitStopAfter, 32, 0,
  "stop trivial automatic variable initialization after the 
specified number of instances. Must be greater than 0.")
-VALUE_LANGOPT(TrivialAutoVarInitMaxSize, 32, 0,
+BENIGN_VALUE_LANGOPT(TrivialAutoVarInitMaxSize, 32, 0,
  "stop trivial automatic variable initialization if var size 
exceeds the specified size (in bytes). Must be greater than 0.")
 ENUM_LANGOPT(SignedOverflowBehavior, SignedOverflowBehaviorTy, 2, 
SOB_Undefined,
  "signed integer overflow handling")

``




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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Shilei Tian via cfe-commits

https://github.com/shiltian created 
https://github.com/llvm/llvm-project/pull/131557

The value of a null pointer is not always `0`. For example, on AMDGPU, the null
pointer in address spaces 3 and 5 is `0x`. Currently, there is no
target-independent way to get this information, making it difficult and
error-prone to handle null pointers in target-agnostic code.

We do have `ConstantPointerNull`, but it might be a little confusing and
misleading. It represents a pointer with an all-zero value rather than
necessarily a real `nullptr`.

This PR introduces the concept of a *sentinel pointer value* to `DataLayout`,
representing the actual `nullptr` value for a given address space. The changes
include:

- A new interface function:
  ```
  APInt getSentinelPointerValue(unsigned AS)
  ```
  This function returns an `APInt` representing the sentinel pointer value for
  the given address space `AS`. An `APInt` is used instead of a literal integer
  to support cases where pointers are wider than 64 bits (e.g., AMDGPU’s address
  space 8).

- An extension to the data layout string format:
  ```
  p[n]::[:[:[:]]]
  ```
  The new `` component specifies the sentinel value for the
  corresponding pointer. It currently supports two values:
- `0` for an all-zero value
- `f` for a full-bit set value

  These two values are the most common representations of `nullptr`. It is
  unlikely that any target would define `nullptr` as a random value.

A follow-up patch series will introduce an equivalent of `ConstantPointerNull`
that represents the actual `nullptr`, built on top of this PR.

>From c966236e1ec99fbd45063e0363873c8d8abe4c50 Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Sun, 16 Mar 2025 23:43:43 -0400
Subject: [PATCH] [DataLayout] Introduce sentinel pointer value
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

The value of a null pointer is not always `0`. For example, on AMDGPU, the null
pointer in address spaces 3 and 5 is `0x`. Currently, there is no
target-independent way to get this information, making it difficult and
error-prone to handle null pointers in target-agnostic code.

We do have `ConstantPointerNull`, but it might be a little confusing and
misleading. It represents a pointer with an all-zero value rather than
necessarily a real `nullptr`.

This PR introduces the concept of a *sentinel pointer value* to `DataLayout`,
representing the actual `nullptr` value for a given address space. The changes
include:

- A new interface function:
  ```
  APInt getSentinelPointerValue(unsigned AS)
  ```
  This function returns an `APInt` representing the sentinel pointer value for
  the given address space `AS`. An `APInt` is used instead of a literal integer
  to support cases where pointers are wider than 64 bits (e.g., AMDGPU’s address
  space 8).

- An extension to the data layout string format:
  ```
  p[n]::[:[:[:]]]
  ```
  The new `` component specifies the sentinel value for the
  corresponding pointer. It currently supports two values:
- `0` for an all-zero value
- `f` for a full-bit set value

  These two values are the most common representations of `nullptr`. It is
  unlikely that any target would define `nullptr` as a random value.

A follow-up patch series will introduce an equivalent of `ConstantPointerNull`
that represents the actual `nullptr`, built on top of this PR.
---
 clang/lib/Basic/Targets/AMDGPU.cpp   |  6 ++--
 llvm/docs/LangRef.rst| 11 +++---
 llvm/include/llvm/IR/DataLayout.h|  8 -
 llvm/lib/IR/DataLayout.cpp   | 54 ++--
 llvm/unittests/IR/DataLayoutTest.cpp | 20 +--
 5 files changed, 78 insertions(+), 21 deletions(-)

diff --git a/clang/lib/Basic/Targets/AMDGPU.cpp 
b/clang/lib/Basic/Targets/AMDGPU.cpp
index a42b4589fb5ac..1506387a41d96 100644
--- a/clang/lib/Basic/Targets/AMDGPU.cpp
+++ b/clang/lib/Basic/Targets/AMDGPU.cpp
@@ -32,9 +32,9 @@ static const char *const DataLayoutStringR600 =
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
 
 static const char *const DataLayoutStringAMDGCN =
-"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
-"-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:"
-"32-v48:64-v96:128"
+"e-p:64:64-p1:64:64-p2:32:32-p3:32:32:32:32:f-p4:64:64-p5:32:32:32:32:f"
+"-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16"
+"-v24:32-v32:32-v48:64-v96:128"
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1"
 "-ni:7:8:9";
 
diff --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index c0567090fdd2a..a22020da38f83 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -3134,7 +3134,7 @@ as follows:
 ``A``
 Specifies the address space of objects created by '``alloca``'.
 Defaults to the default address space of 0.
-``p[n]::[:][:]``
+``p[]::[:[:[:]]]``
 This specifies the *size* o

[clang] [llvm] [BPF] Make -mcpu=v3 as the default (PR #107008)

2025-03-16 Thread via cfe-commits

yonghong-song wrote:

Thanks @yuvald-sweet-security I am not sure whether I can add default v1->v3 in 
llvm20 or not. But let me check anyway.

Also, if the verification failure can be easily reproduced, could you submit 
the test case, we can do some analysis to see why and maybe verifier could be 
improved due to this. Thanks!

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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Matt Arsenault via cfe-commits

https://github.com/arsenm commented:

This needs an RFC. For reference a previous attempt was at #83109

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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Shilei Tian via cfe-commits


@@ -32,9 +32,9 @@ static const char *const DataLayoutStringR600 =
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
 
 static const char *const DataLayoutStringAMDGCN =
-"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
-"-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:"
-"32-v48:64-v96:128"
+"e-p:64:64-p1:64:64-p2:32:32-p3:32:32:32:32:f-p4:64:64-p5:32:32:32:32:f"

shiltian wrote:

Our document says not implemented for HSA though.

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


[clang] 752aa81 - [clang][RISCV] Rename variable name in SemaRISCV. NFC (#131261)

2025-03-16 Thread via cfe-commits

Author: Brandon Wu
Date: 2025-03-17T12:55:59+08:00
New Revision: 752aa81c4ff754945c695ac771577c1370564411

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

LOG: [clang][RISCV] Rename variable name in SemaRISCV. NFC (#131261)

Added: 


Modified: 
clang/lib/Sema/SemaRISCV.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaRISCV.cpp b/clang/lib/Sema/SemaRISCV.cpp
index 69a00adda506c..f23827d566610 100644
--- a/clang/lib/Sema/SemaRISCV.cpp
+++ b/clang/lib/Sema/SemaRISCV.cpp
@@ -687,22 +687,22 @@ bool SemaRISCV::CheckBuiltinFunctionCall(const TargetInfo 
&TI,
   case RISCVVector::BI__builtin_rvv_vaeskf2_vi_tu:
   case RISCVVector::BI__builtin_rvv_vaeskf2_vi:
   case RISCVVector::BI__builtin_rvv_vsm4k_vi_tu: {
-QualType Op1Type = TheCall->getArg(0)->getType();
-QualType Op2Type = TheCall->getArg(1)->getType();
-return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Op1Type, 128) ||
-   CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Op2Type, 128) ||
+QualType Arg0Type = TheCall->getArg(0)->getType();
+QualType Arg1Type = TheCall->getArg(1)->getType();
+return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Arg0Type, 128) ||
+   CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Arg1Type, 128) ||
SemaRef.BuiltinConstantArgRange(TheCall, 2, 0, 31);
   }
   case RISCVVector::BI__builtin_rvv_vsm3c_vi_tu:
   case RISCVVector::BI__builtin_rvv_vsm3c_vi: {
-QualType Op1Type = TheCall->getArg(0)->getType();
-return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Op1Type, 256) ||
+QualType Arg0Type = TheCall->getArg(0)->getType();
+return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Arg0Type, 256) ||
SemaRef.BuiltinConstantArgRange(TheCall, 2, 0, 31);
   }
   case RISCVVector::BI__builtin_rvv_vaeskf1_vi:
   case RISCVVector::BI__builtin_rvv_vsm4k_vi: {
-QualType Op1Type = TheCall->getArg(0)->getType();
-return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Op1Type, 128) ||
+QualType Arg0Type = TheCall->getArg(0)->getType();
+return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Arg0Type, 128) ||
SemaRef.BuiltinConstantArgRange(TheCall, 1, 0, 31);
   }
   case RISCVVector::BI__builtin_rvv_vaesdf_vv:
@@ -727,10 +727,10 @@ bool SemaRISCV::CheckBuiltinFunctionCall(const TargetInfo 
&TI,
   case RISCVVector::BI__builtin_rvv_vaesz_vs_tu:
   case RISCVVector::BI__builtin_rvv_vsm4r_vv_tu:
   case RISCVVector::BI__builtin_rvv_vsm4r_vs_tu: {
-QualType Op1Type = TheCall->getArg(0)->getType();
-QualType Op2Type = TheCall->getArg(1)->getType();
-return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Op1Type, 128) ||
-   CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Op2Type, 128);
+QualType Arg0Type = TheCall->getArg(0)->getType();
+QualType Arg1Type = TheCall->getArg(1)->getType();
+return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Arg0Type, 128) ||
+   CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Arg1Type, 128);
   }
   case RISCVVector::BI__builtin_rvv_vsha2ch_vv:
   case RISCVVector::BI__builtin_rvv_vsha2cl_vv:
@@ -738,22 +738,23 @@ bool SemaRISCV::CheckBuiltinFunctionCall(const TargetInfo 
&TI,
   case RISCVVector::BI__builtin_rvv_vsha2ch_vv_tu:
   case RISCVVector::BI__builtin_rvv_vsha2cl_vv_tu:
   case RISCVVector::BI__builtin_rvv_vsha2ms_vv_tu: {
-QualType Op1Type = TheCall->getArg(0)->getType();
-QualType Op2Type = TheCall->getArg(1)->getType();
-QualType Op3Type = TheCall->getArg(2)->getType();
+QualType Arg0Type = TheCall->getArg(0)->getType();
+QualType Arg1Type = TheCall->getArg(1)->getType();
+QualType Arg2Type = TheCall->getArg(2)->getType();
 ASTContext::BuiltinVectorTypeInfo Info =
-Context.getBuiltinVectorTypeInfo(Op1Type->castAs());
+Context.getBuiltinVectorTypeInfo(Arg0Type->castAs());
 uint64_t ElemSize = Context.getTypeSize(Info.ElementType);
 if (ElemSize == 64 && !TI.hasFeature("zvknhb"))
   return Diag(TheCall->getBeginLoc(),
   diag::err_riscv_builtin_requires_extension)
  << /* IsExtension */ true << TheCall->getSourceRange() << 
"zvknhb";
 
-return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Op1Type,
+return CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Arg0Type,
ElemSize * 4) ||
-   CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Op2Type,
+   CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Arg1Type,
ElemSize * 4) ||
-   CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Op3Type, ElemSize * 
4);
+   CheckInvalidVLENandLMUL(TI, TheCall, SemaRef, Arg2Type,
+   ElemSize * 4);
   }
 
   case RISCVVector::BI__builtin_rvv_sf_vc_i_se:

[clang-tools-extra] [clangd] Add `HeaderInsertion` yaml config option (PR #128503)

2025-03-16 Thread via cfe-commits

https://github.com/MythreyaK updated 
https://github.com/llvm/llvm-project/pull/128503

>From 60ffbf0067b52cf51b5ce1d8eaf98cd2a2737c6a Mon Sep 17 00:00:00 2001
From: Mythreya 
Date: Mon, 24 Feb 2025 04:34:38 -0800
Subject: [PATCH 1/2] [clangd] Add `HeaderInsertion` yaml config option

This is the yaml config equivalent of `--header-insertion` CLI option
---
 clang-tools-extra/clangd/ClangdServer.cpp |  1 +
 clang-tools-extra/clangd/CodeComplete.cpp |  3 ++-
 clang-tools-extra/clangd/CodeComplete.h   |  6 ++
 clang-tools-extra/clangd/Config.h |  9 +
 clang-tools-extra/clangd/ConfigCompile.cpp| 11 +++
 clang-tools-extra/clangd/ConfigFragment.h |  8 
 clang-tools-extra/clangd/ConfigYAML.cpp   |  4 
 clang-tools-extra/clangd/tool/ClangdMain.cpp  |  4 ++--
 .../clangd/unittests/CodeCompleteTests.cpp|  3 ++-
 9 files changed, 41 insertions(+), 8 deletions(-)

diff --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 49a97da2bfa42..47152b7c36140 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -455,6 +455,7 @@ void ClangdServer::codeComplete(PathRef File, Position Pos,
 CodeCompleteOpts.MainFileSignals = IP->Signals;
 CodeCompleteOpts.AllScopes = Config::current().Completion.AllScopes;
 CodeCompleteOpts.ArgumentLists = 
Config::current().Completion.ArgumentLists;
+CodeCompleteOpts.InsertIncludes = Config::current().HeaderInsertion.Policy;
 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
 // both the old and the new version in case only one of them matches.
 CodeCompleteResult Result = clangd::codeComplete(
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index a8182ce98ebe0..5db8eeaee1027 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -294,7 +294,8 @@ struct CompletionCandidate {
   std::optional
   headerToInsertIfAllowed(const CodeCompleteOptions &Opts,
   CodeCompletionContext::Kind ContextKind) const {
-if (Opts.InsertIncludes == CodeCompleteOptions::NeverInsert ||
+if (Opts.InsertIncludes ==
+CodeCompleteOptions::IncludeInsertion::NeverInsert ||
 RankedIncludeHeaders.empty() ||
 !contextAllowsHeaderInsertion(ContextKind))
   return std::nullopt;
diff --git a/clang-tools-extra/clangd/CodeComplete.h 
b/clang-tools-extra/clangd/CodeComplete.h
index cd41f04e4fb5c..f1e4ebae10ebb 100644
--- a/clang-tools-extra/clangd/CodeComplete.h
+++ b/clang-tools-extra/clangd/CodeComplete.h
@@ -71,10 +71,8 @@ struct CodeCompleteOptions {
   /// Whether to present doc comments as plain-text or markdown.
   MarkupKind DocumentationFormat = MarkupKind::PlainText;
 
-  enum IncludeInsertion {
-IWYU,
-NeverInsert,
-  } InsertIncludes = IncludeInsertion::IWYU;
+  using IncludeInsertion = Config::HeaderInsertionPolicy;
+  Config::HeaderInsertionPolicy InsertIncludes = IncludeInsertion::IWYU;
 
   /// Whether include insertions for Objective-C code should use #import 
instead
   /// of #include.
diff --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 3f8a3c9b060f6..e6e4e446ba3e7 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -156,6 +156,15 @@ struct Config {
 ArgumentListsPolicy ArgumentLists = ArgumentListsPolicy::FullPlaceholders;
   } Completion;
 
+  enum class HeaderInsertionPolicy {
+IWYU,   // Include what you use
+NeverInsert // Never insert headers as part of code completion
+  };
+
+  struct {
+HeaderInsertionPolicy Policy = HeaderInsertionPolicy::IWYU;
+  } HeaderInsertion;
+
   /// Configures hover feature.
   struct {
 /// Whether hover show a.k.a type.
diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index 31530c206acd7..d57020eaf7c83 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -697,6 +697,17 @@ struct FragmentCompiler {
   C.Completion.ArgumentLists = *Val;
 });
 }
+if (F.HeaderInsertion) {
+  if (auto Val =
+  compileEnum("HeaderInsertion",
+ *F.HeaderInsertion)
+  .map("IWYU", Config::HeaderInsertionPolicy::IWYU)
+  .map("Never", Config::HeaderInsertionPolicy::NeverInsert)
+  .value())
+Out.Apply.push_back([Val](const Params &, Config &C) {
+  C.HeaderInsertion.Policy = *Val;
+});
+}
   }
 
   void compile(Fragment::HoverBlock &&F) {
diff --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index 6f95474b9c008..f05ed4d1a

[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Shilei Tian via cfe-commits

shiltian wrote:

* **#131557** https://app.graphite.dev/github/pr/llvm/llvm-project/131557?utm_source=stack-comment-icon";
 target="_blank">https://static.graphite.dev/graphite-32x32-black.png"; alt="Graphite" 
width="10px" height="10px"/> 👈 https://app.graphite.dev/github/pr/llvm/llvm-project/131557?utm_source=stack-comment-view-in-graphite";
 target="_blank">(View in Graphite)
* `main`




This stack of pull requests is managed by https://graphite.dev?utm-source=stack-comment";>Graphite. Learn 
more about https://stacking.dev/?utm_source=stack-comment";>stacking.


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


[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread Matt Arsenault via cfe-commits


@@ -753,12 +753,20 @@ void CodeGenModule::handleAMDGPUFlatWorkGroupSizeAttr(
 int32_t *MaxThreadsVal) {
   unsigned Min = 0;
   unsigned Max = 0;
+  auto Eval = [&](Expr *E) {
+return E->EvaluateKnownConstInt(getContext()).getExtValue();
+  };
   if (FlatWGS) {
-Min = FlatWGS->getMin()->EvaluateKnownConstInt(getContext()).getExtValue();
-Max = FlatWGS->getMax()->EvaluateKnownConstInt(getContext()).getExtValue();
+Min = Eval(
+FlatWGS
+->getMin());
+Max = Eval(
+FlatWGS
+->getMax());

arsenm wrote:

Fix formatting 

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


[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread Matt Arsenault via cfe-commits


@@ -53,15 +53,15 @@ void TCETargetCodeGenInfo::setTargetAttributes(
 SmallVector Operands;
 Operands.push_back(llvm::ConstantAsMetadata::get(F));
 
-Operands.push_back(
-llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
-M.Int32Ty, llvm::APInt(32, Attr->getXDim();
-Operands.push_back(
-llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
-M.Int32Ty, llvm::APInt(32, Attr->getYDim();
-Operands.push_back(
-llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
-M.Int32Ty, llvm::APInt(32, Attr->getZDim();
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext());
+};
+Operands.push_back(llvm::ConstantAsMetadata::get(
+llvm::Constant::getIntegerValue(M.Int32Ty, 
Eval(Attr->getXDim();
+Operands.push_back(llvm::ConstantAsMetadata::get(
+llvm::Constant::getIntegerValue(M.Int32Ty, 
Eval(Attr->getYDim();
+Operands.push_back(llvm::ConstantAsMetadata::get(
+llvm::Constant::getIntegerValue(M.Int32Ty, 
Eval(Attr->getZDim();

arsenm wrote:

Can move all this into the Operands initializer list 

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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Shilei Tian via cfe-commits

shiltian wrote:

The RFC is posted 
https://discourse.llvm.org/t/rfc-introduce-sentinel-pointer-value-to-datalayout/85265.

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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Shilei Tian via cfe-commits

shiltian wrote:

> This needs an RFC. For reference a previous attempt was at #83109

The RFC was posted, as mentioned in a previous comment.

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


[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/131546

>From 94a49544f02ac576cbe5bcd9274a0b95943f97a3 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Mon, 17 Mar 2025 00:39:24 +
Subject: [PATCH] [CudaSPIRV] Allow using integral non-type template parameters
 as reqd_work_group_size arguments

---
 .../altera/SingleWorkItemBarrierCheck.cpp |  8 +-
 clang/include/clang/Basic/Attr.td |  7 +-
 clang/lib/CodeGen/CodeGenFunction.cpp | 18 +++--
 clang/lib/CodeGen/Targets/AMDGPU.cpp  | 10 ++-
 clang/lib/CodeGen/Targets/TCE.cpp | 27 +++
 clang/lib/Sema/SemaDeclAttr.cpp   | 79 ---
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 32 
 clang/test/SemaCUDA/spirv-attrs-diag.cu   | 34 
 clang/test/SemaCUDA/spirv-attrs.cu| 14 
 9 files changed, 189 insertions(+), 40 deletions(-)
 create mode 100644 clang/test/SemaCUDA/spirv-attrs-diag.cu

diff --git a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
index df21c425ea956..c5da66a1f28b6 100644
--- a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
@@ -54,8 +54,12 @@ void SingleWorkItemBarrierCheck::check(const 
MatchFinder::MatchResult &Result) {
 bool IsNDRange = false;
 if (MatchedDecl->hasAttr()) {
   const auto *Attribute = MatchedDecl->getAttr();
-  if (Attribute->getXDim() > 1 || Attribute->getYDim() > 1 ||
-  Attribute->getZDim() > 1)
+  auto Eval = [&](Expr *E) {
+return E->EvaluateKnownConstInt(MatchedDecl->getASTContext())
+.getExtValue();
+  };
+  if (Eval(Attribute->getXDim()) > 1 || Eval(Attribute->getYDim()) > 1 ||
+  Eval(Attribute->getZDim()) > 1)
 IsNDRange = true;
 }
 if (IsNDRange) // No warning if kernel is treated as an NDRange.
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 4d34346460561..cceb4085d523d 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3044,8 +3044,7 @@ def NoDeref : TypeAttr {
 def ReqdWorkGroupSize : InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"reqd_work_group_size">];
-  let Args = [UnsignedArgument<"XDim">, UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
@@ -3053,9 +3052,7 @@ def ReqdWorkGroupSize : InheritableAttr {
 def WorkGroupSizeHint :  InheritableAttr {
   // Does not have a [[]] spelling because it is an OpenCL-related attribute.
   let Spellings = [GNU<"work_group_size_hint">];
-  let Args = [UnsignedArgument<"XDim">,
-  UnsignedArgument<"YDim">,
-  UnsignedArgument<"ZDim">];
+  let Args = [ExprArgument<"XDim">, ExprArgument<"YDim">, 
ExprArgument<"ZDim">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
 }
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 447192bc7f60c..de1e04a7982fa 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -649,18 +649,24 @@ void CodeGenFunction::EmitKernelMetadata(const 
FunctionDecl *FD,
   }
 
   if (const WorkGroupSizeHintAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getZDim(};
 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, 
AttrMDArgs));
   }
 
   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr()) {
+auto Eval = [&](Expr *E) {
+  return E->EvaluateKnownConstInt(FD->getASTContext()).getExtValue();
+};
 llvm::Metadata *AttrMDArgs[] = {
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
-llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getXDim(,
+llvm::ConstantAsMetadata::get(Builder.getInt32(Eval(A->getYDim(,
+llvm::ConstantAsMetadata::get(Builder.g

[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Shilei Tian via cfe-commits

https://github.com/shiltian updated 
https://github.com/llvm/llvm-project/pull/131557

>From 86cd48c8f43b34d9fee97137db8abe6454d76268 Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Sun, 16 Mar 2025 23:51:02 -0400
Subject: [PATCH] [DataLayout] Introduce sentinel pointer value
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

The value of a null pointer is not always `0`. For example, on AMDGPU, the null
pointer in address spaces 3 and 5 is `0x`. Currently, there is no
target-independent way to get this information, making it difficult and
error-prone to handle null pointers in target-agnostic code.

We do have `ConstantPointerNull`, but it might be a little confusing and
misleading. It represents a pointer with an all-zero value rather than
necessarily a real `nullptr`.

This PR introduces the concept of a *sentinel pointer value* to `DataLayout`,
representing the actual `nullptr` value for a given address space. The changes
include:

- A new interface function:
  ```
  APInt getSentinelPointerValue(unsigned AS)
  ```
  This function returns an `APInt` representing the sentinel pointer value for
  the given address space `AS`. An `APInt` is used instead of a literal integer
  to support cases where pointers are wider than 64 bits (e.g., AMDGPU’s address
  space 8).

- An extension to the data layout string format:
  ```
  p[n]::[:[:[:]]]
  ```
  The new `` component specifies the sentinel value for the
  corresponding pointer. It currently supports two values:
- `0` for an all-zero value
- `f` for a full-bit set value

  These two values are the most common representations of `nullptr`. It is
  unlikely that any target would define `nullptr` as a random value.

A follow-up patch series will introduce an equivalent of `ConstantPointerNull`
that represents the actual `nullptr`, built on top of this PR.
---
 clang/lib/Basic/Targets/AMDGPU.cpp   |  6 +--
 llvm/docs/LangRef.rst| 11 --
 llvm/include/llvm/IR/DataLayout.h|  8 +++-
 llvm/lib/IR/DataLayout.cpp   | 55 +++-
 llvm/unittests/IR/DataLayoutTest.cpp | 20 --
 5 files changed, 79 insertions(+), 21 deletions(-)

diff --git a/clang/lib/Basic/Targets/AMDGPU.cpp 
b/clang/lib/Basic/Targets/AMDGPU.cpp
index a42b4589fb5ac..1506387a41d96 100644
--- a/clang/lib/Basic/Targets/AMDGPU.cpp
+++ b/clang/lib/Basic/Targets/AMDGPU.cpp
@@ -32,9 +32,9 @@ static const char *const DataLayoutStringR600 =
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
 
 static const char *const DataLayoutStringAMDGCN =
-"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
-"-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:"
-"32-v48:64-v96:128"
+"e-p:64:64-p1:64:64-p2:32:32-p3:32:32:32:32:f-p4:64:64-p5:32:32:32:32:f"
+"-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16"
+"-v24:32-v32:32-v48:64-v96:128"
 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1"
 "-ni:7:8:9";
 
diff --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index c0567090fdd2a..a22020da38f83 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -3134,7 +3134,7 @@ as follows:
 ``A``
 Specifies the address space of objects created by '``alloca``'.
 Defaults to the default address space of 0.
-``p[n]::[:][:]``
+``p[]::[:[:[:]]]``
 This specifies the *size* of a pointer and its  and
 \erred alignments for address space ``n``.  is optional
 and defaults to . The fourth parameter  is the size of 
the
@@ -3143,7 +3143,10 @@ as follows:
 specified, the default index size is equal to the pointer size. All sizes
 are in bits. The address space, ``n``, is optional, and if not specified,
 denotes the default address space 0. The value of ``n`` must be
-in the range [1,2^24).
+in the range [1,2^24). The fifth parameter  specifies the
+sentinel value of the pointer for the corresponding address space. It
+currently accepts two values: ``0`` for an all-zero value and ``f`` for a
+full-bit set value. The default sentinel pointer value is all-zero.
 ``i:[:]``
 This specifies the alignment for an integer type of a given bit
 . The value of  must be in the range [1,2^24).
@@ -13045,9 +13048,9 @@ This instruction requires several arguments:
-  Caller and callee both have the calling convention ``fastcc`` or 
``tailcc``.
-  The call is in tail position (ret immediately follows call and ret
   uses value of call or is void).
-   -  Option ``-tailcallopt`` is enabled, ``llvm::GuaranteedTailCallOpt`` is 
+   -  Option ``-tailcallopt`` is enabled, ``llvm::GuaranteedTailCallOpt`` is
   ``true``, or the calling convention is ``tailcc``.
-   -  `Platform-specific constraints are met. 
+   -  `Platform-specific constraints are met.
   `_
 
 #. The optional ``notail`` marker indica

[clang] [Clang-repl] Implementation for removeModule for wasm use case (PR #131558)

2025-03-16 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 41cece8c86399dd1ffcb6b7a8b50c10083fe5a40 
56d3e301d01cb8ab8f44751d7684378f38b0661e --extensions cpp,h -- 
clang/lib/Interpreter/Wasm.cpp clang/lib/Interpreter/Wasm.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Interpreter/Wasm.cpp b/clang/lib/Interpreter/Wasm.cpp
index ed746beefd..6a59c8961b 100644
--- a/clang/lib/Interpreter/Wasm.cpp
+++ b/clang/lib/Interpreter/Wasm.cpp
@@ -133,7 +133,8 @@ llvm::Error 
WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
 llvm::Error WasmIncrementalExecutor::removeModule(PartialTranslationUnit &PTU) 
{
   std::string BinaryFileName = PTU.TheModule->getName().str() + ".wasm";
 
-  llvm::errs() << "[DEBUG] Entering removeModule() for: " << BinaryFileName << 
"\n";
+  llvm::errs() << "[DEBUG] Entering removeModule() for: " << BinaryFileName
+   << "\n";
   llvm::errs() << "[DEBUG] Current Loaded Modules:\n";
   for (const auto &entry : LoadedModules) {
 llvm::errs() << "  -> " << entry.first << "\n";
@@ -151,8 +152,8 @@ llvm::Error 
WasmIncrementalExecutor::removeModule(PartialTranslationUnit &PTU) {
 
   if (dlclose(It->second) != 0) {
 llvm::errs() << "Failed to unload module: " << dlerror() << '\n';
-return llvm::make_error(
-"Failed to unload module", llvm::inconvertibleErrorCode());
+return llvm::make_error("Failed to unload module",
+   llvm::inconvertibleErrorCode());
   }
 
   // Remove the module from tracking

``




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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Matt Arsenault via cfe-commits


@@ -552,6 +553,11 @@ class DataLayout {
   ///
   /// This includes an explicitly requested alignment (if the global has one).
   Align getPreferredAlign(const GlobalVariable *GV) const;
+
+  /// Returns the sentinel pointer value for a given address space. If the
+  /// address space is invalid, it defaults to the sentinel pointer value of
+  /// address space 0, aligning with the behavior of \p getPointerSpec.
+  APInt getSentinelPointerValue(unsigned AS) const;

arsenm wrote:

If you aren't going to allow an arbitrary bit pattern for this, and only the 2 
special cases, I'd rather this just return an enum over those values than the 
heavier APInt 

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


[clang] [llvm] [DataLayout] Introduce sentinel pointer value (PR #131557)

2025-03-16 Thread Matt Arsenault via cfe-commits


@@ -3143,7 +3143,10 @@ as follows:
 specified, the default index size is equal to the pointer size. All sizes
 are in bits. The address space, ``n``, is optional, and if not specified,
 denotes the default address space 0. The value of ``n`` must be
-in the range [1,2^24).
+in the range [1,2^24). The fifth parameter  specifies the
+sentinel value of the pointer for the corresponding address space. It
+currently accepts two values: ``0`` for an all-zero value and ``f`` for a
+full-bit set value. The default sentinel pointer value is all-zero.

arsenm wrote:

"no sentinel pointer" should also be a valid option. We also should be able to 
specify the default for unlisted address spaces (I thought the old PR had that 
part implemented?)

I'm also not sure if we should just allow an arbitrary bit pattern here.

This also should define what the sentinel pointer means. Also clarify how this 
interacts with null_pointer_is_valid and the various flavors of nonnull 

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


[clang] [clang] Change placeholder from `undef` to `poison` (PR #131533)

2025-03-16 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic approved this pull request.

LGTM

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


[clang] [clang-repl] Address error recovery fixing infinite loop while parsing (PR #127569)

2025-03-16 Thread Anutosh Bhat via cfe-commits

anutosh491 wrote:

Hi @vgvassilev,

Would be nice to know your thoughts here

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


[clang] [Clang] Fix an incorrect assumption on getTemplatedDecl() (PR #131559)

2025-03-16 Thread Younan Zhang via cfe-commits

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

>From a3d01049bca20b9d44a07499b3204756edc8d0e1 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 17 Mar 2025 12:41:42 +0800
Subject: [PATCH 1/2] [Clang] Fix an incorrect assumption on getTemplatedDecl()

Since a68d20e98, we've been calling HandleDelayedAccessCheck() for concept
declarations when the declaration contains invalid member accesses.

However, a concept declaration is TemplateDecl such that doesn't contain any
TemplatedDecl.
---
 clang/lib/Sema/SemaAccess.cpp  |  4 ++--
 clang/test/SemaCXX/concept-crash-on-diagnostic.cpp | 12 
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaAccess.cpp b/clang/lib/Sema/SemaAccess.cpp
index f79d9a758e7af..6813786df3fc4 100644
--- a/clang/lib/Sema/SemaAccess.cpp
+++ b/clang/lib/Sema/SemaAccess.cpp
@@ -1518,8 +1518,8 @@ void Sema::HandleDelayedAccessCheck(DelayedDiagnostic 
&DD, Decl *D) {
   } else if (FunctionDecl *FN = dyn_cast(D)) {
 DC = FN;
   } else if (TemplateDecl *TD = dyn_cast(D)) {
-if (isa(TD->getTemplatedDecl()))
-  DC = cast(TD->getTemplatedDecl());
+if (auto *D = dyn_cast_if_present(TD->getTemplatedDecl()))
+  DC = D;
   } else if (auto *RD = dyn_cast(D)) {
 DC = RD;
   }
diff --git a/clang/test/SemaCXX/concept-crash-on-diagnostic.cpp 
b/clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
index 71e55c8290ee4..bd7b11a32e174 100644
--- a/clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
+++ b/clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
@@ -36,3 +36,15 @@ void function() {
 // expected-note@#4 {{candidate template ignored: constraints not satisfied 
[with IteratorL = Object *, IteratorR = Object *]}}
 // We don't know exactly the substituted type for `lhs == rhs`, thus a 
placeholder 'expr-type' is emitted.
 // expected-note@#3 {{because 'convertible_to' would be 
invalid}}
+
+namespace GH131530 {
+
+class foo {
+  struct bar {}; // expected-note {{implicitly declared private}}
+};
+
+template 
+concept is_foo_concept = __is_same(foo::bar, T);
+// expected-error@-1 {{'bar' is a private member of 'foo'}}
+
+}

>From d620cf503d49df3dc1075084e2665f6386a8913b Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 17 Mar 2025 12:55:47 +0800
Subject: [PATCH 2/2] Fix expected-error

---
 clang/test/SemaCXX/concept-crash-on-diagnostic.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/SemaCXX/concept-crash-on-diagnostic.cpp 
b/clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
index bd7b11a32e174..c38f075de 100644
--- a/clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
+++ b/clang/test/SemaCXX/concept-crash-on-diagnostic.cpp
@@ -45,6 +45,6 @@ class foo {
 
 template 
 concept is_foo_concept = __is_same(foo::bar, T);
-// expected-error@-1 {{'bar' is a private member of 'foo'}}
+// expected-error@-1 {{'bar' is a private member of 'GH131530::foo'}}
 
 }

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


[clang] [clang-tools-extra] [CudaSPIRV] Allow using integral non-type template parameters as attribute args (PR #131546)

2025-03-16 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 2dc123b33d51fcccb9e1af7230bc6573f77b3ccc 
86eefd7db18252d74f7b5891e7490653b6378eb0 --extensions cpp -- 
clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
clang/lib/CodeGen/CodeGenFunction.cpp clang/lib/CodeGen/Targets/AMDGPU.cpp 
clang/lib/CodeGen/Targets/TCE.cpp clang/lib/Sema/SemaDeclAttr.cpp 
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/Targets/AMDGPU.cpp 
b/clang/lib/CodeGen/Targets/AMDGPU.cpp
index 8f999ab113..e3c8243cbb 100644
--- a/clang/lib/CodeGen/Targets/AMDGPU.cpp
+++ b/clang/lib/CodeGen/Targets/AMDGPU.cpp
@@ -757,12 +757,8 @@ void CodeGenModule::handleAMDGPUFlatWorkGroupSizeAttr(
 return E->EvaluateKnownConstInt(getContext()).getExtValue();
   };
   if (FlatWGS) {
-Min = Eval(
-FlatWGS
-->getMin());
-Max = Eval(
-FlatWGS
-->getMax());
+Min = Eval(FlatWGS->getMin());
+Max = Eval(FlatWGS->getMax());
   }
   if (ReqdWGS && Min == 0 && Max == 0)
 Min = Max = Eval(ReqdWGS->getXDim()) * Eval(ReqdWGS->getYDim()) *

``




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


[clang] [Clang-repl] Implementation for removeModule for wasm use case (PR #131558)

2025-03-16 Thread Anutosh Bhat via cfe-commits

anutosh491 wrote:

Has some debug logs for now (shall be removed once ready)

Also the issue tracking this on emscripten is 
https://github.com/emscripten-core/emscripten/issues/23793

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


  1   2   >