[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -4027,12 +4031,10 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   // Reset possible inheritance
   Style.InheritsParentConfig = false;
 
-  auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
-
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
   auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   dropDiagnosticHandler);
+   DiagHandler);

owenca wrote:

```cpp
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
-  auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   DiagHandler);
+  auto EC =
+  parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
+ DiagHandler ? DiagHandler : 
dropDiagnosticHandler);
   // It was already correctly parsed.
   assert(!EC);
   static_cast(EC);
```

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -4027,12 +4031,10 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   // Reset possible inheritance
   Style.InheritsParentConfig = false;
 
-  auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
-

owenca wrote:

Sorry! We do need it.

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -1452,6 +1452,35 @@ TEST(ConfigParseTest, GetStyleOfSpecificFile) {
   ASSERT_EQ(*Style, getGoogleStyle());
 }
 
+TEST(ConfigParseTest, GetStyleOutput) {
+// With output
+::testing::internal::CaptureStderr();
+llvm::vfs::InMemoryFileSystem FS;
+auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
&FS, false);
+
+const std::string output = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style);
+ASSERT_FALSE(output.empty());
+llvm::consumeError(Style.takeError());

owenca wrote:

IMO we don't need this test.

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -1452,6 +1452,35 @@ TEST(ConfigParseTest, GetStyleOfSpecificFile) {
   ASSERT_EQ(*Style, getGoogleStyle());
 }
 
+TEST(ConfigParseTest, GetStyleOutput) {
+// With output
+::testing::internal::CaptureStderr();
+llvm::vfs::InMemoryFileSystem FS;
+auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
&FS, false);
+
+const std::string output = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style);
+ASSERT_FALSE(output.empty());
+llvm::consumeError(Style.takeError());
+
+// Without output
+::testing::internal::CaptureStderr();
+auto Style1 = getStyle("{invalid_key=invalid_value}",
+   "a.h",
+   "LLVM",
+   "",
+   &FS,
+   false,
+   [](const llvm::SMDiagnostic &, void *) {});
+
+const std::string output1 = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style1);
+ASSERT_TRUE(output1.empty());
+llvm::consumeError(Style1.takeError());

owenca wrote:

```suggestion
  // Suppress stderr.
  testing::internal::CaptureStderr();
  auto Style1 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS,
 /*AllowUnknownOptions=*/true,
 [](const llvm::SMDiagnostic &, void *) {});
  const auto output1 = testing::internal::GetCapturedStderr();
  ASSERT_TRUE((bool)Style1);
  ASSERT_TRUE(output1.empty());
```

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


[clang] [clang-format] add an option to insert a space only for non-code block empty braces, not for empty parentheses (PR #93634)

2024-06-14 Thread Kohei Asano via cfe-commits

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


[clang] [Clang][HIP] Suppress availability diagnostics for mismatched host/device overloads (PR #93546)

2024-06-14 Thread Fabian Ritter via cfe-commits

ritter-x2a wrote:

Ping @zygoloid, your input would be highly appreciated. Thanks!

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


[clang] [clang-format] add an option to insert a space only for non-code block empty braces, not for empty parentheses (PR #93634)

2024-06-14 Thread Kohei Asano via cfe-commits

https://github.com/khei4 updated https://github.com/llvm/llvm-project/pull/93634

>From 02b4de5799efe104f352d3f586e8779c5cd4 Mon Sep 17 00:00:00 2001
From: Kohei Asano 
Date: Mon, 3 Jun 2024 09:15:44 +0900
Subject: [PATCH] [clang-format] add an option to insert a space only for empty
 braces

---
 clang/docs/ClangFormatStyleOptions.rst  |  97 ++-
 clang/include/clang/Format/Format.h | 114 --
 clang/lib/Format/Format.cpp |  40 ++-
 clang/lib/Format/TokenAnnotator.cpp |  27 -
 clang/lib/Format/UnwrappedLineFormatter.cpp |  23 +++-
 clang/unittests/Format/ConfigParseTest.cpp  |   9 +-
 clang/unittests/Format/FormatTest.cpp   | 126 +++-
 7 files changed, 412 insertions(+), 24 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index bb00c20922d36..9879d122f8d57 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -6036,12 +6036,103 @@ the configuration (without a prefix: ``Auto``).
 
 **SpaceInEmptyBlock** (``Boolean``) :versionbadge:`clang-format 10` :ref:`¶ 
`
   If ``true``, spaces will be inserted into ``{}``.
+  This option is **deprecated**. The previous behavior is preserved by using
+  ``SpaceInEmptyBraces`` with ``Custom`` and by setting ``Block`` in
+  ``SpaceInEmptyBracesOptions`` to ``true``.
+
+.. _SpaceInEmptyBraces:
+
+**SpaceInEmptyBraces** (``SpaceInEmptyBracesStyle``) 
:versionbadge:`clang-format 19` :ref:`¶ `
+  Defines in which cases spaces will be inserted in empty braces.
+
+  Possible values:
+
+  * ``SIEBO_Never`` (in configuration: ``Never``)
+Never put a space in empty braces.
+
+.. code-block:: c++
+
+   void f() {}
+   T x{};
+   while (true) {}
+   struct U1 {};
+   union U2 {};
+   class U3 {};
+   enum U4 {};
+
+  * ``SIEBO_Custom`` (in configuration: ``Custom``)
+Configure each individual space in empty braces in
+`SpacesInEmptyBracesOptions`.
+
+
+
+.. _SpaceInEmptyBracesOptions:
+
+**SpaceInEmptyBracesOptions** (``SpaceInEmptyBracesCustom``) 
:versionbadge:`clang-format 19` :ref:`¶ `
+  Control of individual spaces in empty braces.
+
+  If ``SpaceInEmptyBraces`` is set to ``Custom``, use this to specify
+  how each individual space in empty braces case should be handled.
+  Otherwise, this is ignored.
+
+  .. code-block:: yaml
+
+# Example of usage:
+SpaceInEmptyBraces: Custom
+SpaceInEmptyBracesOptions:
+  Function: true
+  Record: false
+  InitList: true
+  Block: false
+
+  Nested configuration flags:
+
+  Precise control over the spacing in empty braces.
 
   .. code-block:: c++
 
- true:false:
- void f() { }   vs.   void f() {}
- while (true) { } while (true) {}
+# Should be declared this way:
+SpaceInEmptyBraces: Custom
+SpaceInEmptyBracesOptions:
+  Function: true
+  Record: false
+  InitList: true
+  Block: false
+
+  * ``bool Function`` Put a space in empty braces of function definition.
+
+.. code-block:: c++
+
+   true:  false:
+   void f() { }   vs. void f() {}
+
+  * ``bool Record`` Put a space in empty braces of record/struct definition.
+
+.. code-block:: c++
+
+   true:  false:
+   struct U1 { }; vs. struct U1 {};
+   union U2 { };  union U2 {};
+   class U3 { };  class U3 {};
+   enum U4 { };   enum U4 {};
+
+  * ``bool InitList`` Put a space in empty braces of initializer list.
+
+.. code-block:: c++
+
+   true:  false:
+   T x{ };vs. T x{};
+
+  * ``bool Block`` Put a space in empty braces of other blocks, including 
functions and
+record, compatible with ``SpaceInEmptyBlock``.
+
+.. code-block:: c++
+
+   true:  false:
+   void f() { }   vs. void f() {}
+   enum Unit { }; enum Unit {};
+   while (true) { }   while (true) {}
+
 
 .. _SpaceInEmptyParentheses:
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 4fd6e013df25b..661147a454694 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -4493,13 +4493,11 @@ struct FormatStyle {
   bool SpaceBeforeRangeBasedForLoopColon;
 
   /// If ``true``, spaces will be inserted into ``{}``.
-  /// \code
-  ///true:false:
-  ///void f() { }   vs.   void f() {}
-  ///while (true) { } while (true) {}
-  /// \endcode
+  /// This option is **deprecated**. The previous behavior is preserved by

[clang] [clang-format] add an option to insert a space only for non-code block empty braces, not for empty parentheses (PR #93634)

2024-06-14 Thread Kohei Asano via cfe-commits

khei4 wrote:

@owenca Thank you for the review! 

> @khei4 maybe an enum for SpaceInEmptyBraces with Always, Never, and Custom. 
> (IMO Leave doesn't make sense.)

I make those variants. How do you think the behavior of config, which has only 
`  SpaceInEmptyBraces.SpacesInParensOptions.InEmptyParentheses = true;` should 
be after this patch? I make `Never` default value now, so 
`SpacesInParensOptions.InEmptyParentheses` wouldn't insert a space into empty 
braces after this patch if it's without enabling `SpaceInEmptyBraces`

> I would implement all that make sense or are applicable to WebKit.

TBH, I'm not sure how much braces are classified on config, I will consult 
concretely, but `WebKit` style may be `SpaceInEmptyBraces: Always`. Can I leave 
them to you? Thank you! 

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


[clang] [clang-format] add an option to insert a space only for non-code block empty braces, not for empty parentheses (PR #93634)

2024-06-14 Thread Kohei Asano via cfe-commits

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


[clang] [llvm] [RISCV] Add scheduling model for Syntacore SCR3 (PR #95427)

2024-06-14 Thread Elena Lepilkina via cfe-commits

https://github.com/el-sc approved this pull request.


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


[clang] c947709 - [Driver] Support -Wa, --defsym similar to -Wa, -defsym

2024-06-14 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2024-06-14T00:30:03-07:00
New Revision: c947709df7859bb7285873593adab70349a5ab3e

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

LOG: [Driver] Support -Wa,--defsym similar to -Wa,-defsym

When the integrated assembler is enabled, clangDriver implements a small
set of popular -Wa, options. "-defsym" is implemented
(https://reviews.llvm.org/D26213), but the more common "--defsym" is
not. Support "--defsym".

Close #95386

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/defsym.s

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index b8d8ff3db5d1f..acd32bddea6b6 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -2647,7 +2647,7 @@ static void CollectArgsForIntegratedAssembler(Compilation 
&C,
   } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
  Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
 // Do nothing, we'll validate it later.
-  } else if (Value == "-defsym") {
+  } else if (Value == "-defsym" || Value == "--defsym") {
 if (A->getNumValues() != 2) {
   D.Diag(diag::err_drv_defsym_invalid_format) << Value;
   break;

diff  --git a/clang/test/Driver/defsym.s b/clang/test/Driver/defsym.s
index 165c71b2eae97..d152b326ae8b1 100644
--- a/clang/test/Driver/defsym.s
+++ b/clang/test/Driver/defsym.s
@@ -1,17 +1,14 @@
 // XFAIL: target={{.*}}-aix{{.*}}
 
 // RUN: %clang -### -c -integrated-as %s \
-// RUN: -Wa,-defsym,abc=5 -Wa,-defsym,xyz=0xa \
+// RUN: -Wa,-defsym,abc=5 -Wa,--defsym,xyz=0xa \
 // RUN: 2>&1 | FileCheck %s --check-prefix=CHECK-DEFSYM1
 
 // RUN: %clang -### -c -no-integrated-as -target x86_64-unknown-unknown %s \
-// RUN: -Wa,-defsym,abc=5 -Wa,-defsym,xyz=0xa \
+// RUN: -Wa,-defsym,abc=5 -Wa,--defsym,xyz=0xa \
 // RUN: 2>&1 | FileCheck %s --check-prefix=CHECK-DEFSYM1
 
-// CHECK-DEFSYM1: "-defsym"
-// CHECK-DEFSYM1: "abc=5"
-// CHECK-DEFSYM1: "-defsym"
-// CHECK-DEFSYM1: "xyz=0xa"
+// CHECK-DEFSYM1: "-defsym" "abc=5" "--defsym" "xyz=0xa"
 
 // RUN: not %clang -c -integrated-as -o /dev/null %s \
 // RUN: -Wa,-defsym,abc= \



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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits

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


[clang-tools-extra] [clang-tidy] avoid false positive when overload for bugprone-return-const-ref-from-parameter (PR #95434)

2024-06-14 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] [clang-tidy] avoid false positive when overload for bugprone-return-const-ref-from-parameter (PR #95434)

2024-06-14 Thread Piotr Zegar via cfe-commits

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

Few nits.

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


[clang-tools-extra] [clang-tidy] avoid false positive when overload for bugprone-return-const-ref-from-parameter (PR #95434)

2024-06-14 Thread Piotr Zegar via cfe-commits


@@ -18,20 +17,87 @@ namespace clang::tidy::bugprone {
 void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   returnStmt(
-  hasReturnValue(declRefExpr(to(parmVarDecl(hasType(hasCanonicalType(
-  qualType(matchers::isReferenceToConst()).bind("type"))),
-  hasAncestor(functionDecl(hasReturnTypeLoc(
-  loc(qualType(hasCanonicalType(equalsBoundNode("type"
+  hasReturnValue(declRefExpr(
+  to(parmVarDecl(hasType(hasCanonicalType(
+ qualType(lValueReferenceType(pointee(
+  qualType(isConstQualified()
+ .bind("type"
+ .bind("param",
+  hasAncestor(
+  functionDecl(hasReturnTypeLoc(loc(qualType(
+   hasCanonicalType(equalsBoundNode("type"))
+  .bind("func")))
   .bind("ret"),
   this);
 }
 
+static bool isSameTypeIgnoringConst(QualType A, QualType B) {
+  A = A.getCanonicalType();
+  B = B.getCanonicalType();
+  A.addConst();
+  B.addConst();
+  return A == B;
+}
+
+static bool isSameTypeIgnoringConstRef(QualType A, QualType B) {
+  return isSameTypeIgnoringConst(A.getCanonicalType().getNonReferenceType(),
+ B.getCanonicalType().getNonReferenceType());
+}
+
+static bool hasSameParameterTypes(const FunctionDecl &FD, const FunctionDecl 
&O,
+  const ParmVarDecl &PD) {
+  if (FD.getNumParams() != O.getNumParams())
+return false;
+  for (unsigned I = 0, E = FD.getNumParams(); I < E; ++I) {
+const ParmVarDecl *DPD = FD.getParamDecl(I);
+const QualType OPT = O.getParamDecl(I)->getType();
+if (DPD == &PD) {
+  if (!llvm::isa(OPT) ||
+  !isSameTypeIgnoringConstRef(DPD->getType(), OPT))
+return false;
+} else {
+  if (!isSameTypeIgnoringConst(DPD->getType(), OPT))
+return false;
+}
+  }
+  return true;
+}
+
+static const Decl *findRVRefOverload(const FunctionDecl &FD,
+ const ParmVarDecl &PD) {
+  // Actually it would be better to do lookup in caller site.
+  // But in most of cases, overloads of LVRef and RVRef will appear together.
+  // FIXME:
+  // 1. overload in anonymous namespace
+  // 2. forward reference
+  DeclContext::lookup_result LookupResult =
+  FD.getParent()->lookup(FD.getNameInfo().getName());
+  if (LookupResult.isSingleResult()) {
+return nullptr;
+  }
+  for (const Decl *Overload : LookupResult) {
+if (Overload == &FD)
+  continue;
+Overload->dumpColor();

PiotrZSL wrote:

debug ?

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


[clang-tools-extra] [clang-tidy] avoid false positive when overload for bugprone-return-const-ref-from-parameter (PR #95434)

2024-06-14 Thread Piotr Zegar via cfe-commits


@@ -18,20 +17,87 @@ namespace clang::tidy::bugprone {
 void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   returnStmt(
-  hasReturnValue(declRefExpr(to(parmVarDecl(hasType(hasCanonicalType(
-  qualType(matchers::isReferenceToConst()).bind("type"))),
-  hasAncestor(functionDecl(hasReturnTypeLoc(
-  loc(qualType(hasCanonicalType(equalsBoundNode("type"
+  hasReturnValue(declRefExpr(
+  to(parmVarDecl(hasType(hasCanonicalType(
+ qualType(lValueReferenceType(pointee(
+  qualType(isConstQualified()
+ .bind("type"
+ .bind("param",
+  hasAncestor(
+  functionDecl(hasReturnTypeLoc(loc(qualType(
+   hasCanonicalType(equalsBoundNode("type"))
+  .bind("func")))
   .bind("ret"),
   this);
 }
 
+static bool isSameTypeIgnoringConst(QualType A, QualType B) {
+  A = A.getCanonicalType();
+  B = B.getCanonicalType();
+  A.addConst();
+  B.addConst();
+  return A == B;

PiotrZSL wrote:

```suggestion
  return A.getCanonicalType().withConst() == B.getCanonicalType().withConst();
```

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


[clang] d712ae4 - [Driver] Support -Wa, --defsym similar to -Wa, -defsym

2024-06-14 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2024-06-14T00:40:33-07:00
New Revision: d712ae4a21822a51817941e7007e0dd41343cde3

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

LOG: [Driver] Support -Wa,--defsym similar to -Wa,-defsym

Missing part in c947709df7859bb7285873593adab70349a5ab3e

Added: 
clang/test/Misc/cc1as-defsym.s

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/defsym.s

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 880221176027e..062fbd2e4c0a4 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -8124,7 +8124,7 @@ def show_inst : Flag<["-"], "show-inst">,
 def dwarf_debug_producer : Separate<["-"], "dwarf-debug-producer">,
   HelpText<"The string to embed in the Dwarf debug AT_producer record.">;
 
-def defsym : Separate<["-"], "defsym">,
+def defsym : Separate<["--"], "defsym">,
   HelpText<"Define a value for a symbol">;
 
 } // let Visibility = [CC1AsOption]

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index acd32bddea6b6..331cf6e713d89 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -2666,7 +2666,7 @@ static void CollectArgsForIntegratedAssembler(Compilation 
&C,
   D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
   break;
 }
-CmdArgs.push_back(Value.data());
+CmdArgs.push_back("--defsym");
 TakeNextArg = true;
   } else if (Value == "-fdebug-compilation-dir") {
 CmdArgs.push_back("-fdebug-compilation-dir");

diff  --git a/clang/test/Driver/defsym.s b/clang/test/Driver/defsym.s
index d152b326ae8b1..af66656cce15e 100644
--- a/clang/test/Driver/defsym.s
+++ b/clang/test/Driver/defsym.s
@@ -6,9 +6,10 @@
 
 // RUN: %clang -### -c -no-integrated-as -target x86_64-unknown-unknown %s \
 // RUN: -Wa,-defsym,abc=5 -Wa,--defsym,xyz=0xa \
-// RUN: 2>&1 | FileCheck %s --check-prefix=CHECK-DEFSYM1
+// RUN: 2>&1 | FileCheck %s --check-prefix=CHECK-DEFSYM1-GAS
 
-// CHECK-DEFSYM1: "-defsym" "abc=5" "--defsym" "xyz=0xa"
+// CHECK-DEFSYM1: "--defsym" "abc=5" "--defsym" "xyz=0xa"
+// CHECK-DEFSYM1-GAS: "-defsym" "abc=5" "--defsym" "xyz=0xa"
 
 // RUN: not %clang -c -integrated-as -o /dev/null %s \
 // RUN: -Wa,-defsym,abc= \

diff  --git a/clang/test/Misc/cc1as-defsym.s b/clang/test/Misc/cc1as-defsym.s
new file mode 100644
index 0..0dc7f24dac2c0
--- /dev/null
+++ b/clang/test/Misc/cc1as-defsym.s
@@ -0,0 +1,12 @@
+// REQUIRES: x86-registered-target
+// RUN: %clang -cc1as -triple x86_64 -filetype obj --defsym A=1 %s -o %t.o
+// RUN: llvm-nm %t.o | FileCheck %s
+
+// CHECK: 0001 A foo
+
+.globl foo
+.ifdef A
+foo = 1
+.else
+foo = 0
+.endif



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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -1452,6 +1452,35 @@ TEST(ConfigParseTest, GetStyleOfSpecificFile) {
   ASSERT_EQ(*Style, getGoogleStyle());
 }
 
+TEST(ConfigParseTest, GetStyleOutput) {
+// With output
+::testing::internal::CaptureStderr();
+llvm::vfs::InMemoryFileSystem FS;
+auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
&FS, false);
+
+const std::string output = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style);
+ASSERT_FALSE(output.empty());
+llvm::consumeError(Style.takeError());

owenca wrote:

```suggestion
  llvm::vfs::InMemoryFileSystem FS;

  // Don't suppress output.
  testing::internal::CaptureStderr();
  auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS,
/*AllowUnknownOptions=*/true);
  const auto output = testing::internal::GetCapturedStderr();
  ASSERT_TRUE((bool)Style);
  ASSERT_FALSE(output.empty());
```

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


[clang] [llvm] [llvm][AArch64] Support -mcpu=apple-m4 (PR #95478)

2024-06-14 Thread Martin Storsjö via cfe-commits


@@ -1010,6 +1034,9 @@ def : ProcessorModel<"apple-a16", CycloneModel, 
ProcessorFeatures.AppleA16,
  [TuneAppleA16]>;
 def : ProcessorModel<"apple-a17", CycloneModel, ProcessorFeatures.AppleA17,
  [TuneAppleA17]>;
+def : ProcessorModel<"apple-m4", CycloneModel, ProcessorFeatures.AppleM4,

mstorsjo wrote:

Shouldn't this go below, under `// Mac CPUs`?

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


[clang] [clang-tools-extra] [Clang] Implement CWG2813: Class member access with prvalues (PR #95112)

2024-06-14 Thread Mital Ashok via cfe-commits


@@ -1140,26 +1131,68 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType 
BaseExprType,
 BaseExpr = BuildCXXThisExpr(Loc, BaseExprType, /*IsImplicit=*/true);
   }
 
+  // C++17 [expr.ref]p2, per CWG2813:
+  //   For the first option (dot), if the id-expression names a static member 
or
+  //   an enumerator, the first expression is a discarded-value expression; if
+  //   the id-expression names a non-static data member, the first expression
+  //   shall be a glvalue.
+  auto MakeDiscardedValue = [&BaseExpr, IsArrow, this] {
+assert(getLangOpts().CPlusPlus &&
+   "Static member / member enumerator outside of C++");
+if (IsArrow)
+  return false;
+ExprResult Converted = IgnoredValueConversions(BaseExpr);
+if (Converted.isInvalid())
+  return true;
+BaseExpr = Converted.get();
+DiagnoseUnusedExprResult(BaseExpr,
+ diag::warn_discarded_class_member_access);
+return false;
+  };
+  auto MakeGLValue = [&BaseExpr, IsArrow, this] {
+if (IsArrow || !BaseExpr->isPRValue())
+  return false;
+ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
+if (Converted.isInvalid())
+  return true;
+BaseExpr = Converted.get();
+return false;
+  };
+
   // Check the use of this member.
   if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
 return ExprError();
 
-  if (FieldDecl *FD = dyn_cast(MemberDecl))
+  if (FieldDecl *FD = dyn_cast(MemberDecl)) {
+if (MakeGLValue())
+  return ExprError();
 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
MemberNameInfo);
+  }
 
-  if (MSPropertyDecl *PD = dyn_cast(MemberDecl))
+  if (MSPropertyDecl *PD = dyn_cast(MemberDecl)) {
+// Properties treated as non-static data members for the purpose of
+// temporary materialization
+if (MakeGLValue())

MitalAshok wrote:

(Tested locally on v19.41.33923) MSVC does not seem to implement CWG2813 so 
this:

```c++
struct S {
S(const S&) = delete;
S() = default;
int getX(this S) { return 42; }
__declspec(property(get = getX))
int x;
};

int main() {
return S().x;
}
```

... doesn't compile (attempts to call `S::S(const S&)` on the temporary to 
construct the explicit object argument).

I assume MSVC will eventually allow this, so we should wait to materialize the 
temporary here? Especially since 
https://learn.microsoft.com/en-gb/cpp/cpp/property-cpp?view=msvc-170 describes 
properties directly as a transformation from data member access -> member 
function call. I'll get this changed

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


[clang] [clang-tools-extra] [Clang] Implement CWG2813: Class member access with prvalues (PR #95112)

2024-06-14 Thread Mital Ashok via cfe-commits


@@ -1174,6 +1207,9 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType 
BaseExprType,
   valueKind = VK_PRValue;
   type = Context.BoundMemberTy;

MitalAshok wrote:

For non-static member function, we don't require a glvalue anymore (to allow 
by-value explicit objects to bind to prvalues)

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


[clang] [clang-tools-extra] [Clang] Implement CWG2813: Class member access with prvalues (PR #95112)

2024-06-14 Thread Mital Ashok via cfe-commits


@@ -387,9 +388,16 @@ void Sema::DiagnoseUnusedExprResult(const Stmt *S, 
unsigned DiagID) {
   // Do not diagnose use of a comma operator in a SFINAE context because the
   // type of the left operand could be used for SFINAE, so technically it is
   // *used*.
-  if (DiagID != diag::warn_unused_comma_left_operand || !isSFINAEContext())
-DiagIfReachable(Loc, S ? llvm::ArrayRef(S) : std::nullopt,
-PDiag(DiagID) << R1 << R2);
+  if (DiagID == diag::warn_unused_comma_left_operand && isSFINAEContext())
+return;
+
+  // Don't diagnose discarded left of dot in static class member access
+  // because its type is "used" to determine the class to access
+  if (OrigDiagID == diag::warn_discarded_class_member_access)
+return;

MitalAshok wrote:

This code path is called for all static member accesses, not just on prvalues.

The problem is in stuff like `discarded.static_member_fn();`. This function is 
called for `(discarded, E2)` and `discarded;` (expression-statement), where 
those were previously the only two discarded-value expressions. These had an 
easy fix of casting to `void`, but that doesn't work for this new 
discarded-value. https://godbolt.org/z/9b949rvxc

I think that this warning shouldn't be applied when the thing that is discarded 
is/was dependently typed. Maybe for `s.x()` if we have a declaration `S s;` we 
can suggest `S::x()`, but that shouldn't be on by default. Or `S().x()` into 
`S::x()` if that constructor call has no side-effects. Maybe that is more 
appropriate for clang-tidy than the compiler though?

For now this PR doesn't introduce any new diagnostics, just existing warnings 
about [[nodiscard]] values being discarded in new positions. I think I'll just 
split some of `Sema::DiagnoseUnusedExprResult` into 
`Sema::DiagnoseDiscardedValue` for specifically checking [[nodiscard]] stuff 
and call that instead without a new diagnostic

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


[clang] [llvm] [llvm][AArch64] Support -mcpu=apple-m4 (PR #95478)

2024-06-14 Thread Thorsten Schütt via cfe-commits

tschuett wrote:

It is a problem that is worth fixing long term. How to correctly model release 
versions and their optional dependencies. Furthermore, for the BTI example how 
remove features.

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


[clang] [clang-tools-extra] [Clang] Implement CWG2813: Class member access with prvalues (PR #95112)

2024-06-14 Thread via cfe-commits


@@ -1174,6 +1207,9 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType 
BaseExprType,
   valueKind = VK_PRValue;
   type = Context.BoundMemberTy;

Sirraide wrote:

Oh yeah, duh, makes sense.

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


[clang] [clang-tools-extra] [Clang] Implement CWG2813: Class member access with prvalues (PR #95112)

2024-06-14 Thread via cfe-commits


@@ -387,9 +388,16 @@ void Sema::DiagnoseUnusedExprResult(const Stmt *S, 
unsigned DiagID) {
   // Do not diagnose use of a comma operator in a SFINAE context because the
   // type of the left operand could be used for SFINAE, so technically it is
   // *used*.
-  if (DiagID != diag::warn_unused_comma_left_operand || !isSFINAEContext())
-DiagIfReachable(Loc, S ? llvm::ArrayRef(S) : std::nullopt,
-PDiag(DiagID) << R1 << R2);
+  if (DiagID == diag::warn_unused_comma_left_operand && isSFINAEContext())
+return;
+
+  // Don't diagnose discarded left of dot in static class member access
+  // because its type is "used" to determine the class to access
+  if (OrigDiagID == diag::warn_discarded_class_member_access)
+return;

Sirraide wrote:

> I think that this warning shouldn't be applied when the thing that is 
> discarded is/was dependently typed.

Yeah, I think that makes sense.

> existing warnings about `[[nodiscard]]` values being discarded in new 
> positions.

That’s what I would expect, so that also makes sense.

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


[clang] [clang-tools-extra] [Clang] Implement CWG2813: Class member access with prvalues (PR #95112)

2024-06-14 Thread via cfe-commits


@@ -1140,26 +1131,68 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType 
BaseExprType,
 BaseExpr = BuildCXXThisExpr(Loc, BaseExprType, /*IsImplicit=*/true);
   }
 
+  // C++17 [expr.ref]p2, per CWG2813:
+  //   For the first option (dot), if the id-expression names a static member 
or
+  //   an enumerator, the first expression is a discarded-value expression; if
+  //   the id-expression names a non-static data member, the first expression
+  //   shall be a glvalue.
+  auto MakeDiscardedValue = [&BaseExpr, IsArrow, this] {
+assert(getLangOpts().CPlusPlus &&
+   "Static member / member enumerator outside of C++");
+if (IsArrow)
+  return false;
+ExprResult Converted = IgnoredValueConversions(BaseExpr);
+if (Converted.isInvalid())
+  return true;
+BaseExpr = Converted.get();
+DiagnoseUnusedExprResult(BaseExpr,
+ diag::warn_discarded_class_member_access);
+return false;
+  };
+  auto MakeGLValue = [&BaseExpr, IsArrow, this] {
+if (IsArrow || !BaseExpr->isPRValue())
+  return false;
+ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
+if (Converted.isInvalid())
+  return true;
+BaseExpr = Converted.get();
+return false;
+  };
+
   // Check the use of this member.
   if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
 return ExprError();
 
-  if (FieldDecl *FD = dyn_cast(MemberDecl))
+  if (FieldDecl *FD = dyn_cast(MemberDecl)) {
+if (MakeGLValue())
+  return ExprError();
 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
MemberNameInfo);
+  }
 
-  if (MSPropertyDecl *PD = dyn_cast(MemberDecl))
+  if (MSPropertyDecl *PD = dyn_cast(MemberDecl)) {
+// Properties treated as non-static data members for the purpose of
+// temporary materialization
+if (MakeGLValue())

Sirraide wrote:

Yeah, I think this is a case where, even though MSVC doesn’t allow this at the 
moment, I personally think that it would be in accordance with the intent 
behind this DR to allow this here (though, of course, it is a compiler 
extension, so the MSVC people can decide to do whatever they want to here). 

>From what I can tell, it also isn’t a breaking change: it’s just that some 
>code that previously wouldn’t compile now does, but please correct me if I’m 
>wrong about this.

Also, I’d maybe mention in a comment that we’re intentionally diverging from 
MSVC’s behaviour here and why.

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


[clang] da249ca - [clang-cl] Map /Ot to -O3 instead of -O2 (#95406)

2024-06-14 Thread via cfe-commits

Author: Hans
Date: 2024-06-14T10:23:33+02:00
New Revision: da249cad8d398939e0c608d38d0c038954941316

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

LOG: [clang-cl] Map /Ot to -O3 instead of -O2 (#95406)

/Ot (which is also implied by /O2) is supposed to optimize for maximum
speed, so -O3 seems like a better match.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/docs/UsersManual.rst
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/MSVC.cpp
clang/test/Driver/cl-options.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8c2f737836a9d..68355dbb5861b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -921,6 +921,10 @@ Android Support
 Windows Support
 ^^^
 
+- The clang-cl ``/Ot`` compiler option ("optimize for speed", also implied by
+  ``/O2``) now maps to clang's ``-O3`` optimizataztion level instead of 
``-O2``.
+  Users who prefer the old behavior can use ``clang-cl /Ot /clang:-O2 ...``.
+
 - Clang-cl now supports function targets with intrinsic headers. This allows
   for runtime feature detection of intrinsics. Previously under clang-cl
   ``immintrin.h`` and similar intrinsic headers would only include the 
intrinsics

diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index f954857b0235a..ee30e4eff9ea0 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -4636,8 +4636,8 @@ Execute ``clang-cl /?`` to see a list of supported 
options:
   /Og No effect
   /Oi-Disable use of builtin functions
   /Oi Enable use of builtin functions
-  /Os Optimize for size
-  /Ot Optimize for speed
+  /Os Optimize for size (like clang -Os)
+  /Ot Optimize for speed (like clang -O3)
   /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use 
/O2 instead
   /Oy-Disable frame pointer omission (x86 only, 
default)
   /Oy Enable frame pointer omission (x86 only)

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 062fbd2e4c0a4..d523e8c611f0f 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -8279,9 +8279,9 @@ def : CLFlag<"Oi">, Alias<_SLASH_O>, AliasArgs<["i"]>,
 def : CLFlag<"Oi-">, Alias<_SLASH_O>, AliasArgs<["i-"]>,
   HelpText<"Disable use of builtin functions">;
 def : CLFlag<"Os">, Alias<_SLASH_O>, AliasArgs<["s"]>,
-  HelpText<"Optimize for size">;
+  HelpText<"Optimize for size (like clang -Os)">;
 def : CLFlag<"Ot">, Alias<_SLASH_O>, AliasArgs<["t"]>,
-  HelpText<"Optimize for speed">;
+  HelpText<"Optimize for speed (like clang -O3)">;
 def : CLFlag<"Ox">, Alias<_SLASH_O>, AliasArgs<["x"]>,
   HelpText<"Deprecated (like /Og /Oi /Ot /Oy /Ob2); use /O2">;
 def : CLFlag<"Oy">, Alias<_SLASH_O>, AliasArgs<["y"]>,

diff  --git a/clang/lib/Driver/ToolChains/MSVC.cpp 
b/clang/lib/Driver/ToolChains/MSVC.cpp
index b7021d4b996dd..d03687208c5c6 100644
--- a/clang/lib/Driver/ToolChains/MSVC.cpp
+++ b/clang/lib/Driver/ToolChains/MSVC.cpp
@@ -861,7 +861,7 @@ static void TranslateOptArg(Arg *A, 
llvm::opt::DerivedArgList &DAL,
   DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
 } else if (OptChar == '2' || OptChar == 'x') {
   DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
-  DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
+  DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "3");
 }
 if (SupportsForcingFramePointer &&
 !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
@@ -901,7 +901,7 @@ static void TranslateOptArg(Arg *A, 
llvm::opt::DerivedArgList &DAL,
   DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
   break;
 case 't':
-  DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
+  DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "3");
   break;
 case 'y': {
   bool OmitFramePointer = true;

diff  --git a/clang/test/Driver/cl-options.c b/clang/test/Driver/cl-options.c
index 2c17459dde656..e77ec364170d1 100644
--- a/clang/test/Driver/cl-options.c
+++ b/clang/test/Driver/cl-options.c
@@ -189,12 +189,12 @@
 // RUN: %clang_cl /Ot --target=i686-pc-windows-msvc -### -- %s 2>&1 | 
FileCheck -check-prefix=Ot %s
 // RUN: %clang_cl /Ot --target=x86_64-pc-windows-msvc -### -- %s 2>&1 | 
FileCheck -check-prefix=Ot %s
 // Ot: -mframe-pointer=none
-// Ot: -O2
+// Ot: -O3
 
 // RUN: %clang_cl /Ox --target=i686-pc-windows-msvc -### -- %s 2>&1 | 
FileCheck -check-prefix=Ox %

[clang] [clang-cl] Map /Ot to -O3 instead of -O2 (PR #95406)

2024-06-14 Thread via cfe-commits

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


[clang] 880d370 - [APFloat] Add APFloat support for FP4 data type (#95392)

2024-06-14 Thread via cfe-commits

Author: Durgadoss R
Date: 2024-06-14T14:17:37+05:30
New Revision: 880d37038c7bbff53ef02c9d6b01cbbc87875243

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

LOG: [APFloat] Add APFloat support for FP4 data type (#95392)

This patch adds APFloat type support for the E2M1
FP4 datatype. The definitions for this format are
detailed in section 5.3.3 of the OCP specification,
which can be accessed here:

https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf

Signed-off-by: Durgadoss R 

Added: 


Modified: 
clang/lib/AST/MicrosoftMangle.cpp
llvm/include/llvm/ADT/APFloat.h
llvm/lib/Support/APFloat.cpp
llvm/unittests/ADT/APFloatTest.cpp

Removed: 




diff  --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index ffc5d2d4cd8fc..a863ec7a529b9 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -901,6 +901,7 @@ void MicrosoftCXXNameMangler::mangleFloat(llvm::APFloat 
Number) {
   case APFloat::S_FloatTF32:
   case APFloat::S_Float6E3M2FN:
   case APFloat::S_Float6E2M3FN:
+  case APFloat::S_Float4E2M1FN:
 llvm_unreachable("Tried to mangle unexpected APFloat semantics");
   }
 

diff  --git a/llvm/include/llvm/ADT/APFloat.h b/llvm/include/llvm/ADT/APFloat.h
index a9bb6ccb1..c24eae8da3797 100644
--- a/llvm/include/llvm/ADT/APFloat.h
+++ b/llvm/include/llvm/ADT/APFloat.h
@@ -197,6 +197,10 @@ struct APFloatBase {
 // types, there are no infinity or NaN values. The format is detailed in
 // 
https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
 S_Float6E2M3FN,
+// 4-bit floating point number with bit layout S1E2M1. Unlike IEEE-754
+// types, there are no infinity or NaN values. The format is detailed in
+// 
https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
+S_Float4E2M1FN,
 
 S_x87DoubleExtended,
 S_MaxSemantics = S_x87DoubleExtended,
@@ -219,6 +223,7 @@ struct APFloatBase {
   static const fltSemantics &FloatTF32() LLVM_READNONE;
   static const fltSemantics &Float6E3M2FN() LLVM_READNONE;
   static const fltSemantics &Float6E2M3FN() LLVM_READNONE;
+  static const fltSemantics &Float4E2M1FN() LLVM_READNONE;
   static const fltSemantics &x87DoubleExtended() LLVM_READNONE;
 
   /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
@@ -639,6 +644,7 @@ class IEEEFloat final : public APFloatBase {
   APInt convertFloatTF32APFloatToAPInt() const;
   APInt convertFloat6E3M2FNAPFloatToAPInt() const;
   APInt convertFloat6E2M3FNAPFloatToAPInt() const;
+  APInt convertFloat4E2M1FNAPFloatToAPInt() const;
   void initFromAPInt(const fltSemantics *Sem, const APInt &api);
   template  void initFromIEEEAPInt(const APInt &api);
   void initFromHalfAPInt(const APInt &api);
@@ -656,6 +662,7 @@ class IEEEFloat final : public APFloatBase {
   void initFromFloatTF32APInt(const APInt &api);
   void initFromFloat6E3M2FNAPInt(const APInt &api);
   void initFromFloat6E2M3FNAPInt(const APInt &api);
+  void initFromFloat4E2M1FNAPInt(const APInt &api);
 
   void assign(const IEEEFloat &);
   void copySignificand(const IEEEFloat &);
@@ -1067,6 +1074,7 @@ class APFloat : public APFloatBase {
 // Below Semantics do not support {NaN or Inf}
 case APFloat::S_Float6E3M2FN:
 case APFloat::S_Float6E2M3FN:
+case APFloat::S_Float4E2M1FN:
   return false;
 }
   }

diff  --git a/llvm/lib/Support/APFloat.cpp b/llvm/lib/Support/APFloat.cpp
index 1209bf71a287d..47618bc325951 100644
--- a/llvm/lib/Support/APFloat.cpp
+++ b/llvm/lib/Support/APFloat.cpp
@@ -69,8 +69,8 @@ enum class fltNonfiniteBehavior {
   // encodings do not distinguish between signalling and quiet NaN.
   NanOnly,
 
-  // This behavior is present in Float6E3M2FN and Float6E2M3FN types,
-  // which do not support Inf or NaN values.
+  // This behavior is present in Float6E3M2FN, Float6E2M3FN, and
+  // Float4E2M1FN types, which do not support Inf or NaN values.
   FiniteOnly,
 };
 
@@ -147,6 +147,8 @@ static constexpr fltSemantics semFloat6E3M2FN = {
 4, -2, 3, 6, fltNonfiniteBehavior::FiniteOnly};
 static constexpr fltSemantics semFloat6E2M3FN = {
 2, 0, 4, 6, fltNonfiniteBehavior::FiniteOnly};
+static constexpr fltSemantics semFloat4E2M1FN = {
+2, 0, 2, 4, fltNonfiniteBehavior::FiniteOnly};
 static constexpr fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
 static constexpr fltSemantics semBogus = {0, 0, 0, 0};
 
@@ -218,6 +220,8 @@ const llvm::fltSemantics 
&APFloatBase::EnumToSemantics(Semantics S) {
 return Float6E3M2FN();
   case S_Float6E2M3FN:
 return Float6E2M3FN();
+  case S_Float4E2M1FN:
+return Float4E2M1FN();
   case S_x87DoubleExtended:
 return x87Dou

[clang] [llvm] [APFloat] Add APFloat support for FP4 data type (PR #95392)

2024-06-14 Thread Durgadoss R via cfe-commits

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-06-14 Thread via cfe-commits

zmodem wrote:

This broke the lit tests on mac: 
https://green.lab.llvm.org/job/llvm.org/job/clang-stage1-RA/1096/

I'll revert to green for now.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,370 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+
+#include "Compiler.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+#include "clang/Serialization/ASTReader.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+// Create a path to store module files. Generally it should be:
+//
+//   {TEMP_DIRS}/clangd/module_files/{PrefixDir}-%%-%%-%%-%%-%%-%%/.
+//
+// {TEMP_DIRS} is the temporary directory for the system, e.g., "/var/tmp"
+// or "C:/TEMP".
+//
+// '%%' means random value to make the generated path unique.
+//
+// \param MainFile is used to get the root of the project from global
+// compilation database. \param PrefixDir is used to get the user
+// defined prefix for module files. This is useful when we want to seperate
+// module files. e.g., we want to build module files for the same module unit
+// `a.cppm` with 2 different users `b.cpp` and `c.cpp` and we don't want the
+// module file for `b.cpp` be conflict with the module files for `c.cpp`. Then
+// we can put the 2 module files into different dirs like:
+//
+//   ${TEMP_DIRS}/clangd/module_files/b.cpp/a.pcm
+//   ${TEMP_DIRS}/clangd/module_files/c.cpp/a.pcm
+//
+// TODO: Move these module fils out of the temporary directory if the module
+// files are persistent.
+llvm::SmallString<256> getUniqueModuleFilesPath(PathRef MainFile,
+llvm::StringRef PrefixDir) {
+  llvm::SmallString<256> ResultPattern;
+
+  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/true,
+ ResultPattern);
+
+  llvm::sys::path::append(ResultPattern, "clangd");
+  llvm::sys::path::append(ResultPattern, "module_files");
+
+  llvm::sys::path::append(ResultPattern, PrefixDir);
+
+  ResultPattern.append("-%%-%%-%%-%%-%%-%%");
+
+  llvm::SmallString<256> Result;
+  llvm::sys::fs::createUniquePath(ResultPattern, Result,
+  /*MakeAbsolute=*/false);
+
+  llvm::sys::fs::create_directories(Result);
+  return Result;
+}
+
+// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getModuleFilePath(llvm::StringRef ModuleName,
+  PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePattern(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePattern, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePattern.append("-");
+ModuleFilePattern.append(PartitionName);
+  }
+
+  ModuleFilePattern.append(".pcm");
+
+  llvm::SmallString<256> ModuleFilePath;
+  llvm::sys::fs::createUniquePath(ModuleFilePattern, ModuleFilePath,
+  /*MakeAbsolute=*/false);
+
+  return std::string(ModuleFilePath);
+}
+} // namespace
+
+// FailedPrerequisiteModules - stands for the PrerequisiteModules which has
+// errors happened during the building process.
+class FailedPrerequisiteModules : public PrerequisiteModules {
+public:
+  ~FailedPrerequisiteModules() override = default;
+
+  // We shouldn't adjust the compilation commands based on
+  // FailedPrerequisiteModules.
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+  }
+
+  // FailedPrerequisiteModules can never be reused.
+  bool
+  canReuse(const CompilerInvocation &CI,
+   llvm::IntrusiveRefCntPtr) const override {
+return false;
+  }
+
+  // No module unit got built in FailedPrerequisiteModules.
+  bool isModuleUnitBuilt(llvm::StringRef ModuleName) const override {
+return false;
+  }
+};
+
+// StandalonePrerequisiteModules - stands for PrerequisiteModules for which all
+// the required modules are built successfully. All the module files
+// are owned by the StandalonePrerequisiteModules class.
+//
+// Any of the built module files won't be shared with other instances of the
+// class. So that we can avoid worrying thread safety.
+//
+// We don't need to worry about duplicated module names here since the standard
+// guarantees the module names should be unique to a pr

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -112,6 +114,9 @@ class ClangdServer {
 /// This throttler controls which preambles may be built at a given time.
 clangd::PreambleThrottler *PreambleThrottler = nullptr;
 
+/// Enable experimental support for modules.

ChuanqiXu9 wrote:

I add ModulesManager to `ClangdServer::Options` and removed this flag. But I 
still need a variable to pass the information from the command line. I add that 
to `ClangdLSPServer::Options`. Otherwise we have to refactor the command line 
system of clangd a little bit. They are all local to `ClangdMain.cpp` now. If 
we really want that, I suggest we should do that in a separat patch.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,347 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+
+#include "Compiler.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+#include "clang/Serialization/ASTReader.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+// Create a path to store module files. Generally it should be:
+//
+//   {TEMP_DIRS}/clangd/module_files/{hashed-file-name}-%%-%%-%%-%%-%%-%%/.
+//
+// {TEMP_DIRS} is the temporary directory for the system, e.g., "/var/tmp"
+// or "C:/TEMP".
+//
+// '%%' means random value to make the generated path unique.
+//
+// \param MainFile is used to get the root of the project from global
+// compilation database.
+//
+// TODO: Move these module fils out of the temporary directory if the module
+// files are persistent.
+llvm::SmallString<256> getUniqueModuleFilesPath(PathRef MainFile) {
+  llvm::SmallString<128> HashedPrefix = llvm::sys::path::filename(MainFile);
+  // There might be multiple files with the same name in a project. So 
appending
+  // the hash value of the full path to make sure they won't conflict.
+  HashedPrefix += std::to_string(llvm::hash_value(MainFile));
+
+  llvm::SmallString<256> ResultPattern;
+
+  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/true,
+ ResultPattern);
+
+  llvm::sys::path::append(ResultPattern, "clangd");
+  llvm::sys::path::append(ResultPattern, "module_files");
+
+  llvm::sys::path::append(ResultPattern, HashedPrefix);
+
+  ResultPattern.append("-%%-%%-%%-%%-%%-%%");
+
+  llvm::SmallString<256> Result;
+  llvm::sys::fs::createUniquePath(ResultPattern, Result,
+  /*MakeAbsolute=*/false);
+
+  llvm::sys::fs::create_directories(Result);
+  return Result;
+}
+
+// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getModuleFilePath(llvm::StringRef ModuleName,
+  PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePath(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePath, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePath.append("-");
+ModuleFilePath.append(PartitionName);
+  }
+
+  ModuleFilePath.append(".pcm");
+  return std::string(ModuleFilePath);
+}
+
+// FailedPrerequisiteModules - stands for the PrerequisiteModules which has
+// errors happened during the building process.
+class FailedPrerequisiteModules : public PrerequisiteModules {
+public:
+  ~FailedPrerequisiteModules() override = default;
+
+  // We shouldn't adjust the compilation commands based on
+  // FailedPrerequisiteModules.
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+  }
+
+  // FailedPrerequisiteModules can never be reused.
+  bool
+  canReuse(const CompilerInvocation &CI,
+   llvm::IntrusiveRefCntPtr) const override {
+return false;
+  }
+};
+
+// StandalonePrerequisiteModules - stands for PrerequisiteModules for which all
+// the required modules are built successfully. All the module files
+// are owned by the StandalonePrerequisiteModules class.
+//
+// Any of the built module files won't be shared with other instances of the
+// class. So that we can avoid worrying thread safety.
+//
+// We don't need to worry about duplicated module names here since the standard
+// guarantees the module names should be unique to a program.
+class StandalonePrerequisiteModules : public PrerequisiteModules {
+public:
+  StandalonePrerequisiteModules() = default;
+
+  StandalonePrerequisiteModules(const StandalonePrerequisiteModules &) = 
delete;
+  StandalonePrerequisiteModules
+  operator=(const StandalonePrerequisiteModules &) = delete;
+  StandalonePrerequisiteModules(StandalonePrerequisiteModules &&) = delete;
+  StandalonePrerequisiteModules
+  operator=(StandalonePrerequisiteModules &&) = delete;
+
+  ~StandalonePrerequisiteModules() override = default;
+
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+// Appending all built module f

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,347 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+
+#include "Compiler.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+#include "clang/Serialization/ASTReader.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+// Create a path to store module files. Generally it should be:
+//
+//   {TEMP_DIRS}/clangd/module_files/{hashed-file-name}-%%-%%-%%-%%-%%-%%/.
+//
+// {TEMP_DIRS} is the temporary directory for the system, e.g., "/var/tmp"
+// or "C:/TEMP".
+//
+// '%%' means random value to make the generated path unique.
+//
+// \param MainFile is used to get the root of the project from global
+// compilation database.
+//
+// TODO: Move these module fils out of the temporary directory if the module
+// files are persistent.
+llvm::SmallString<256> getUniqueModuleFilesPath(PathRef MainFile) {
+  llvm::SmallString<128> HashedPrefix = llvm::sys::path::filename(MainFile);
+  // There might be multiple files with the same name in a project. So 
appending
+  // the hash value of the full path to make sure they won't conflict.
+  HashedPrefix += std::to_string(llvm::hash_value(MainFile));
+
+  llvm::SmallString<256> ResultPattern;
+
+  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/true,
+ ResultPattern);
+
+  llvm::sys::path::append(ResultPattern, "clangd");
+  llvm::sys::path::append(ResultPattern, "module_files");
+
+  llvm::sys::path::append(ResultPattern, HashedPrefix);
+
+  ResultPattern.append("-%%-%%-%%-%%-%%-%%");
+
+  llvm::SmallString<256> Result;
+  llvm::sys::fs::createUniquePath(ResultPattern, Result,
+  /*MakeAbsolute=*/false);
+
+  llvm::sys::fs::create_directories(Result);
+  return Result;
+}
+
+// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,370 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+
+#include "Compiler.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+#include "clang/Serialization/ASTReader.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+// Create a path to store module files. Generally it should be:
+//
+//   {TEMP_DIRS}/clangd/module_files/{PrefixDir}-%%-%%-%%-%%-%%-%%/.
+//
+// {TEMP_DIRS} is the temporary directory for the system, e.g., "/var/tmp"
+// or "C:/TEMP".
+//
+// '%%' means random value to make the generated path unique.
+//
+// \param MainFile is used to get the root of the project from global
+// compilation database. \param PrefixDir is used to get the user
+// defined prefix for module files. This is useful when we want to seperate
+// module files. e.g., we want to build module files for the same module unit
+// `a.cppm` with 2 different users `b.cpp` and `c.cpp` and we don't want the
+// module file for `b.cpp` be conflict with the module files for `c.cpp`. Then
+// we can put the 2 module files into different dirs like:
+//
+//   ${TEMP_DIRS}/clangd/module_files/b.cpp/a.pcm
+//   ${TEMP_DIRS}/clangd/module_files/c.cpp/a.pcm
+//
+// TODO: Move these module fils out of the temporary directory if the module
+// files are persistent.
+llvm::SmallString<256> getUniqueModuleFilesPath(PathRef MainFile,
+llvm::StringRef PrefixDir) {
+  llvm::SmallString<256> ResultPattern;
+
+  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/true,
+ ResultPattern);
+
+  llvm::sys::path::append(ResultPattern, "clangd");
+  llvm::sys::path::append(ResultPattern, "module_files");
+
+  llvm::sys::path::append(ResultPattern, PrefixDir);
+
+  ResultPattern.append("-%%-%%-%%-%%-%%-%%");
+
+  llvm::SmallString<256> Result;
+  llvm::sys::fs::createUniquePath(ResultPattern, Result,
+  /*MakeAbsolute=*/false);
+
+  llvm::sys::fs::create_directories(Result);
+  return Result;
+}
+
+// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getModuleFilePath(llvm::StringRef ModuleName,
+  PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePattern(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePattern, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePattern.append("-");
+ModuleFilePattern.append(PartitionName);
+  }
+
+  ModuleFilePattern.append(".pcm");
+
+  llvm::SmallString<256> ModuleFilePath;
+  llvm::sys::fs::createUniquePath(ModuleFilePattern, ModuleFilePath,
+  /*MakeAbsolute=*/false);
+
+  return std::string(ModuleFilePath);
+}
+} // namespace
+
+// FailedPrerequisiteModules - stands for the PrerequisiteModules which has
+// errors happened during the building process.
+class FailedPrerequisiteModules : public PrerequisiteModules {
+public:
+  ~FailedPrerequisiteModules() override = default;
+
+  // We shouldn't adjust the compilation commands based on
+  // FailedPrerequisiteModules.
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+  }
+
+  // FailedPrerequisiteModules can never be reused.
+  bool
+  canReuse(const CompilerInvocation &CI,
+   llvm::IntrusiveRefCntPtr) const override {
+return false;
+  }
+
+  // No module unit got built in FailedPrerequisiteModules.
+  bool isModuleUnitBuilt(llvm::StringRef ModuleName) const override {
+return false;
+  }
+};
+
+// StandalonePrerequisiteModules - stands for PrerequisiteModules for which all
+// the required modules are built successfully. All the module files
+// are owned by the StandalonePrerequisiteModules class.
+//
+// Any of the built module files won't be shared with other instances of the
+// class. So that we can avoid worrying thread safety.
+//
+// We don't need to worry about duplicated module names here since the standard
+// guarantees the module names should be unique to a pr

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits




ChuanqiXu9 wrote:

Oh, maybe I was misreading. It looks doable if we only want to avoid 
DirectoryBasedGlobalCompilationDatabase. Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -27,6 +27,9 @@
 #include "Diagnostics.h"
 #include "FS.h"
 #include "Headers.h"
+

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits




ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,81 @@
+//=== ModuleDependencyScanner.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModuleDependencyScanner.h"
+#include "support/Logger.h"
+
+namespace clang {
+namespace clangd {
+
+std::optional
+ModuleDependencyScanner::scan(PathRef FilePath) {
+  std::optional Cmd = CDB.getCompileCommand(FilePath);
+
+  if (!Cmd)
+return std::nullopt;
+
+  using namespace clang::tooling::dependencies;
+
+  llvm::SmallString<128> FilePathDir(FilePath);
+  llvm::sys::path::remove_filename(FilePathDir);
+  DependencyScanningTool ScanningTool(Service, TFS.view(FilePathDir));
+
+  llvm::Expected ScanningResult =
+  ScanningTool.getP1689ModuleDependencyFile(*Cmd, Cmd->Directory);
+
+  if (auto E = ScanningResult.takeError()) {
+log("Scanning modules dependencies for {0} failed: {1}", FilePath,
+llvm::toString(std::move(E)));
+return std::nullopt;
+  }
+
+  ModuleDependencyInfo Result;
+
+  if (ScanningResult->Provides) {
+ModuleNameToSource[ScanningResult->Provides->ModuleName] = FilePath;

ChuanqiXu9 wrote:

> i think it might be better to change the layering a little bit, so that we 
> can scan for a single file (possibly with contents coming from a virtual 
> buffer, as clangd can operate on non-saved files) without triggering the scan 
> on the whole project (e.g. ModulesBuilder::buildPrerequisiteModulesFor should 
> probably retrieve RequiredModules for current file without consulting the 
> full module-graph). But I can see that's a big change, it's fine to do that 
> in a follow up patch.

Maybe due to I am the author, I feel the code here is almost natural and not 
complex. And I agree that there will be a lot of spaces to improve in the 
future.

> sorry i was rather talking about projects that enabled modules, but contain 
> files that do not use modules, as in such a project we shouldn't really 
> expect any files that don't use modules (at least that's my understanding, 
> happy to be proven wrong).

It should be true for some small grained project like I listed above. But let's 
image a big project just like LLVM which has a lot of sub-module. We can image 
if someday modules goes to LLVM, it won't be the case that all of the headers 
gone in one night. It must be a pretty long process to refactor the code base 
step by step and remain the headers for a relative long time to backup or for 
backward compatiblity. And this is exactly what we have internally.


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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,347 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+
+#include "Compiler.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+#include "clang/Serialization/ASTReader.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+// Create a path to store module files. Generally it should be:
+//
+//   {TEMP_DIRS}/clangd/module_files/{hashed-file-name}-%%-%%-%%-%%-%%-%%/.
+//
+// {TEMP_DIRS} is the temporary directory for the system, e.g., "/var/tmp"
+// or "C:/TEMP".
+//
+// '%%' means random value to make the generated path unique.
+//
+// \param MainFile is used to get the root of the project from global
+// compilation database.
+//
+// TODO: Move these module fils out of the temporary directory if the module
+// files are persistent.
+llvm::SmallString<256> getUniqueModuleFilesPath(PathRef MainFile) {
+  llvm::SmallString<128> HashedPrefix = llvm::sys::path::filename(MainFile);
+  // There might be multiple files with the same name in a project. So 
appending
+  // the hash value of the full path to make sure they won't conflict.
+  HashedPrefix += std::to_string(llvm::hash_value(MainFile));
+
+  llvm::SmallString<256> ResultPattern;
+
+  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/true,
+ ResultPattern);
+
+  llvm::sys::path::append(ResultPattern, "clangd");
+  llvm::sys::path::append(ResultPattern, "module_files");
+
+  llvm::sys::path::append(ResultPattern, HashedPrefix);
+
+  ResultPattern.append("-%%-%%-%%-%%-%%-%%");
+
+  llvm::SmallString<256> Result;
+  llvm::sys::fs::createUniquePath(ResultPattern, Result,
+  /*MakeAbsolute=*/false);
+
+  llvm::sys::fs::create_directories(Result);
+  return Result;
+}
+
+// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {

ChuanqiXu9 wrote:

Oh, I didn't notice this. Thanks.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,26 @@
+//=== ScanningProjectModules.h ---*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_SCANNINGPROJECTMODULES_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_SCANNINGPROJECTMODULES_H
+
+#include "ProjectModules.h"
+#include "clang/Tooling/CompilationDatabase.h"
+
+namespace clang {
+namespace clangd {
+
+// Providing modules information for the project by scanning every file.

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -710,6 +710,7 @@ class ASTWorker {
   TUScheduler::ASTCache &IdleASTs;
   TUScheduler::HeaderIncluderCache &HeaderIncluders;
   const bool RunSync;
+

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -213,10 +213,10 @@ ClangdServer::Options::operator TUScheduler::Options() 
const {
 
 ClangdServer::ClangdServer(const GlobalCompilationDatabase &CDB,
const ThreadsafeFS &TFS, const Options &Opts,
-   Callbacks *Callbacks)
+   Callbacks *Callbacks, ModulesBuilder 
*ModulesManager)

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,364 @@
+//===--- PrerequisiteModulesTests.cpp ---*- C++
+//-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+/// FIXME: Skip testing on windows temporarily due to the different escaping
+/// code mode.
+#ifndef _WIN32
+
+#include "ModulesBuilder.h"
+
+#include "Annotations.h"
+#include "CodeComplete.h"
+#include "Compiler.h"
+#include "TestTU.h"
+#include "support/ThreadsafeFS.h"
+
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang::clangd {
+namespace {
+class PrerequisiteModulesTests : public ::testing::Test {
+  protected:
+  void SetUp() override {
+ASSERT_FALSE(llvm::sys::fs::createUniqueDirectory("modules-test", 
TestDir));
+  }
+
+  void TearDown() override { llvm::sys::fs::remove_directories(TestDir); }
+
+public:
+  // Add files to the working testing directory and repalce all the
+  // `__DIR__` to TestDir.
+  void addFile(llvm::StringRef Path, llvm::StringRef Contents) {
+ASSERT_FALSE(llvm::sys::path::is_absolute(Path));
+
+SmallString<256> AbsPath(TestDir);
+llvm::sys::path::append(AbsPath, Path);
+
+ASSERT_FALSE(llvm::sys::fs::create_directories(
+llvm::sys::path::parent_path(AbsPath)));
+
+std::error_code EC;
+llvm::raw_fd_ostream OS(AbsPath, EC);
+ASSERT_FALSE(EC);
+
+std::size_t Pos = Contents.find("__DIR__");
+while (Pos != llvm::StringRef::npos) {
+  OS << Contents.take_front(Pos);
+  OS << TestDir;
+  Contents = Contents.drop_front(Pos + sizeof("__DIR__") - 1);
+  Pos = Contents.find("__DIR__");
+}
+
+OS << Contents;
+  }
+
+  // Get the absolute path for file specified by Path under testing working
+  // directory.
+  std::string getFullPath(llvm::StringRef Path) {
+SmallString<128> Result(TestDir);
+llvm::sys::path::append(Result, Path);
+EXPECT_TRUE(llvm::sys::fs::exists(Result.str()));
+return Result.str().str();
+  }
+
+  std::unique_ptr getGlobalCompilationDatabase() {
+// The compilation flags with modules are much complex so it looks better
+// to use DirectoryBasedGlobalCompilationDatabase than a mocked compilation
+// database.
+DirectoryBasedGlobalCompilationDatabase::Options Opts(TFS);
+return std::make_unique(Opts);
+  }
+
+  ParseInputs getInputs(llvm::StringRef FileName,
+const GlobalCompilationDatabase &CDB) {
+std::string FullPathName = getFullPath(FileName);
+
+ParseInputs Inputs;
+std::optional Cmd =
+CDB.getCompileCommand(FullPathName);
+EXPECT_TRUE(Cmd);
+Inputs.CompileCommand = std::move(*Cmd);
+Inputs.TFS = &TFS;
+
+if (auto Contents = TFS.view(TestDir)->getBufferForFile(FullPathName))
+  Inputs.Contents = Contents->get()->getBuffer().str();
+
+return Inputs;
+  }
+
+  std::unique_ptr
+  getCompilerInvocation(const ParseInputs &Inputs) {
+std::vector CC1Args;
+return buildCompilerInvocation(Inputs, DiagConsumer, &CC1Args);

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,364 @@
+//===--- PrerequisiteModulesTests.cpp ---*- C++
+//-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+/// FIXME: Skip testing on windows temporarily due to the different escaping
+/// code mode.
+#ifndef _WIN32
+
+#include "ModulesBuilder.h"
+
+#include "Annotations.h"
+#include "CodeComplete.h"
+#include "Compiler.h"
+#include "TestTU.h"
+#include "support/ThreadsafeFS.h"
+
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang::clangd {
+namespace {
+class PrerequisiteModulesTests : public ::testing::Test {
+  protected:
+  void SetUp() override {
+ASSERT_FALSE(llvm::sys::fs::createUniqueDirectory("modules-test", 
TestDir));
+  }
+
+  void TearDown() override { llvm::sys::fs::remove_directories(TestDir); }

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,347 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+
+#include "Compiler.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+#include "clang/Serialization/ASTReader.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+// Create a path to store module files. Generally it should be:
+//
+//   {TEMP_DIRS}/clangd/module_files/{hashed-file-name}-%%-%%-%%-%%-%%-%%/.
+//
+// {TEMP_DIRS} is the temporary directory for the system, e.g., "/var/tmp"
+// or "C:/TEMP".
+//
+// '%%' means random value to make the generated path unique.
+//
+// \param MainFile is used to get the root of the project from global
+// compilation database.
+//
+// TODO: Move these module fils out of the temporary directory if the module
+// files are persistent.
+llvm::SmallString<256> getUniqueModuleFilesPath(PathRef MainFile) {
+  llvm::SmallString<128> HashedPrefix = llvm::sys::path::filename(MainFile);
+  // There might be multiple files with the same name in a project. So 
appending
+  // the hash value of the full path to make sure they won't conflict.
+  HashedPrefix += std::to_string(llvm::hash_value(MainFile));
+
+  llvm::SmallString<256> ResultPattern;
+
+  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/true,
+ ResultPattern);
+
+  llvm::sys::path::append(ResultPattern, "clangd");
+  llvm::sys::path::append(ResultPattern, "module_files");
+
+  llvm::sys::path::append(ResultPattern, HashedPrefix);
+
+  ResultPattern.append("-%%-%%-%%-%%-%%-%%");
+
+  llvm::SmallString<256> Result;
+  llvm::sys::fs::createUniquePath(ResultPattern, Result,
+  /*MakeAbsolute=*/false);
+
+  llvm::sys::fs::create_directories(Result);
+  return Result;
+}
+
+// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getModuleFilePath(llvm::StringRef ModuleName,
+  PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePath(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePath, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePath.append("-");
+ModuleFilePath.append(PartitionName);
+  }
+
+  ModuleFilePath.append(".pcm");
+  return std::string(ModuleFilePath);
+}
+
+// FailedPrerequisiteModules - stands for the PrerequisiteModules which has
+// errors happened during the building process.
+class FailedPrerequisiteModules : public PrerequisiteModules {
+public:
+  ~FailedPrerequisiteModules() override = default;
+
+  // We shouldn't adjust the compilation commands based on
+  // FailedPrerequisiteModules.
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+  }
+
+  // FailedPrerequisiteModules can never be reused.
+  bool
+  canReuse(const CompilerInvocation &CI,
+   llvm::IntrusiveRefCntPtr) const override {
+return false;
+  }
+};
+
+// StandalonePrerequisiteModules - stands for PrerequisiteModules for which all
+// the required modules are built successfully. All the module files
+// are owned by the StandalonePrerequisiteModules class.
+//
+// Any of the built module files won't be shared with other instances of the
+// class. So that we can avoid worrying thread safety.
+//
+// We don't need to worry about duplicated module names here since the standard
+// guarantees the module names should be unique to a program.
+class StandalonePrerequisiteModules : public PrerequisiteModules {
+public:
+  StandalonePrerequisiteModules() = default;
+
+  StandalonePrerequisiteModules(const StandalonePrerequisiteModules &) = 
delete;
+  StandalonePrerequisiteModules
+  operator=(const StandalonePrerequisiteModules &) = delete;
+  StandalonePrerequisiteModules(StandalonePrerequisiteModules &&) = delete;
+  StandalonePrerequisiteModules
+  operator=(StandalonePrerequisiteModules &&) = delete;
+
+  ~StandalonePrerequisiteModules() override = default;
+
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+// Appending all built module f

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,347 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+
+#include "Compiler.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+#include "clang/Serialization/ASTReader.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+// Create a path to store module files. Generally it should be:
+//
+//   {TEMP_DIRS}/clangd/module_files/{hashed-file-name}-%%-%%-%%-%%-%%-%%/.
+//
+// {TEMP_DIRS} is the temporary directory for the system, e.g., "/var/tmp"
+// or "C:/TEMP".
+//
+// '%%' means random value to make the generated path unique.
+//
+// \param MainFile is used to get the root of the project from global
+// compilation database.
+//
+// TODO: Move these module fils out of the temporary directory if the module
+// files are persistent.
+llvm::SmallString<256> getUniqueModuleFilesPath(PathRef MainFile) {
+  llvm::SmallString<128> HashedPrefix = llvm::sys::path::filename(MainFile);
+  // There might be multiple files with the same name in a project. So 
appending
+  // the hash value of the full path to make sure they won't conflict.
+  HashedPrefix += std::to_string(llvm::hash_value(MainFile));
+
+  llvm::SmallString<256> ResultPattern;
+
+  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/true,
+ ResultPattern);
+
+  llvm::sys::path::append(ResultPattern, "clangd");
+  llvm::sys::path::append(ResultPattern, "module_files");
+
+  llvm::sys::path::append(ResultPattern, HashedPrefix);
+
+  ResultPattern.append("-%%-%%-%%-%%-%%-%%");
+
+  llvm::SmallString<256> Result;
+  llvm::sys::fs::createUniquePath(ResultPattern, Result,
+  /*MakeAbsolute=*/false);
+
+  llvm::sys::fs::create_directories(Result);
+  return Result;
+}
+
+// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getModuleFilePath(llvm::StringRef ModuleName,
+  PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePath(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePath, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePath.append("-");
+ModuleFilePath.append(PartitionName);
+  }
+
+  ModuleFilePath.append(".pcm");
+  return std::string(ModuleFilePath);
+}
+
+// FailedPrerequisiteModules - stands for the PrerequisiteModules which has
+// errors happened during the building process.
+class FailedPrerequisiteModules : public PrerequisiteModules {
+public:
+  ~FailedPrerequisiteModules() override = default;
+
+  // We shouldn't adjust the compilation commands based on
+  // FailedPrerequisiteModules.
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+  }
+
+  // FailedPrerequisiteModules can never be reused.
+  bool
+  canReuse(const CompilerInvocation &CI,
+   llvm::IntrusiveRefCntPtr) const override {
+return false;
+  }
+};
+
+// StandalonePrerequisiteModules - stands for PrerequisiteModules for which all
+// the required modules are built successfully. All the module files
+// are owned by the StandalonePrerequisiteModules class.
+//
+// Any of the built module files won't be shared with other instances of the
+// class. So that we can avoid worrying thread safety.
+//
+// We don't need to worry about duplicated module names here since the standard
+// guarantees the module names should be unique to a program.
+class StandalonePrerequisiteModules : public PrerequisiteModules {
+public:
+  StandalonePrerequisiteModules() = default;
+
+  StandalonePrerequisiteModules(const StandalonePrerequisiteModules &) = 
delete;
+  StandalonePrerequisiteModules
+  operator=(const StandalonePrerequisiteModules &) = delete;
+  StandalonePrerequisiteModules(StandalonePrerequisiteModules &&) = delete;
+  StandalonePrerequisiteModules
+  operator=(StandalonePrerequisiteModules &&) = delete;
+
+  ~StandalonePrerequisiteModules() override = default;
+
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+// Appending all built module f

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,347 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+
+#include "Compiler.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+#include "clang/Serialization/ASTReader.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+// Create a path to store module files. Generally it should be:
+//
+//   {TEMP_DIRS}/clangd/module_files/{hashed-file-name}-%%-%%-%%-%%-%%-%%/.
+//
+// {TEMP_DIRS} is the temporary directory for the system, e.g., "/var/tmp"
+// or "C:/TEMP".
+//
+// '%%' means random value to make the generated path unique.
+//
+// \param MainFile is used to get the root of the project from global
+// compilation database.
+//
+// TODO: Move these module fils out of the temporary directory if the module
+// files are persistent.
+llvm::SmallString<256> getUniqueModuleFilesPath(PathRef MainFile) {
+  llvm::SmallString<128> HashedPrefix = llvm::sys::path::filename(MainFile);
+  // There might be multiple files with the same name in a project. So 
appending
+  // the hash value of the full path to make sure they won't conflict.
+  HashedPrefix += std::to_string(llvm::hash_value(MainFile));
+
+  llvm::SmallString<256> ResultPattern;
+
+  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/true,
+ ResultPattern);
+
+  llvm::sys::path::append(ResultPattern, "clangd");
+  llvm::sys::path::append(ResultPattern, "module_files");
+
+  llvm::sys::path::append(ResultPattern, HashedPrefix);
+
+  ResultPattern.append("-%%-%%-%%-%%-%%-%%");
+
+  llvm::SmallString<256> Result;
+  llvm::sys::fs::createUniquePath(ResultPattern, Result,
+  /*MakeAbsolute=*/false);
+
+  llvm::sys::fs::create_directories(Result);
+  return Result;
+}
+
+// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getModuleFilePath(llvm::StringRef ModuleName,
+  PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePath(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePath, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePath.append("-");
+ModuleFilePath.append(PartitionName);
+  }
+
+  ModuleFilePath.append(".pcm");
+  return std::string(ModuleFilePath);
+}
+
+// FailedPrerequisiteModules - stands for the PrerequisiteModules which has
+// errors happened during the building process.
+class FailedPrerequisiteModules : public PrerequisiteModules {
+public:
+  ~FailedPrerequisiteModules() override = default;
+
+  // We shouldn't adjust the compilation commands based on
+  // FailedPrerequisiteModules.
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+  }
+
+  // FailedPrerequisiteModules can never be reused.
+  bool
+  canReuse(const CompilerInvocation &CI,
+   llvm::IntrusiveRefCntPtr) const override {
+return false;
+  }
+};
+
+// StandalonePrerequisiteModules - stands for PrerequisiteModules for which all
+// the required modules are built successfully. All the module files
+// are owned by the StandalonePrerequisiteModules class.
+//
+// Any of the built module files won't be shared with other instances of the
+// class. So that we can avoid worrying thread safety.
+//
+// We don't need to worry about duplicated module names here since the standard
+// guarantees the module names should be unique to a program.
+class StandalonePrerequisiteModules : public PrerequisiteModules {
+public:
+  StandalonePrerequisiteModules() = default;
+
+  StandalonePrerequisiteModules(const StandalonePrerequisiteModules &) = 
delete;
+  StandalonePrerequisiteModules
+  operator=(const StandalonePrerequisiteModules &) = delete;
+  StandalonePrerequisiteModules(StandalonePrerequisiteModules &&) = delete;
+  StandalonePrerequisiteModules
+  operator=(StandalonePrerequisiteModules &&) = delete;
+
+  ~StandalonePrerequisiteModules() override = default;
+
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
+// Appending all built module f

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-06-14 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,199 @@
+//===-- ProjectModules.h -*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ProjectModules.h"
+
+#include "support/Logger.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+namespace clang::clangd {
+namespace {
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(vector)` member
+/// function. See the comments of `globalScan` to see the details.
+///
+/// The ModuleDependencyScanner can get the directly required module names for 
a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring the primary module interface for a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interfere with each other.
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(
+  std::shared_ptr CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  /// The scanned modules dependency information for a specific source file.
+  struct ModuleDependencyInfo {
+/// The name of the module if the file is a module unit.
+std::optional ModuleName;
+/// A list of names for the modules that the file directly depends.
+std::vector RequiredModules;
+  };
+
+  /// Scanning the single file specified by \param FilePath.
+  std::optional scan(PathRef FilePath);
+
+  /// Scanning every source file in the current project to get the
+  ///  to  map.
+  /// TODO: We should find an efficient method to get the 
+  /// to  map. We can make it either by providing
+  /// a global module dependency scanner to monitor every file. Or we
+  /// can simply require the build systems (or even the end users)
+  /// to provide the map.
+  void globalScan();
+
+  /// Get the source file from the module name. Note that the language
+  /// guarantees all the module names are unique in a valid program.
+  /// This function should only be called after globalScan.
+  ///
+  /// TODO: We should handle the case that there are multiple source files
+  /// declaring the same module.
+  PathRef getSourceForModuleName(llvm::StringRef ModuleName) const;
+
+  /// Return the direct required modules. Indirect required modules are not
+  /// included.
+  std::vector getRequiredModules(PathRef File);
+
+private:
+  std::shared_ptr CDB;
+  const ThreadsafeFS &TFS;
+
+  // Whether the scanner has scanned the project globally.
+  bool GlobalScanned = false;
+
+  clang::tooling::dependencies::DependencyScanningService Service;
+
+  // TODO: Add a scanning cache.
+
+  // Map module name to source file path.
+  llvm::StringMap ModuleNameToSource;
+};
+
+std::optional
+ModuleDependencyScanner::scan(PathRef FilePath) {
+  auto Candidates = CDB->getCompileCommands(FilePath);
+  if (Candidates.empty())
+return std::nullopt;
+
+  // Choose the first candidates as the compile commands as the file.
+  // Following the same logic with
+  // DirectoryBasedGlobalCompilationDatabase::getCompileCommand.
+  tooling::CompileCommand Cmd = std::move(Candidates.front());

ChuanqiXu9 wrote:

Sorry. I don't understand. Where should the resource dir information go to?

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


[clang] [clang][ARM] Fix warning for VFP function calls from interrupts. (PR #91870)

2024-06-14 Thread Chris Copeland via cfe-commits

https://github.com/chrisnc updated 
https://github.com/llvm/llvm-project/pull/91870

>From b892c59a27089b4753b7677a1ada1ee8da59301b Mon Sep 17 00:00:00 2001
From: Chris Copeland 
Date: Sat, 11 May 2024 00:15:50 -0700
Subject: [PATCH 1/2] [clang][ARM] Fix warning for using VFP from interrupts.

This warning has three issues:
 - The interrupt attribute causes the function to return using an exception
   return instruction. This warning allows calls from one function with
   the interrupt attribute to another, and the diagnostic text suggests
   that not having the attribute on the callee is a problem. Actually
   making such a call will lead to a double exception return, which is
   unpredictable according to the ARM architecture manual section
   B9.1.1, "Restrictions on exception return instructions". Even on
   machines where an exception return from user/system mode is
   tolerated, if the callee's interrupt type is anything other than a
   supervisor call or secure monitor call, it will also return to a
   different address than a normal function would. For example,
   returning from an "IRQ" handler will return to lr - 4, which will
   generally result in calling the same function again.
 - The interrupt attribute currently does not cause caller-saved VFP
   registers to be saved and restored if they are used, so putting
   __attribute__((interrupt)) on a called function doesn't prevent it
   from clobbering VFP state.
 - It is part of the -Wextra diagnostic group and can't be individually
   disabled when using -Wextra, which also means the diagnostic text of
   this specific warning appears in the documentation of -Wextra.

This change addresses all three issues by instead generating a warning
for any interrupt handler where the vfp feature is enabled. The warning is
also given its own diagnostic group.

Closes #34876.
---
 clang/docs/ReleaseNotes.rst   | 11 +
 .../clang/Basic/DiagnosticSemaKinds.td|  7 +--
 clang/lib/Sema/SemaARM.cpp|  5 +++
 clang/lib/Sema/SemaExpr.cpp   | 14 +-
 clang/test/Sema/arm-interrupt-attr.c  | 45 +++
 5 files changed, 27 insertions(+), 55 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 148ff05008552..9d007c3e28cd9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -409,6 +409,11 @@ Modified Compiler Flags
   evaluating to ``true`` and an empty body such as ``while(1);``)
   are considered infinite, even when the ``-ffinite-loop`` flag is set.
 
+- Removed "arm interrupt calling convention" warning that was included in
+  ``-Wextra`` without its own flag.
+
+- Added ``-Warm-interrupt-vfp-clobber``, with its own warning group.
+
 Removed Compiler Flags
 -
 
@@ -569,6 +574,12 @@ Improvements to Clang's diagnostics
 - Clang no longer emits a "declared here" note for a builtin function that has 
no declaration in source.
   Fixes #GH93369.
 
+- For the ARM target, Clang no longer suggests adding 
``__attribute__((interrupt))`` to
+  functions that are called from interrupt handlers to prevent clobbering VFP 
registers
+  as part of ``-Wextra`` (#GH34876). Following this suggestion leads to 
unpredictable
+  behavior. Instead, a new warning, ``-Warm-interrupt-vfp-clobber`` will 
trigger for
+  interrupt handlers with VFP enabled.
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 193eae3bc41d6..56598cafdd0e6 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -336,9 +336,10 @@ def warn_anyx86_excessive_regsave : Warning<
   " with attribute 'no_caller_saved_registers'"
   " or be compiled with '-mgeneral-regs-only'">,
   InGroup>;
-def warn_arm_interrupt_calling_convention : Warning<
-   "call to function without interrupt attribute could clobber interruptee's 
VFP registers">,
-   InGroup;
+def warn_arm_interrupt_vfp_clobber : Warning<
+  "interrupt service routine with vfp enabled may clobber the "
+  "interruptee's vfp state">,
+  InGroup>;
 def warn_interrupt_attribute_invalid : Warning<
"%select{MIPS|MSP430|RISC-V}0 'interrupt' attribute only applies to "
"functions that have %select{no parameters|a 'void' return type}1">,
diff --git a/clang/lib/Sema/SemaARM.cpp b/clang/lib/Sema/SemaARM.cpp
index 02e68dbdb2e9d..5face34d145ae 100644
--- a/clang/lib/Sema/SemaARM.cpp
+++ b/clang/lib/Sema/SemaARM.cpp
@@ -1277,6 +1277,11 @@ void SemaARM::handleInterruptAttr(Decl *D, const 
ParsedAttr &AL) {
 return;
   }
 
+  const TargetInfo &TI = getASTContext().getTargetInfo();
+  if (TI.hasFeature("vfp")) {
+Diag(D->getLocation(), diag::warn_arm_interrupt_vfp_clobber);
+  }
+
   D->addAttr(::new (getASTContext())
  ARMInterruptAttr(getASTContext(), AL, Kind));
 }
diff

[clang] [clang][ARM] Fix warning for VFP function calls from interrupts. (PR #91870)

2024-06-14 Thread Chris Copeland via cfe-commits

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


[clang] dc726c3 - Reapply#4 "[RemoveDIs] Load into new debug info format by default in LLVM (#89799)"

2024-06-14 Thread Stephen Tozer via cfe-commits

Author: Stephen Tozer
Date: 2024-06-14T09:54:56+01:00
New Revision: dc726c340392d4a0f3af9dde5f34c58d98198667

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

LOG: Reapply#4 "[RemoveDIs] Load into new debug info format by default in LLVM 
(#89799)"

Reapplies commit c5aeca73 (and its followup commit 21396be8), which were
reverted due to missing functionality in MLIR and Flang regarding printing
debug records. This has now been added in commit 08aa511, along with support
for printing debug records in flang.

This reverts commit 2dc2290860355dd2bac3b655eea895fe30fde257.

Added: 


Modified: 
clang/test/CodeGen/instrument-objc-method.m
flang/test/Transforms/debug-local-var-2.f90
llvm/docs/ReleaseNotes.rst
llvm/include/llvm/AsmParser/LLParser.h
llvm/lib/AsmParser/LLParser.cpp
llvm/lib/Bitcode/Reader/BitcodeReader.cpp
llvm/lib/IR/BasicBlock.cpp
llvm/lib/IR/DebugProgramInstruction.cpp
llvm/lib/IR/Function.cpp
llvm/lib/IR/Module.cpp
llvm/tools/llvm-as/llvm-as.cpp
llvm/tools/llvm-dis/llvm-dis.cpp
llvm/tools/llvm-link/llvm-link.cpp
llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp
llvm/unittests/IR/BasicBlockDbgInfoTest.cpp
llvm/unittests/IR/DebugInfoTest.cpp
llvm/unittests/IR/IRBuilderTest.cpp
llvm/unittests/IR/InstructionsTest.cpp
llvm/unittests/IR/ValueTest.cpp
llvm/unittests/Transforms/Utils/CloningTest.cpp
llvm/unittests/Transforms/Utils/LocalTest.cpp

Removed: 




diff  --git a/clang/test/CodeGen/instrument-objc-method.m 
b/clang/test/CodeGen/instrument-objc-method.m
index cfc0a0a98bec6..2c9d1fc88554b 100644
--- a/clang/test/CodeGen/instrument-objc-method.m
+++ b/clang/test/CodeGen/instrument-objc-method.m
@@ -11,16 +11,16 @@ @implementation ObjCClass
 + (void)initialize {
 }
 
-// PREINLINE: declare void @llvm.dbg.declare(metadata, metadata, metadata) #1
-// BARE: @"\01+[ObjCClass load]"{{\(.*\)}} #2
+// BARE: @"\01+[ObjCClass load]"{{\(.*\)}} #1
 + (void)load __attribute__((no_instrument_function)) {
 }
 
-// PREINLINE: @"\01-[ObjCClass dealloc]"{{\(.*\)}} #2
-// BARE: @"\01-[ObjCClass dealloc]"{{\(.*\)}} #2
+// PREINLINE: @"\01-[ObjCClass dealloc]"{{\(.*\)}} #1
+// BARE: @"\01-[ObjCClass dealloc]"{{\(.*\)}} #1
 - (void)dealloc __attribute__((no_instrument_function)) {
 }
 
+// PREINLINE: declare void @llvm.dbg.declare(metadata, metadata, metadata) #2
 // PREINLINE: attributes #0 = { 
{{.*}}"instrument-function-entry"="__cyg_profile_func_enter"
 // PREINLINE-NOT: attributes #0 = { 
{{.*}}"instrument-function-entry"="__cyg_profile_func_enter_bare"
 // PREINLINE-NOT: attributes #2 = { {{.*}}"__cyg_profile_func_enter"

diff  --git a/flang/test/Transforms/debug-local-var-2.f90 
b/flang/test/Transforms/debug-local-var-2.f90
index 3b2873a1edaaf..ce78bfd005056 100644
--- a/flang/test/Transforms/debug-local-var-2.f90
+++ b/flang/test/Transforms/debug-local-var-2.f90
@@ -28,27 +28,27 @@
 
 ! BOTH-LABEL: define {{.*}}i64 @_QFPfn1
 ! BOTH-SAME: (ptr %[[ARG1:.*]], ptr %[[ARG2:.*]], ptr %[[ARG3:.*]])
-! INTRINSICS-DAG: tail call void @llvm.dbg.declare(metadata ptr %[[ARG1]], 
metadata ![[A1:.*]], metadata !DIExpression())
-! INTRINSICS-DAG: tail call void @llvm.dbg.declare(metadata ptr %[[ARG2]], 
metadata ![[B1:.*]], metadata !DIExpression())
-! INTRINSICS-DAG: tail call void @llvm.dbg.declare(metadata ptr %[[ARG3]], 
metadata ![[C1:.*]], metadata !DIExpression())
+! INTRINSICS-DAG: call void @llvm.dbg.declare(metadata ptr %[[ARG1]], metadata 
![[A1:.*]], metadata !DIExpression())
+! INTRINSICS-DAG: call void @llvm.dbg.declare(metadata ptr %[[ARG2]], metadata 
![[B1:.*]], metadata !DIExpression())
+! INTRINSICS-DAG: call void @llvm.dbg.declare(metadata ptr %[[ARG3]], metadata 
![[C1:.*]], metadata !DIExpression())
 ! RECORDS-DAG: #dbg_declare(ptr %[[ARG1]], ![[A1:.*]], !DIExpression(), 
!{{.*}})
 ! RECORDS-DAG: #dbg_declare(ptr %[[ARG2]], ![[B1:.*]], !DIExpression(), 
!{{.*}})
 ! RECORDS-DAG: #dbg_declare(ptr %[[ARG3]], ![[C1:.*]], !DIExpression(), 
!{{.*}})
 ! BOTH-DAG: %[[AL2:.*]] = alloca i64
-! INTRINSICS-DAG: tail call void @llvm.dbg.declare(metadata ptr %[[AL2]], 
metadata ![[RES1:.*]], metadata !DIExpression())
+! INTRINSICS-DAG: call void @llvm.dbg.declare(metadata ptr %[[AL2]], metadata 
![[RES1:.*]], metadata !DIExpression())
 ! RECORDS-DAG: #dbg_declare(ptr %[[AL2]], ![[RES1:.*]], !DIExpression(), 
!{{.*}})
 ! BOTH-LABEL: }
 
 ! BOTH-LABEL: define {{.*}}i32 @_QFPfn2
 ! BOTH-SAME: (ptr %[[FN2ARG1:.*]], ptr %[[FN2ARG2:.*]], ptr %[[FN2ARG3:.*]])
-! INTRINSICS-DAG: tail call void @llvm.dbg.declare(metadata ptr %[[FN2ARG1]], 
metadata ![[A2:.*]], metadata !DIExpression())
-! INTRINSICS-DAG: tail call void @llvm.dbg.declare(metadata ptr %[[FN2ARG2]], 
metadata ![[B2:.*]], metadata !DIExpression())
-! 

[clang] [clang][ARM] Fix warning for using VFP from interrupts. (PR #91870)

2024-06-14 Thread Chris Copeland via cfe-commits

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


[clang] [clang][ARM] Fix warning for using VFP from interrupts. (PR #91870)

2024-06-14 Thread Chris Copeland via cfe-commits

chrisnc wrote:

Updated to just warn if the attribute is used while vfp is enabled, and added 
an error for calling an interrupt handler, similar to x86.

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


[clang] [llvm] [llvm][AArch64] Support -mcpu=apple-m4 (PR #95478)

2024-06-14 Thread Tomas Matheson via cfe-commits


@@ -521,7 +521,14 @@ inline constexpr CpuInfo CpuInfos[] = {
  AArch64::ExtensionBitset({AArch64::AEK_AES, AArch64::AEK_SHA2,
AArch64::AEK_SHA3, AArch64::AEK_FP16,
AArch64::AEK_FP16FML})},
-
+// Technically apple-m4 is ARMv9.2a, but a quirk of LLVM defines v9.0 as
+// requiring SVE, which is optional according to the Arm ARM and not
+// supported by the core. ARMv8.7a is the next closest choice.

tmatheson-arm wrote:

>From the Arm ARM: 
> FEAT_SVE2 is OPTIONAL from Armv9.0.

In LLVM, SVE2 is an `Implied` (read: mandatory) feature of 9.0-a (wrong), and 
SVE and SVE2 are both on by default for the architecture:
```
def HasV9_0aOps : Architecture64<9, 0, "a", "v9a",
  [HasV8_5aOps, FeatureMEC, FeatureSVE2],
  !listconcat(HasV8_5aOps.DefaultExts, [FeatureFullFP16, FeatureSVE,
FeatureSVE2])>;
```

It should be possible to remove SVE2 from the `Implied` list while keeping it 
in the list of default extensions, which would avoid any user-facing changes.

I'm not sure why FEAT_MEC is enabled there either.
> FEAT_MEC is OPTIONAL from Armv9.2.


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


[clang] 32cd703 - [clang-cl] Support the /Ob3 flag

2024-06-14 Thread Hans Wennborg via cfe-commits

Author: Hans Wennborg
Date: 2024-06-14T11:11:30+02:00
New Revision: 32cd703da578e769787a921d76b768164a4256b6

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

LOG: [clang-cl] Support the /Ob3 flag

According to the docs, this was added in VS2019 and specifies more
aggressive inlining than /Ob2. Let's treat it the same as /Ob2 for now.

Added: 


Modified: 
clang/docs/UsersManual.rst
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/MSVC.cpp
clang/test/Driver/cl-options.c

Removed: 




diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index ee30e4eff9ea0..15bf5e30cf8e2 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -4632,6 +4632,7 @@ Execute ``clang-cl /?`` to see a list of supported 
options:
   /Ob0Disable function inlining
   /Ob1Only inline functions which are (explicitly or 
implicitly) marked inline
   /Ob2Inline functions as deemed beneficial by the 
compiler
+  /Ob3Same as /Ob2
   /Od Disable optimization
   /Og No effect
   /Oi-Disable use of builtin functions

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 96e522720cec8..1cb03ac1bffb6 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -8262,6 +8262,8 @@ def : CLFlag<"Ob1">, Alias<_SLASH_O>, AliasArgs<["b1"]>,
   HelpText<"Only inline functions explicitly or implicitly marked inline">;
 def : CLFlag<"Ob2">, Alias<_SLASH_O>, AliasArgs<["b2"]>,
   HelpText<"Inline functions as deemed beneficial by the compiler">;
+def : CLFlag<"Ob3">, Alias<_SLASH_O>, AliasArgs<["b3"]>,
+  HelpText<"Same as /Ob2">;
 def : CLFlag<"Od", [CLOption, DXCOption]>, Alias<_SLASH_O>, AliasArgs<["d"]>,
   HelpText<"Disable optimization">;
 def : CLFlag<"Og">, Alias<_SLASH_O>, AliasArgs<["g"]>,

diff  --git a/clang/lib/Driver/ToolChains/MSVC.cpp 
b/clang/lib/Driver/ToolChains/MSVC.cpp
index d03687208c5c6..ca266e3e1d1d3 100644
--- a/clang/lib/Driver/ToolChains/MSVC.cpp
+++ b/clang/lib/Driver/ToolChains/MSVC.cpp
@@ -880,6 +880,7 @@ static void TranslateOptArg(Arg *A, 
llvm::opt::DerivedArgList &DAL,
   DAL.AddFlagArg(A, 
Opts.getOption(options::OPT_finline_hint_functions));
   break;
 case '2':
+case '3':
   DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
   break;
 }

diff  --git a/clang/test/Driver/cl-options.c b/clang/test/Driver/cl-options.c
index e77ec364170d1..95d28e46bc582 100644
--- a/clang/test/Driver/cl-options.c
+++ b/clang/test/Driver/cl-options.c
@@ -163,7 +163,9 @@
 // Ob0: -fno-inline
 
 // RUN: %clang_cl /Ob2 -### -- %s 2>&1 | FileCheck -check-prefix=Ob2 %s
+// RUN: %clang_cl /Ob3 -### -- %s 2>&1 | FileCheck -check-prefix=Ob2 %s
 // RUN: %clang_cl /Odb2 -### -- %s 2>&1 | FileCheck -check-prefix=Ob2 %s
+// RUN: %clang_cl /Odb3 -### -- %s 2>&1 | FileCheck -check-prefix=Ob2 %s
 // RUN: %clang_cl /O2 /Ob2 -### -- %s 2>&1 | FileCheck -check-prefix=Ob2 %s
 // Ob2-NOT: warning: argument unused during compilation: '/O2'
 // Ob2: -finline-functions



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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread via cfe-commits

https://github.com/pointhex updated 
https://github.com/llvm/llvm-project/pull/91317

>From c1e0ad6ee57a95fa4321bbe91aa754167da9fb3b Mon Sep 17 00:00:00 2001
From: Artem Sokolovskii 
Date: Tue, 7 May 2024 12:27:29 +0200
Subject: [PATCH] [clang-format] Add DiagHandler for getStyle function

It allows to control of error output for the function.
---
 clang/include/clang/Format/Format.h|  9 
 clang/lib/Format/Format.cpp| 25 +-
 clang/unittests/Format/ConfigParseTest.cpp | 21 ++
 3 files changed, 41 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 4fd6e013df25b..3bbc362fc8bc7 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5387,10 +5387,11 @@ extern const char *DefaultFallbackStyle;
 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
 /// "file" and no file is found, returns ``FallbackStyle``. If no style could 
be
 /// determined, returns an Error.
-Expected getStyle(StringRef StyleName, StringRef FileName,
-   StringRef FallbackStyle, StringRef Code = "",
-   llvm::vfs::FileSystem *FS = nullptr,
-   bool AllowUnknownOptions = false);
+Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle,
+ StringRef Code = "", llvm::vfs::FileSystem *FS = nullptr,
+ bool AllowUnknownOptions = false,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr);
 
 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
 // Defaults to FormatStyle::LK_Cpp.
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index c015e03fa15e7..b1def18f9b7da 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3946,20 +3946,23 @@ const char *DefaultFallbackStyle = "LLVM";
 
 llvm::ErrorOr>
 loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
-   FormatStyle *Style, bool AllowUnknownOptions) {
+   FormatStyle *Style, bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   llvm::ErrorOr> Text =
   FS->getBufferForFile(ConfigFile.str());
   if (auto EC = Text.getError())
 return EC;
-  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions))
+  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions,
+   DiagHandler)) {
 return EC;
+  }
   return Text;
 }
 
-Expected getStyle(StringRef StyleName, StringRef FileName,
-   StringRef FallbackStyleName, StringRef Code,
-   llvm::vfs::FileSystem *FS,
-   bool AllowUnknownOptions) {
+Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName,
+ StringRef Code, llvm::vfs::FileSystem *FS, bool AllowUnknownOptions,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
   FormatStyle FallbackStyle = getNoStyle();
   if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
@@ -3972,7 +3975,7 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
 StringRef Source = "";
 if (std::error_code ec =
 parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), 
&Style,
-   AllowUnknownOptions)) {
+   AllowUnknownOptions, DiagHandler)) {
   return make_string_error("Error parsing -style: " + ec.message());
 }
 
@@ -3992,7 +3995,8 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   StyleName.starts_with_insensitive("file:")) {
 auto ConfigFile = StyleName.substr(5);
 llvm::ErrorOr> Text =
-loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions);
+loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions,
+   DiagHandler);
 if (auto EC = Text.getError()) {
   return make_string_error("Error reading " + ConfigFile + ": " +
EC.message());
@@ -4032,7 +4036,7 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
   auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   dropDiagnosticHandler);
+   DiagHandler ? DiagHandler : 
dropDiagnosticHandler);
   // It was already correctly parsed.
   assert(!EC);
   static_cast(EC);
@@ -4066,7 +4070,8 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   }
 
   llvm::ErrorOr> Text =
-  loadAndParseConfigFile(Conf

[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-06-14 Thread Mariya Podchishchaeva via cfe-commits


@@ -3334,7 +3347,9 @@ static bool evaluateVarDeclInit(EvalInfo &Info, const 
Expr *E,
 return true;
   }
 
-  if (isa(VD)) {
+  // P2280R4 struck the restriction that variable of referene type lifetime

Fznamznon wrote:

```suggestion
  // P2280R4 struck the restriction that variable of reference type lifetime
```

Though I wonder if these comments should say struck if this was a DR

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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-06-14 Thread Mariya Podchishchaeva via cfe-commits


@@ -3700,6 +3730,11 @@ findSubobject(EvalInfo &Info, const Expr *E, const 
CompleteObject &Obj,
   const FieldDecl *LastField = nullptr;
   const FieldDecl *VolatileField = nullptr;
 
+  // P2280R4 If we have an unknown referene or pointer and we don't have a

Fznamznon wrote:

```suggestion
  // P2280R4 If we have an unknown reference or pointer and we don't have a
```

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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-06-14 Thread Mariya Podchishchaeva via cfe-commits


@@ -3420,6 +3441,15 @@ static bool evaluateVarDeclInit(EvalInfo &Info, const 
Expr *E,
   }
 
   Result = VD->getEvaluatedValue();
+
+  // P2280R4 If we don't have a value because this is a reference that was not
+  // initialized or whose lifetime began within E then create a value with as
+  // a ConstexprUnknown status.
+  if (AllowConstexprUnknown) {
+if (!Result) {
+  Result = new APValue(Base, APValue::ConstexprUnknown{}, 
CharUnits::One());
+}
+  }

Fznamznon wrote:

I also wonder what part of clang will free memory allocated here?

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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-06-14 Thread Mariya Podchishchaeva via cfe-commits


@@ -3358,7 +3373,9 @@ static bool evaluateVarDeclInit(EvalInfo &Info, const 
Expr *E,
   // FIXME: We should eventually check whether the variable has a reachable
   // initializing declaration.
   const Expr *Init = VD->getAnyInitializer(VD);
-  if (!Init) {
+  // P2280R4 struck the restriction that variable of referene type should have

Fznamznon wrote:

```suggestion
  // P2280R4 struck the restriction that variable of reference type should have
```

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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-06-14 Thread Mariya Podchishchaeva via cfe-commits


@@ -3420,6 +3441,15 @@ static bool evaluateVarDeclInit(EvalInfo &Info, const 
Expr *E,
   }
 
   Result = VD->getEvaluatedValue();
+
+  // P2280R4 If we don't have a value because this is a reference that was not
+  // initialized or whose lifetime began within E then create a value with as
+  // a ConstexprUnknown status.
+  if (AllowConstexprUnknown) {
+if (!Result) {
+  Result = new APValue(Base, APValue::ConstexprUnknown{}, 
CharUnits::One());
+}
+  }

Fznamznon wrote:

```suggestion
  if (AllowConstexprUnknown && !Result)
  Result = new APValue(Base, APValue::ConstexprUnknown{}, CharUnits::One());
```

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread via cfe-commits


@@ -4027,12 +4031,10 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   // Reset possible inheritance
   Style.InheritsParentConfig = false;
 
-  auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
-

pointhex wrote:

No problem.

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


[clang] 88e42c6 - [libclang/python] Fix bugs in custom enum implementation and add tests (#95381)

2024-06-14 Thread via cfe-commits

Author: Jannick Kremer
Date: 2024-06-14T13:19:28+04:00
New Revision: 88e42c6779067c4b65624939be74db2d56ee017b

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

LOG: [libclang/python] Fix bugs in custom enum implementation and add tests 
(#95381)

Do not allow initialization of enum from negative IDs (e.g. from_id(-1)
currently produces the last known variant)
Rename duplicate enums: CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE and
TypeKind.OBJCCLASS
Add tests to cover these cases

Added: 
clang/bindings/python/tests/cindex/test_enums.py

Modified: 
clang/bindings/python/clang/cindex.py
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index 302d99dccd77b..b3d51e4d2a668 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -649,7 +649,7 @@ def name(self):
 
 @classmethod
 def from_id(cls, id):
-if id >= len(cls._kinds) or cls._kinds[id] is None:
+if id < 0 or id >= len(cls._kinds) or cls._kinds[id] is None:
 raise ValueError("Unknown template argument kind %d" % id)
 return cls._kinds[id]
 
@@ -1336,7 +1336,7 @@ def __repr__(self):
 CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(271)
 
 # OpenMP teams distribute simd directive.
-CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(272)
+CursorKind.OMP_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(272)
 
 # OpenMP teams distribute parallel for simd directive.
 CursorKind.OMP_TEAMS_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(273)
@@ -2215,7 +2215,7 @@ def name(self):
 
 @staticmethod
 def from_id(id):
-if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]:
+if id < 0 or id >= len(StorageClass._kinds) or not 
StorageClass._kinds[id]:
 raise ValueError("Unknown storage class %d" % id)
 return StorageClass._kinds[id]
 
@@ -2395,7 +2395,7 @@ def __repr__(self):
 TypeKind.OCLRESERVEID = TypeKind(160)
 
 TypeKind.OBJCOBJECT = TypeKind(161)
-TypeKind.OBJCCLASS = TypeKind(162)
+TypeKind.OBJCTYPEPARAM = TypeKind(162)
 TypeKind.ATTRIBUTED = TypeKind(163)
 
 TypeKind.OCLINTELSUBGROUPAVCMCEPAYLOAD = TypeKind(164)

diff  --git a/clang/bindings/python/tests/cindex/test_enums.py 
b/clang/bindings/python/tests/cindex/test_enums.py
new file mode 100644
index 0..6fc0e5ed77e3e
--- /dev/null
+++ b/clang/bindings/python/tests/cindex/test_enums.py
@@ -0,0 +1,47 @@
+import unittest
+
+from clang.cindex import (
+CursorKind,
+TemplateArgumentKind,
+ExceptionSpecificationKind,
+AvailabilityKind,
+AccessSpecifier,
+TypeKind,
+RefQualifierKind,
+LinkageKind,
+TLSKind,
+StorageClass,
+)
+
+
+class TestCursorKind(unittest.TestCase):
+enums = [
+CursorKind,
+TemplateArgumentKind,
+ExceptionSpecificationKind,
+AvailabilityKind,
+AccessSpecifier,
+TypeKind,
+RefQualifierKind,
+LinkageKind,
+TLSKind,
+StorageClass,
+]
+
+def test_from_id(self):
+"""Check that kinds can be constructed from valid IDs"""
+for enum in self.enums:
+self.assertEqual(enum.from_id(2), enum._kinds[2])
+with self.assertRaises(ValueError):
+enum.from_id(len(enum._kinds))
+with self.assertRaises(ValueError):
+enum.from_id(-1)
+
+def test_unique_kinds(self):
+"""Check that no kind name has been used multiple times"""
+for enum in self.enums:
+for id in range(len(enum._kinds)):
+try:
+enum.from_id(id).name
+except ValueError:
+pass

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 68355dbb5861b..bae9f5e1bd02a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -135,6 +135,14 @@ Clang Frontend Potentially Breaking Changes
 - The ``hasTypeLoc`` AST matcher will no longer match a 
``classTemplateSpecializationDecl``;
   existing uses should switch to ``templateArgumentLoc`` or 
``hasAnyTemplateArgumentLoc`` instead.
 
+Clang Python Bindings Potentially Breaking Changes
+--
+- Renamed ``CursorKind`` variant 272 from ``OMP_TEAMS_DISTRIBUTE_DIRECTIVE``
+  to ``OMP_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE``. The previous name was incorrect, 
it was a duplicate
+  of variant 271.
+- Renamed ``TypeKind`` variant 162 from ``OBJCCLASS`` to ``OBJCTYPEPARAM``.
+  The previous name was incorrect, it was a duplicate of variant 28.
+
 What's New in Clang |release|?
 ==
 Some of the major new features and improvements to C

[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread via cfe-commits


@@ -4027,12 +4031,10 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   // Reset possible inheritance
   Style.InheritsParentConfig = false;
 
-  auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
-
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) {
   auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   dropDiagnosticHandler);
+   DiagHandler);

pointhex wrote:

Done

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


[clang] [libclang/python] Fix bugs in custom enum implementation and add tests (PR #95381)

2024-06-14 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [libclang/python] Fix bugs in custom enum implementation and add tests (PR #95381)

2024-06-14 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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


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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread via cfe-commits


@@ -1452,6 +1452,35 @@ TEST(ConfigParseTest, GetStyleOfSpecificFile) {
   ASSERT_EQ(*Style, getGoogleStyle());
 }
 
+TEST(ConfigParseTest, GetStyleOutput) {
+// With output
+::testing::internal::CaptureStderr();
+llvm::vfs::InMemoryFileSystem FS;
+auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
&FS, false);
+
+const std::string output = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style);
+ASSERT_FALSE(output.empty());
+llvm::consumeError(Style.takeError());
+
+// Without output
+::testing::internal::CaptureStderr();
+auto Style1 = getStyle("{invalid_key=invalid_value}",
+   "a.h",
+   "LLVM",
+   "",
+   &FS,
+   false,
+   [](const llvm::SMDiagnostic &, void *) {});
+
+const std::string output1 = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style1);
+ASSERT_TRUE(output1.empty());
+llvm::consumeError(Style1.takeError());

pointhex wrote:

Done

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread via cfe-commits


@@ -1452,6 +1452,35 @@ TEST(ConfigParseTest, GetStyleOfSpecificFile) {
   ASSERT_EQ(*Style, getGoogleStyle());
 }
 
+TEST(ConfigParseTest, GetStyleOutput) {
+// With output
+::testing::internal::CaptureStderr();
+llvm::vfs::InMemoryFileSystem FS;
+auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
&FS, false);
+
+const std::string output = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style);
+ASSERT_FALSE(output.empty());
+llvm::consumeError(Style.takeError());

pointhex wrote:

Done

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


[clang] fix(95366): enhance cast operation safety with LValue validation (PR #95479)

2024-06-14 Thread via cfe-commits

cor3ntin wrote:

Can you make sure the PR/commit have titles and messages that follow our 
guidelines? Thanks!

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


[clang] [llvm] Parse target attribute (PR #95519)

2024-06-14 Thread Alexandros Lamprineas via cfe-commits

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

This is the second attempt. We should be inserting the Driver
features in front of the features of a parsed target attribute
to avoid errors like the following:

```
% cat neon.c
__attribute__((target("arch=armv8-a")))
uint64x2_t foo(uint64x2_t a, uint64x2_t b) { return veorq_u64(a, b); }

% clang --target=aarch64-linux-gnu -c neon.c
error: always_inline function 'veorq_u64' requires target feature
   'outline-atomics', but would be inlined into function 'foo'
   that is compiled without support for 'outline-atomics'
```

>From 66b4dcd6d074c700346b405c48c7ff608122ae8d Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Fri, 14 Jun 2024 08:46:12 +0100
Subject: [PATCH 1/2] Reland "[AArch64] Decouple feature dependency expansion.
 (#94279)"

This is the second attempt. We should be inserting the Driver
features in front of the features of a parsed target attribute
to avoid errors like the following:

```
% cat neon.c
__attribute__((target("arch=armv8-a")))
uint64x2_t foo(uint64x2_t a, uint64x2_t b) { return veorq_u64(a, b); }

% clang --target=aarch64-linux-gnu -c neon.c
error: always_inline function 'veorq_u64' requires target feature
   'outline-atomics', but would be inlined into function 'foo'
   that is compiled without support for 'outline-atomics'
```
---
 clang/include/clang/AST/ASTContext.h  |   3 -
 clang/lib/AST/ASTContext.cpp  |  59 +-
 clang/lib/AST/CMakeLists.txt  |   2 +
 clang/lib/Basic/Targets/AArch64.cpp   | 105 ++---
 clang/lib/Basic/Targets/AArch64.h |   4 -
 .../CodeGen/aarch64-cpu-supports-target.c |   4 +-
 .../aarch64-sme-attrs.cpp |   2 +-
 clang/test/CodeGen/aarch64-targetattr.c   |  48 
 clang/test/CodeGen/attr-target-version.c  |  46 
 clang/test/Sema/aarch64-neon-target.c |   4 +-
 .../llvm/TargetParser/AArch64TargetParser.h   | 107 +++---
 llvm/lib/TargetParser/AArch64TargetParser.cpp |  51 ++---
 12 files changed, 213 insertions(+), 222 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 53ece996769a8..f1f20fca477a4 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -3210,9 +3210,6 @@ class ASTContext : public RefCountedBase {
   /// valid feature names.
   ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
 
-  std::vector
-  filterFunctionTargetVersionAttrs(const TargetVersionAttr *TV) const;
-
   void getFunctionFeatureMap(llvm::StringMap &FeatureMap,
  const FunctionDecl *) const;
   void getFunctionFeatureMap(llvm::StringMap &FeatureMap,
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 34aa399fda2f8..aa22825602a40 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -87,6 +87,7 @@
 #include "llvm/Support/MD5.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/TargetParser/AArch64TargetParser.h"
 #include "llvm/TargetParser/Triple.h"
 #include 
 #include 
@@ -13676,17 +13677,20 @@ QualType 
ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
   }
 }
 
-std::vector ASTContext::filterFunctionTargetVersionAttrs(
-const TargetVersionAttr *TV) const {
-  assert(TV != nullptr);
-  llvm::SmallVector Feats;
-  std::vector ResFeats;
-  TV->getFeatures(Feats);
-  for (auto &Feature : Feats)
-if (Target->validateCpuSupports(Feature.str()))
-  // Use '?' to mark features that came from TargetVersion.
-  ResFeats.push_back("?" + Feature.str());
-  return ResFeats;
+// Given a list of FMV features, return a concatenated list of the
+// corresponding backend features (which may contain duplicates).
+static std::vector getFMVBackendFeaturesFor(
+const llvm::SmallVectorImpl &FMVFeatStrings) {
+  std::vector BackendFeats;
+  for (StringRef F : FMVFeatStrings) {
+if (auto FMVExt = llvm::AArch64::parseArchExtension(F)) {
+  SmallVector Feats;
+  FMVExt->DependentFeatures.split(Feats, ',', -1, false);
+  for (StringRef F : Feats)
+BackendFeats.push_back(F.str());
+}
+  }
+  return BackendFeats;
 }
 
 ParsedTargetAttr
@@ -13721,10 +13725,12 @@ void 
ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap,
 
 // Make a copy of the features as passed on the command line into the
 // beginning of the additional features from the function to override.
-ParsedAttr.Features.insert(
-ParsedAttr.Features.begin(),
-Target->getTargetOpts().FeaturesAsWritten.begin(),
-Target->getTargetOpts().FeaturesAsWritten.end());
+// AArch64 handles command line option features in parseTargetAttr().
+if (!Target->getTriple().isAArch64())
+  ParsedAttr.Features.insert(
+  ParsedAttr.Featur

[clang] [llvm] Parse target attribute (PR #95519)

2024-06-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alexandros Lamprineas (labrinea)


Changes

This is the second attempt. We should be inserting the Driver
features in front of the features of a parsed target attribute
to avoid errors like the following:

```
% cat neon.c
__attribute__((target("arch=armv8-a")))
uint64x2_t foo(uint64x2_t a, uint64x2_t b) { return veorq_u64(a, b); }

% clang --target=aarch64-linux-gnu -c neon.c
error: always_inline function 'veorq_u64' requires target feature
   'outline-atomics', but would be inlined into function 'foo'
   that is compiled without support for 'outline-atomics'
```

---

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


12 Files Affected:

- (modified) clang/include/clang/AST/ASTContext.h (-3) 
- (modified) clang/lib/AST/ASTContext.cpp (+26-23) 
- (modified) clang/lib/AST/CMakeLists.txt (+2) 
- (modified) clang/lib/Basic/Targets/AArch64.cpp (+33-72) 
- (modified) clang/lib/Basic/Targets/AArch64.h (-4) 
- (modified) clang/test/CodeGen/aarch64-cpu-supports-target.c (+2-2) 
- (modified) clang/test/CodeGen/aarch64-sme-intrinsics/aarch64-sme-attrs.cpp 
(+1-1) 
- (modified) clang/test/CodeGen/aarch64-targetattr.c (+20-28) 
- (modified) clang/test/CodeGen/attr-target-version.c (+23-23) 
- (modified) clang/test/Sema/aarch64-neon-target.c (+8-2) 
- (modified) llvm/include/llvm/TargetParser/AArch64TargetParser.h (+65-42) 
- (modified) llvm/lib/TargetParser/AArch64TargetParser.cpp (+33-18) 


``diff
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 53ece996769a8..f1f20fca477a4 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -3210,9 +3210,6 @@ class ASTContext : public RefCountedBase {
   /// valid feature names.
   ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
 
-  std::vector
-  filterFunctionTargetVersionAttrs(const TargetVersionAttr *TV) const;
-
   void getFunctionFeatureMap(llvm::StringMap &FeatureMap,
  const FunctionDecl *) const;
   void getFunctionFeatureMap(llvm::StringMap &FeatureMap,
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 34aa399fda2f8..7fb5966c0bf7c 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -87,6 +87,7 @@
 #include "llvm/Support/MD5.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/TargetParser/AArch64TargetParser.h"
 #include "llvm/TargetParser/Triple.h"
 #include 
 #include 
@@ -13676,17 +13677,20 @@ QualType 
ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
   }
 }
 
-std::vector ASTContext::filterFunctionTargetVersionAttrs(
-const TargetVersionAttr *TV) const {
-  assert(TV != nullptr);
-  llvm::SmallVector Feats;
-  std::vector ResFeats;
-  TV->getFeatures(Feats);
-  for (auto &Feature : Feats)
-if (Target->validateCpuSupports(Feature.str()))
-  // Use '?' to mark features that came from TargetVersion.
-  ResFeats.push_back("?" + Feature.str());
-  return ResFeats;
+// Given a list of FMV features, return a concatenated list of the
+// corresponding backend features (which may contain duplicates).
+static std::vector getFMVBackendFeaturesFor(
+const llvm::SmallVectorImpl &FMVFeatStrings) {
+  std::vector BackendFeats;
+  for (StringRef F : FMVFeatStrings) {
+if (auto FMVExt = llvm::AArch64::parseArchExtension(F)) {
+  SmallVector Feats;
+  FMVExt->DependentFeatures.split(Feats, ',', -1, false);
+  for (StringRef F : Feats)
+BackendFeats.push_back(F.str());
+}
+  }
+  return BackendFeats;
 }
 
 ParsedTargetAttr
@@ -13745,32 +13749,31 @@ void 
ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap,
 Target->getTargetOpts().FeaturesAsWritten.end());
 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
   } else if (const auto *TC = FD->getAttr()) {
-std::vector Features;
 if (Target->getTriple().isAArch64()) {
-  // TargetClones for AArch64
   llvm::SmallVector Feats;
   TC->getFeatures(Feats, GD.getMultiVersionIndex());
-  for (StringRef Feat : Feats)
-if (Target->validateCpuSupports(Feat.str()))
-  // Use '?' to mark features that came from AArch64 TargetClones.
-  Features.push_back("?" + Feat.str());
+  std::vector Features = getFMVBackendFeaturesFor(Feats);
   Features.insert(Features.begin(),
   Target->getTargetOpts().FeaturesAsWritten.begin(),
   Target->getTargetOpts().FeaturesAsWritten.end());
+  Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 
Features);
 } else {
+  std::vector Features;
   StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
   if (VersionStr.starts_with("arch="))
 TargetCPU = VersionStr.drop_f

[clang] [llvm] [AMDGPU] Extend readlane, writelane and readfirstlane intrinsic lowering for generic types (PR #89217)

2024-06-14 Thread Vikram Hegde via cfe-commits

vikramRH wrote:





> That's another option. The only real plus to the intermediate is it's 
> slightly less annoying to write combines for. But there are limited combining 
> opportunities for these

we now legalize to intrinsics directly. The SDAG lowering uses a new helper to 
unroll vector cases while also handling convergence tokens

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


[clang] [clang] Dump Auto Type Inference (PR #95509)

2024-06-14 Thread via cfe-commits

Sirraide wrote:

I candidly don’t really see the use case for this feature. This seems like it 
should be done by an LSP rather than by Clang itself—and `clangd` for instance 
can already do this: when I hover over a variable, it shows me the type of that 
variable, irrespective of whether it was declared with `auto` or not. 

Furthermore, in cases where the `auto` ends up being confusing, you can always 
just... not use it. That’s pretty much how we use `auto` in LLVM (i.e. only if 
the type is obvious, e.g. in a `cast<>()`).

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


[clang] (New) Add option to generate additional debug info for expression dereferencing pointer to pointers (PR #95298)

2024-06-14 Thread Jeremy Morse via cfe-commits

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

LGTM, thanks for rapidly rewriting this. I think dereferencing the insertion 
iterator with `&**` will eventually need addressing with the move away from 
intrinsics and insertion, but that can be a matter for when the DIBuilder APIs 
get deprecated / retired.

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-06-14 Thread NAKAMURA Takumi via cfe-commits

chapuni wrote:

Oh, it's apple-specific continuous mode test :(

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


[clang] [clang] Dump Auto Type Inference (PR #95509)

2024-06-14 Thread via cfe-commits

Sirraide wrote:

> when I hover over a variable, it shows me the type of that variable

For example:

![image](https://github.com/llvm/llvm-project/assets/74590115/ab0cf4a7-2967-4278-8109-0a8d8ebbe1bb)


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


[clang] [flang] [flang] Implement -mcmodel flag (PR #95411)

2024-06-14 Thread Tom Eccles via cfe-commits


@@ -39,6 +39,7 @@ ENUM_CODEGENOPT(RelocationModel, llvm::Reloc::Model, 3, 
llvm::Reloc::PIC_) ///<
 ENUM_CODEGENOPT(DebugInfo,  llvm::codegenoptions::DebugInfoKind, 4,  
llvm::codegenoptions::NoDebugInfo) ///< Level of debug info to generate
 ENUM_CODEGENOPT(VecLib, llvm::driver::VectorLibrary, 3, 
llvm::driver::VectorLibrary::NoLibrary) ///< Vector functions library to use
 ENUM_CODEGENOPT(FramePointer, llvm::FramePointerKind, 2, 
llvm::FramePointerKind::None) ///< Enable the usage of frame pointers
+ENUM_CODEGENOPT(CodeModel, llvm::CodeModel::Model, 5, 
llvm::CodeModel::Model::Small)

tblah wrote:

What was your reasoning for defaulting to `llvm::CodeModel::Model::Small` here? 
So far as I can tell, clang avoids setting it when the option is not specified 
explicitly: 
https://github.com/llvm/llvm-project/blob/44df1167f88cabbb4cfde816f279337379ea30b3/clang/lib/CodeGen/CodeGenModule.cpp#L1304

In LLVM, the code model logic seems to get overridden in each implementation of 
LLVMTargetMachine. The first one I looked at does default to 
llvm::CodeModel::Model::Small, but I don't know whether that will always be 
true for every target.

I think it would be safer to store this as a std::optional instead of a 
bitfield.

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


[clang] [flang] [flang] Implement -mcmodel flag (PR #95411)

2024-06-14 Thread Tom Eccles via cfe-commits


@@ -39,6 +39,7 @@ ENUM_CODEGENOPT(RelocationModel, llvm::Reloc::Model, 3, 
llvm::Reloc::PIC_) ///<
 ENUM_CODEGENOPT(DebugInfo,  llvm::codegenoptions::DebugInfoKind, 4,  
llvm::codegenoptions::NoDebugInfo) ///< Level of debug info to generate
 ENUM_CODEGENOPT(VecLib, llvm::driver::VectorLibrary, 3, 
llvm::driver::VectorLibrary::NoLibrary) ///< Vector functions library to use
 ENUM_CODEGENOPT(FramePointer, llvm::FramePointerKind, 2, 
llvm::FramePointerKind::None) ///< Enable the usage of frame pointers
+ENUM_CODEGENOPT(CodeModel, llvm::CodeModel::Model, 5, 
llvm::CodeModel::Model::Small)

tblah wrote:

ultra-nit: why did you use 5 bits here? 3 should be enough

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


[clang] [clang] SourceLocIdentKind::Function should not be dependent (PR #94942)

2024-06-14 Thread via cfe-commits

cor3ntin wrote:

So, looked into this more.
You are correct that `Function` needs not be dependent because we only ever 
show the name of the function unqualified.
However, `FunctionSig` does.
Here is an example of what we are trying to preserve 
https://godbolt.org/z/M3eTa8nn5 (the clang 17 behavior was incorrect)

I apologize for not realizing earlier that your change was actually sensible in 
the case of `Function`

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


[clang] [clang] Dump Auto Type Inference (PR #95509)

2024-06-14 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll commented:

Thank you for working on this, but I'm not sure this is the right direction.

The flag you're proposing is going to add unwieldy amount of remarks if used on 
a typical translation unit as opposed to a small example, because from what I 
understand, it dumps the type of every single `auto` in the TU. I believe this 
is bad ergonomics. You can improve it by not adding remarks to declarations in 
`#include`s, but this only gets you so far.

We already have more targeted means to achieve the same result, but they are 
reserved for the purpose of debugging Clang itself. I'm referring to `#pragma 
clang __debug dump` 
([docs](https://clang.llvm.org/docs/LanguageExtensions.html#dump)):
```cpp
template 
T f(T) {
  return {};
}

int main() {
  auto a = f(0);
  #pragma clang __debug dump a
}
```
yields (colorized in the actual terminal):
```
lookup results for a:
VarDecl 0xe93dce8 <:7:3, col:15> col:8 a 'int' cinit
`-CallExpr 0xe93e108  'int'
  |-ImplicitCastExpr 0xe93e0f0  'int (*)(int)' 
  | `-DeclRefExpr 0xe93e060  'int (int)' lvalue Function 0xe93df60 'f' 
'int (int)' (FunctionTemplate 0xe93d9e8 'f')
  `-IntegerLiteral 0xe93dd98  'int' 0
```
https://godbolt.org/z/Ko5PqdvEh

If you're going to pursue this direction, having a pragma or an attribute that 
adds a remark to a particular declaration seems more useful by being less noisy.

> -mllvm -fdump-auto-type-inference

This patch adds frontend behavior, so it should be `-Xclang`, not `-mllvm`. But 
in any case, if we intend this to be a user interface, it should be a regular 
driver flag, not a frontend flag, because we shouldn't make promises to users 
about the latter.

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


[clang] [Clang][AArch64] Generalise streaming mode checks for builtins. (PR #93802)

2024-06-14 Thread Sander de Smalen via cfe-commits


@@ -559,31 +559,86 @@ SemaARM::ArmStreamingType getArmStreamingFnType(const 
FunctionDecl *FD) {
   return SemaARM::ArmNonStreaming;
 }
 
-static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall,
- const FunctionDecl *FD,
- SemaARM::ArmStreamingType BuiltinType) {
+static bool checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall,
+ FunctionDecl *FD,
+ SemaARM::ArmStreamingType BuiltinType,
+ unsigned BuiltinID) {
   SemaARM::ArmStreamingType FnType = getArmStreamingFnType(FD);
-  if (BuiltinType == SemaARM::ArmStreamingOrSVE2p1) {
-// Check intrinsics that are available in [sve2p1 or sme/sme2].
-llvm::StringMap CallerFeatureMap;
-S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
-if (Builtin::evaluateRequiredTargetFeatures("sve2p1", CallerFeatureMap))
-  BuiltinType = SemaARM::ArmStreamingCompatible;
-else
+
+  // Check if the intrinsic is available in the right mode, i.e.
+  // * When compiling for SME only, the caller must be in streaming mode.
+  // * When compiling for SVE only, the caller must be in non-streaming mode.
+  // * When compiling for both SVE and SME, the caller can be in either mode.
+  if (BuiltinType == SemaARM::VerifyRuntimeMode) {
+static llvm::StringMap CallerFeatureMapWithoutSVE,
+CallerFeatureMapWithoutSME;

sdesmalen-arm wrote:

You're right, not sure what I was thinking here with the 'static' variable :)

I'd rather not go down the route of parsing the BuiltinTargetGuards here or 
making assumptions on the format if we're not going to ensure this format in 
the arm_sve.td file. For example, one can write 
`(sve,featureX)|(sme2,featureX)` or `(sve|sme),featureX`. Sure we can assume 
the former format, but in that case I think we need to have a `SVETargetGuard` 
and a `SMETargetGuard`, that we let TableGen combine into a canonical form for 
the combined `TargetGuard`.

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


[clang] [Clang][AArch64] Generalise streaming mode checks for builtins. (PR #93802)

2024-06-14 Thread Sander de Smalen via cfe-commits


@@ -622,7 +679,8 @@ bool SemaARM::CheckSMEBuiltinFunctionCall(unsigned 
BuiltinID,
 }
 
 if (BuiltinType)
-  checkArmStreamingBuiltin(SemaRef, TheCall, FD, *BuiltinType);
+  HasError |= checkArmStreamingBuiltin(SemaRef, TheCall, FD, *BuiltinType,

sdesmalen-arm wrote:

Done

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


[clang] [Clang][AArch64] Generalise streaming mode checks for builtins. (PR #93802)

2024-06-14 Thread Sander de Smalen via cfe-commits


@@ -559,31 +559,86 @@ SemaARM::ArmStreamingType getArmStreamingFnType(const 
FunctionDecl *FD) {
   return SemaARM::ArmNonStreaming;
 }
 
-static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall,
- const FunctionDecl *FD,
- SemaARM::ArmStreamingType BuiltinType) {
+static bool checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall,
+ FunctionDecl *FD,
+ SemaARM::ArmStreamingType BuiltinType,
+ unsigned BuiltinID) {
   SemaARM::ArmStreamingType FnType = getArmStreamingFnType(FD);
-  if (BuiltinType == SemaARM::ArmStreamingOrSVE2p1) {
-// Check intrinsics that are available in [sve2p1 or sme/sme2].
-llvm::StringMap CallerFeatureMap;
-S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
-if (Builtin::evaluateRequiredTargetFeatures("sve2p1", CallerFeatureMap))
-  BuiltinType = SemaARM::ArmStreamingCompatible;
-else
+
+  // Check if the intrinsic is available in the right mode, i.e.
+  // * When compiling for SME only, the caller must be in streaming mode.
+  // * When compiling for SVE only, the caller must be in non-streaming mode.
+  // * When compiling for both SVE and SME, the caller can be in either mode.
+  if (BuiltinType == SemaARM::VerifyRuntimeMode) {
+static llvm::StringMap CallerFeatureMapWithoutSVE,
+CallerFeatureMapWithoutSME;
+
+// Cache the feature maps, to avoid having to recalculate this for each
+// builtin call.
+static unsigned CachedODRHash = 0;

sdesmalen-arm wrote:

Done

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


[clang] [serialization] no transitive decl change (PR #92083)

2024-06-14 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

While this looks like a useful optimization, I am still not sure why 2x more 
data (is that a correct upper bound?) can lead to a 10x slowdown. I will try to 
dig further to understand what's going on here.

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


[clang] [analyzer] Check the correct first and last elements in cstring.UninitializedRead (PR #95408)

2024-06-14 Thread Donát Nagy via cfe-commits


@@ -26,16 +50,12 @@ void top(char *dst) {
 
 void *mempcpy(void *restrict s1, const void *restrict s2, size_t n);
 
-void mempcpy14() {
+void mempcpy13() {

NagyDonat wrote:

Why are you renaming this to `memcpy13`? I see only two `memcpy` tests after 
this and they have index 15 and 16, which is very random, but at least follows 
14 directly.

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


[clang] [analyzer] Check the correct first and last elements in cstring.UninitializedRead (PR #95408)

2024-06-14 Thread Donát Nagy via cfe-commits

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


[clang] [analyzer] Check the correct first and last elements in cstring.UninitializedRead (PR #95408)

2024-06-14 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat commented:

I read the rest of the commit and only found two very minor observations.

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


[clang] [analyzer] Check the correct first and last elements in cstring.UninitializedRead (PR #95408)

2024-06-14 Thread Donát Nagy via cfe-commits


@@ -413,38 +588,18 @@ ProgramStateRef 
CStringChecker::CheckLocation(CheckerContext &C,
   if (!ER)
 return state;
 
-  SValBuilder &svalBuilder = C.getSValBuilder();
-  ASTContext &Ctx = svalBuilder.getContext();
-
   // Get the index of the accessed element.
-  NonLoc Idx = ER->getIndex();
-
-  if (CK == CharKind::Regular) {
-if (ER->getValueType() != Ctx.CharTy)
-  return state;
-  } else {
-if (ER->getValueType() != Ctx.WideCharTy)
-  return state;
-
-QualType SizeTy = Ctx.getSizeType();
-NonLoc WideSize =
-svalBuilder
-.makeIntVal(Ctx.getTypeSizeInChars(Ctx.WideCharTy).getQuantity(),
-SizeTy)
-.castAs();
-SVal Offset = svalBuilder.evalBinOpNN(state, BO_Mul, Idx, WideSize, 
SizeTy);
-if (Offset.isUnknown())
-  return state;
-Idx = Offset.castAs();
-  }
+  std::optional Idx = getIndex(state, ER, CK);
+  if (!Idx)
+return state;

NagyDonat wrote:

Consider capitalizing `state` in this function to be consistent with the coding 
guidelines and other functions.

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


[clang] [clang] Dump Auto Type Inference (PR #95509)

2024-06-14 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 11c08327dab425b67d80e99850e654e4c6c17864 
df232a67ac0f5a294e8db4c86e10b6bdf664d673 -- 
clang/test/Sema/fdump_auto-type-inference.cpp clang/include/clang/Sema/Sema.h 
clang/lib/Sema/Sema.cpp clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaStmt.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 13d137ec0e..dbb7edd826 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -84,8 +84,9 @@ namespace opts {
 llvm::cl::OptionCategory DumpAutoInference("DumpAutoInference");
 llvm::cl::opt DumpAutoTypeInference{
 "fdump-auto-type-inference",
-llvm::cl::desc("Dump compiler-deduced type for variables and return 
expressions declared using C++ 'auto' keyword"), llvm::cl::ZeroOrMore,
-llvm::cl::cat(DumpAutoInference)};
+llvm::cl::desc("Dump compiler-deduced type for variables and return "
+   "expressions declared using C++ 'auto' keyword"),
+llvm::cl::ZeroOrMore, llvm::cl::cat(DumpAutoInference)};
 } // namespace opts
 
 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {

``




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


[clang] [llvm] [AMDGPU] Extend readlane, writelane and readfirstlane intrinsic lowering for generic types (PR #89217)

2024-06-14 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,65 @@
+; RUN: llc -stop-after=amdgpu-isel -mtriple=amdgcn-- -mcpu=gfx1100 
-verify-machineinstrs -o - %s | FileCheck --check-prefixes=CHECK,ISEL %s
+
+; CHECK-LABEL: name:basic_readfirstlane_i64
+;   CHECK:[[TOKEN:%[0-9]+]]{{[^ ]*}} = CONVERGENCECTRL_ANCHOR

arsenm wrote:

We don't need these isel checks for the tokens if the IR verifier is going to 
catch the breakage. This test can jus be merged with the existing intrinsic 
tests 

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


[clang] [llvm] [AMDGPU] Extend readlane, writelane and readfirstlane intrinsic lowering for generic types (PR #89217)

2024-06-14 Thread Matt Arsenault via cfe-commits


@@ -6129,13 +6150,55 @@ static SDValue lowerLaneOp(const SITargetLowering &TLI, 
SDNode *N,
   if (ValSize % 32 != 0)
 return SDValue();
 
+  auto unrollLaneOp = [&DAG, &SL](SDNode *N) -> SDValue {
+EVT VT = N->getValueType(0);
+unsigned NE = VT.getVectorNumElements();
+EVT EltVT = VT.getVectorElementType();
+SmallVector Scalars;
+unsigned NumOperands = N->getNumOperands();
+SmallVector Operands(NumOperands);
+SDNode *GL = N->getGluedNode();
+
+if (GL) {
+  // only handle convegrencectrl_glue
+  assert(GL->getOpcode() == ISD::CONVERGENCECTRL_GLUE);
+}

arsenm wrote:

Typo convegrencectrl_glue. Also assert(!GL || ...)

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


[clang] [llvm] [analyzer][NFC] Reorganize Z3 report refutation (PR #95128)

2024-06-14 Thread Donát Nagy via cfe-commits

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


[clang] [llvm] [analyzer][NFC] Reorganize Z3 report refutation (PR #95128)

2024-06-14 Thread Donát Nagy via cfe-commits


@@ -50,16 +45,17 @@ void Z3ErrorHandler(Z3_context Context, Z3_error_code 
Error) {
 /// Wrapper for Z3 context
 class Z3Context {

NagyDonat wrote:

Another class that manages a resource in a destructor, but does not handle 
copy/move assignment/construction.

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


[clang] [llvm] [analyzer][NFC] Reorganize Z3 report refutation (PR #95128)

2024-06-14 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat commented:

I tried to review the resource management code thoroughly, but I admit that I'm 
not skilled in this area -- I'm used to working in modern C++ and Python where 
these footguns are less relevant.

I found two classed that (if I understand correctly) violate the "rule of 
three", but I didn't find any acute issues.

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


[clang] [llvm] [analyzer][NFC] Reorganize Z3 report refutation (PR #95128)

2024-06-14 Thread Donát Nagy via cfe-commits


@@ -26,17 +28,10 @@ namespace {
 class Z3Config {

NagyDonat wrote:

If I understand it correctly, rule of three/five dictates that the copy/move 
assignment/construction of this class needs to be handled (or deleted).

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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-06-14 Thread via cfe-commits

https://github.com/cor3ntin commented:

Thanks a lot Shafik!

I like the direction, it looks less complex than i thought it would be
I agree with @frederick-vs-ja that some diagnostics seem to have regressed.
Maybe a variable should not treated as constexpr-unknown if it's not within its 
lifetime

I'd like you to go over all the related issues we have (including the ones we 
closed for duplication), to make sure they work as expected. i think they make 
up for a good corpus of unit tests

We will need changelog / status page update

Just to point it out, there are a few unresolved core issues

https://cplusplus.github.io/CWG/issues/2740.html
https://cplusplus.github.io/CWG/issues/2633.html


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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-06-14 Thread via cfe-commits

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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-06-14 Thread via cfe-commits


@@ -314,53 +316,69 @@ class APValue {
   DataType Data;
 
 public:
-  APValue() : Kind(None) {}
-  explicit APValue(APSInt I) : Kind(None) {
+  bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
+
+  void setConstexprUnknown() { AllowConstexprUnknown = true; }
+
+  APValue() : Kind(None), AllowConstexprUnknown(false) {}
+  explicit APValue(APSInt I) : Kind(None), AllowConstexprUnknown(false) {
 MakeInt(); setInt(std::move(I));
   }
-  explicit APValue(APFloat F) : Kind(None) {
+  explicit APValue(APFloat F) : Kind(None), AllowConstexprUnknown(false) {
 MakeFloat(); setFloat(std::move(F));
   }
-  explicit APValue(APFixedPoint FX) : Kind(None) {
+  explicit APValue(APFixedPoint FX) : Kind(None), AllowConstexprUnknown(false) 
{
 MakeFixedPoint(std::move(FX));
   }
-  explicit APValue(const APValue *E, unsigned N) : Kind(None) {
+  explicit APValue(const APValue *E, unsigned N)
+  : Kind(None), AllowConstexprUnknown(false) {
 MakeVector(); setVector(E, N);
   }
-  APValue(APSInt R, APSInt I) : Kind(None) {
+  APValue(APSInt R, APSInt I) : Kind(None), AllowConstexprUnknown(false) {
 MakeComplexInt(); setComplexInt(std::move(R), std::move(I));
   }
-  APValue(APFloat R, APFloat I) : Kind(None) {
+  APValue(APFloat R, APFloat I) : Kind(None), AllowConstexprUnknown(false) {
 MakeComplexFloat(); setComplexFloat(std::move(R), std::move(I));
   }
   APValue(const APValue &RHS);
   APValue(APValue &&RHS);
   APValue(LValueBase B, const CharUnits &O, NoLValuePath N,
   bool IsNullPtr = false)
-  : Kind(None) {
+  : Kind(None), AllowConstexprUnknown(false) {
 MakeLValue(); setLValue(B, O, N, IsNullPtr);
   }
   APValue(LValueBase B, const CharUnits &O, ArrayRef Path,
   bool OnePastTheEnd, bool IsNullPtr = false)
-  : Kind(None) {
+  : Kind(None), AllowConstexprUnknown(false) {

cor3ntin wrote:

No need to change these, that's what default member initializers are for!

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


  1   2   3   4   >