[clang] 39f4bd2 - [clang][Interp][NFC] Simplify dump() indentation

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T09:01:57+02:00
New Revision: 39f4bd214f1be248283fb7e35bc2610c19169252

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

LOG: [clang][Interp][NFC] Simplify dump() indentation

Use llvm::raw_ostream::indent().

Added: 


Modified: 
clang/lib/AST/Interp/Disasm.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Disasm.cpp b/clang/lib/AST/Interp/Disasm.cpp
index 7a5da90cd9002..f4a6cb85470fb 100644
--- a/clang/lib/AST/Interp/Disasm.cpp
+++ b/clang/lib/AST/Interp/Disasm.cpp
@@ -42,9 +42,7 @@ LLVM_DUMP_METHOD void Function::dump(llvm::raw_ostream &OS) 
const {
 
   auto PrintName = [&OS](const char *Name) {
 OS << Name;
-for (long I = 0, N = strlen(Name); I < 30 - N; ++I) {
-  OS << ' ';
-}
+OS.indent(std::max(30l - strlen(Name), 0ul));
   };
 
   for (CodePtr Start = getCodeBegin(), PC = Start; PC != getCodeEnd();) {



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


[clang] ddff70c - [clang][Interp][NFC] Make InterpFrame::describe() more const-correct

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T09:01:57+02:00
New Revision: ddff70cb4b0017489d98bf301a5bcc4f9fa4afab

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

LOG: [clang][Interp][NFC] Make InterpFrame::describe() more const-correct

Added: 


Modified: 
clang/lib/AST/Interp/InterpFrame.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/InterpFrame.cpp 
b/clang/lib/AST/Interp/InterpFrame.cpp
index 6acfbd3fa614..e20f283c2855 100644
--- a/clang/lib/AST/Interp/InterpFrame.cpp
+++ b/clang/lib/AST/Interp/InterpFrame.cpp
@@ -98,20 +98,19 @@ void print(llvm::raw_ostream &OS, const Pointer &P, 
ASTContext &Ctx,
 return;
   }
 
-  auto printDesc = [&OS, &Ctx](Descriptor *Desc) {
-if (auto *D = Desc->asDecl()) {
+  auto printDesc = [&OS, &Ctx](const Descriptor *Desc) {
+if (const auto *D = Desc->asDecl()) {
   // Subfields or named values.
-  if (auto *VD = dyn_cast(D)) {
+  if (const auto *VD = dyn_cast(D)) {
 OS << *VD;
 return;
   }
   // Base classes.
-  if (isa(D)) {
+  if (isa(D))
 return;
-  }
 }
 // Temporary expression.
-if (auto *E = Desc->asExpr()) {
+if (const auto *E = Desc->asExpr()) {
   E->printPretty(OS, nullptr, Ctx.getPrintingPolicy());
   return;
 }



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


[clang] a0ea9f6 - [clang] Fix 39f4bd214f1be248283fb7e35bc2610c19169252 on win builders

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T09:13:48+02:00
New Revision: a0ea9f63c25b1cd4cb7747ea611596bb5e2db8a3

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

LOG: [clang] Fix 39f4bd214f1be248283fb7e35bc2610c19169252 on win builders

Added: 


Modified: 
clang/lib/AST/Interp/Disasm.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Disasm.cpp b/clang/lib/AST/Interp/Disasm.cpp
index f4a6cb85470f..35ed5d128697 100644
--- a/clang/lib/AST/Interp/Disasm.cpp
+++ b/clang/lib/AST/Interp/Disasm.cpp
@@ -42,7 +42,9 @@ LLVM_DUMP_METHOD void Function::dump(llvm::raw_ostream &OS) 
const {
 
   auto PrintName = [&OS](const char *Name) {
 OS << Name;
-OS.indent(std::max(30l - strlen(Name), 0ul));
+long N = 30 - strlen(Name);
+if (N > 0)
+  OS.indent(N);
   };
 
   for (CodePtr Start = getCodeBegin(), PC = Start; PC != getCodeEnd();) {



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


[clang] 238f158 - [clang] Add test for CWG873

2023-05-31 Thread Vlad Serebrennikov via cfe-commits
Author: Vlad Serebrennikov
Date: 2023-05-31T10:17:27+03:00
New Revision: 238f15820e71080b0bbc7d6ee95303fdb430d6fa

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

LOG: [clang] Add test for CWG873

Also add missing marking to the test of related issue 621.

https://cplusplus.github.io/CWG/issues/621.html
https://cplusplus.github.io/CWG/issues/873.html

Reviewed By: #clang-language-wg, shafik

Differential Revision: https://reviews.llvm.org/D151704

Added: 
clang/test/CXX/drs/dr8xx.cpp

Modified: 
clang/test/CXX/drs/dr6xx.cpp
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/test/CXX/drs/dr6xx.cpp b/clang/test/CXX/drs/dr6xx.cpp
index 59331e7de7687..a08f55dd562a4 100644
--- a/clang/test/CXX/drs/dr6xx.cpp
+++ b/clang/test/CXX/drs/dr6xx.cpp
@@ -234,7 +234,7 @@ namespace dr619 { // dr619: yes
 
 // dr620: dup 568
 
-namespace dr621 {
+namespace dr621 { // dr621: yes
   template T f();
   template<> int f() {} // expected-note {{previous}}
   template<> int f() {} // expected-error {{redefinition}}

diff  --git a/clang/test/CXX/drs/dr8xx.cpp b/clang/test/CXX/drs/dr8xx.cpp
new file mode 100644
index 0..d79430f9e03ca
--- /dev/null
+++ b/clang/test/CXX/drs/dr8xx.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -std=c++98 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++17 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++23 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++2c -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+
+// expected-no-diagnostics
+
+namespace dr873 { // dr873: yes
+#if __cplusplus >= 201103L
+template  void f(T &&);
+template <> void f(int &) {}  // #1
+template <> void f(int &&) {} // #2
+void g(int i) {
+  f(i); // calls f(int&), i.e., #1
+#pragma clang __debug dump f(i)
+  //  CHECK: CallExpr {{.*}}
+  // CHECK-NEXT: |-ImplicitCastExpr {{.*}}
+  // CHECK-NEXT: | `-DeclRefExpr {{.*}} 'f' 'void (int &)' {{.*}}
+
+  f(0); // calls f(int&&), i.e., #2
+#pragma clang __debug dump f(0)
+  //  CHECK: CallExpr {{.*}}
+  // CHECK-NEXT: |-ImplicitCastExpr {{.*}}
+  // CHECK-NEXT: | `-DeclRefExpr {{.*}} 'f' 'void (int &&)' {{.*}}
+}
+#endif
+} // namespace dr873

diff  --git a/clang/www/cxx_dr_status.html b/clang/www/cxx_dr_status.html
index ec2ac24450832..77790bceea851 100755
--- a/clang/www/cxx_dr_status.html
+++ b/clang/www/cxx_dr_status.html
@@ -3767,7 +3767,7 @@ C++ defect report implementation 
status
 https://cplusplus.github.io/CWG/issues/621.html";>621
 C++11
 Template argument deduction from function return types
-Unknown
+Yes
   
   
 https://cplusplus.github.io/CWG/issues/622.html";>622
@@ -5117,7 +5117,7 @@ C++ defect report implementation 
status
 https://cplusplus.github.io/CWG/issues/873.html";>873
 C++11
 Deducing rvalue references in declarative contexts
-Unknown
+Yes
   
   
 https://cplusplus.github.io/CWG/issues/874.html";>874



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


[PATCH] D151704: [clang] Add test for CWG873

2023-05-31 Thread Vlad Serebrennikov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG238f15820e71: [clang] Add test for CWG873 (authored by 
Endill).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151704/new/

https://reviews.llvm.org/D151704

Files:
  clang/test/CXX/drs/dr6xx.cpp
  clang/test/CXX/drs/dr8xx.cpp
  clang/www/cxx_dr_status.html


Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -3767,7 +3767,7 @@
 https://cplusplus.github.io/CWG/issues/621.html";>621
 C++11
 Template argument deduction from function return types
-Unknown
+Yes
   
   
 https://cplusplus.github.io/CWG/issues/622.html";>622
@@ -5117,7 +5117,7 @@
 https://cplusplus.github.io/CWG/issues/873.html";>873
 C++11
 Deducing rvalue references in declarative contexts
-Unknown
+Yes
   
   
 https://cplusplus.github.io/CWG/issues/874.html";>874
Index: clang/test/CXX/drs/dr8xx.cpp
===
--- /dev/null
+++ clang/test/CXX/drs/dr8xx.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -std=c++98 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++17 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++23 -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++2c -triple x86_64-unknown-unknown %s -verify 
-fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+
+// expected-no-diagnostics
+
+namespace dr873 { // dr873: yes
+#if __cplusplus >= 201103L
+template  void f(T &&);
+template <> void f(int &) {}  // #1
+template <> void f(int &&) {} // #2
+void g(int i) {
+  f(i); // calls f(int&), i.e., #1
+#pragma clang __debug dump f(i)
+  //  CHECK: CallExpr {{.*}}
+  // CHECK-NEXT: |-ImplicitCastExpr {{.*}}
+  // CHECK-NEXT: | `-DeclRefExpr {{.*}} 'f' 'void (int &)' {{.*}}
+
+  f(0); // calls f(int&&), i.e., #2
+#pragma clang __debug dump f(0)
+  //  CHECK: CallExpr {{.*}}
+  // CHECK-NEXT: |-ImplicitCastExpr {{.*}}
+  // CHECK-NEXT: | `-DeclRefExpr {{.*}} 'f' 'void (int &&)' {{.*}}
+}
+#endif
+} // namespace dr873
Index: clang/test/CXX/drs/dr6xx.cpp
===
--- clang/test/CXX/drs/dr6xx.cpp
+++ clang/test/CXX/drs/dr6xx.cpp
@@ -234,7 +234,7 @@
 
 // dr620: dup 568
 
-namespace dr621 {
+namespace dr621 { // dr621: yes
   template T f();
   template<> int f() {} // expected-note {{previous}}
   template<> int f() {} // expected-error {{redefinition}}


Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -3767,7 +3767,7 @@
 https://cplusplus.github.io/CWG/issues/621.html";>621
 C++11
 Template argument deduction from function return types
-Unknown
+Yes
   
   
 https://cplusplus.github.io/CWG/issues/622.html";>622
@@ -5117,7 +5117,7 @@
 https://cplusplus.github.io/CWG/issues/873.html";>873
 C++11
 Deducing rvalue references in declarative contexts
-Unknown
+Yes
   
   
 https://cplusplus.github.io/CWG/issues/874.html";>874
Index: clang/test/CXX/drs/dr8xx.cpp
===
--- /dev/null
+++ clang/test/CXX/drs/dr8xx.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -std=c++98 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++17 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++23 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -std=c++2c -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -

[clang] b7e5cb1 - [clang][NFC] Refactor emitSnippet()

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T09:21:23+02:00
New Revision: b7e5cb1f9a3a5226f22bb81c865214be81dce940

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

LOG: [clang][NFC] Refactor emitSnippet()

Rename parameters and local variables and reorder things a bit to be
closer to their first point of use.

Differential Revision: https://reviews.llvm.org/D150840

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index baf9b017fc83..51b901180ee5 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1298,16 +1298,12 @@ void TextDiagnostic::emitSnippetAndCaret(
   emitParseableFixits(Hints, SM);
 }
 
-void TextDiagnostic::emitSnippet(StringRef line, unsigned 
MaxLineNoDisplayWidth,
+void TextDiagnostic::emitSnippet(StringRef SourceLine,
+ unsigned MaxLineNoDisplayWidth,
  unsigned LineNo) {
-  if (line.empty())
+  if (SourceLine.empty())
 return;
 
-  size_t i = 0;
-
-  std::string to_print;
-  bool print_reversed = false;
-
   // Emit line number.
   if (MaxLineNoDisplayWidth > 0) {
 unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);
@@ -1318,28 +1314,30 @@ void TextDiagnostic::emitSnippet(StringRef line, 
unsigned MaxLineNoDisplayWidth,
 OS << " | ";
   }
 
-  while (i,bool> res
-= printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
-bool was_printable = res.second;
+  bool PrintReversed = false;
+  std::string ToPrint;
+  size_t I = 0;
+  while (I < SourceLine.size()) {
+auto [Str, WasPrintable] =
+printableTextForNextCharacter(SourceLine, &I, DiagOpts->TabStop);
 
-if (DiagOpts->ShowColors && was_printable == print_reversed) {
-  if (print_reversed)
+if (DiagOpts->ShowColors && WasPrintable == PrintReversed) {
+  if (PrintReversed)
 OS.reverseColor();
-  OS << to_print;
-  to_print.clear();
+  OS << ToPrint;
+  ToPrint.clear();
   if (DiagOpts->ShowColors)
 OS.resetColor();
 }
 
-print_reversed = !was_printable;
-to_print += res.first.str();
+PrintReversed = !WasPrintable;
+ToPrint += Str;
   }
 
-  if (print_reversed && DiagOpts->ShowColors)
+  if (PrintReversed && DiagOpts->ShowColors)
 OS.reverseColor();
-  OS << to_print;
-  if (print_reversed && DiagOpts->ShowColors)
+  OS << ToPrint;
+  if (PrintReversed && DiagOpts->ShowColors)
 OS.resetColor();
 
   OS << '\n';



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


[PATCH] D150840: [clang][NFC] Refactor emitSnippet()

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb7e5cb1f9a3a: [clang][NFC] Refactor emitSnippet() (authored 
by tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150840/new/

https://reviews.llvm.org/D150840

Files:
  clang/lib/Frontend/TextDiagnostic.cpp


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1298,16 +1298,12 @@
   emitParseableFixits(Hints, SM);
 }
 
-void TextDiagnostic::emitSnippet(StringRef line, unsigned 
MaxLineNoDisplayWidth,
+void TextDiagnostic::emitSnippet(StringRef SourceLine,
+ unsigned MaxLineNoDisplayWidth,
  unsigned LineNo) {
-  if (line.empty())
+  if (SourceLine.empty())
 return;
 
-  size_t i = 0;
-
-  std::string to_print;
-  bool print_reversed = false;
-
   // Emit line number.
   if (MaxLineNoDisplayWidth > 0) {
 unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);
@@ -1318,28 +1314,30 @@
 OS << " | ";
   }
 
-  while (i,bool> res
-= printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
-bool was_printable = res.second;
+  bool PrintReversed = false;
+  std::string ToPrint;
+  size_t I = 0;
+  while (I < SourceLine.size()) {
+auto [Str, WasPrintable] =
+printableTextForNextCharacter(SourceLine, &I, DiagOpts->TabStop);
 
-if (DiagOpts->ShowColors && was_printable == print_reversed) {
-  if (print_reversed)
+if (DiagOpts->ShowColors && WasPrintable == PrintReversed) {
+  if (PrintReversed)
 OS.reverseColor();
-  OS << to_print;
-  to_print.clear();
+  OS << ToPrint;
+  ToPrint.clear();
   if (DiagOpts->ShowColors)
 OS.resetColor();
 }
 
-print_reversed = !was_printable;
-to_print += res.first.str();
+PrintReversed = !WasPrintable;
+ToPrint += Str;
   }
 
-  if (print_reversed && DiagOpts->ShowColors)
+  if (PrintReversed && DiagOpts->ShowColors)
 OS.reverseColor();
-  OS << to_print;
-  if (print_reversed && DiagOpts->ShowColors)
+  OS << ToPrint;
+  if (PrintReversed && DiagOpts->ShowColors)
 OS.resetColor();
 
   OS << '\n';


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1298,16 +1298,12 @@
   emitParseableFixits(Hints, SM);
 }
 
-void TextDiagnostic::emitSnippet(StringRef line, unsigned MaxLineNoDisplayWidth,
+void TextDiagnostic::emitSnippet(StringRef SourceLine,
+ unsigned MaxLineNoDisplayWidth,
  unsigned LineNo) {
-  if (line.empty())
+  if (SourceLine.empty())
 return;
 
-  size_t i = 0;
-
-  std::string to_print;
-  bool print_reversed = false;
-
   // Emit line number.
   if (MaxLineNoDisplayWidth > 0) {
 unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);
@@ -1318,28 +1314,30 @@
 OS << " | ";
   }
 
-  while (i,bool> res
-= printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
-bool was_printable = res.second;
+  bool PrintReversed = false;
+  std::string ToPrint;
+  size_t I = 0;
+  while (I < SourceLine.size()) {
+auto [Str, WasPrintable] =
+printableTextForNextCharacter(SourceLine, &I, DiagOpts->TabStop);
 
-if (DiagOpts->ShowColors && was_printable == print_reversed) {
-  if (print_reversed)
+if (DiagOpts->ShowColors && WasPrintable == PrintReversed) {
+  if (PrintReversed)
 OS.reverseColor();
-  OS << to_print;
-  to_print.clear();
+  OS << ToPrint;
+  ToPrint.clear();
   if (DiagOpts->ShowColors)
 OS.resetColor();
 }
 
-print_reversed = !was_printable;
-to_print += res.first.str();
+PrintReversed = !WasPrintable;
+ToPrint += Str;
   }
 
-  if (print_reversed && DiagOpts->ShowColors)
+  if (PrintReversed && DiagOpts->ShowColors)
 OS.reverseColor();
-  OS << to_print;
-  if (print_reversed && DiagOpts->ShowColors)
+  OS << ToPrint;
+  if (PrintReversed && DiagOpts->ShowColors)
 OS.resetColor();
 
   OS << '\n';
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151785: [clangd] Desugar dependent type aliases for auto type hints

2023-05-31 Thread Younan Zhang via Phabricator via cfe-commits
zyounan created this revision.
Herald added subscribers: jeroen.dobbelaere, kadircet, arphaman.
Herald added a project: All.
zyounan requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

This patch alleviates https://github.com/clangd/clangd/issues/1298.

Containers in C++ such as `std::vector` or `llvm::SmallVector`,
introduce a series of type aliases to adapt to generic algorithms.

Currently, If we write an declarator involving expressions with
these containers and `auto` placeholder, we probably obtain opaque
type alias like following:

  c++
  std::vector v = {1, 2, 3};
  auto value = v[1]; // hint for `value`: value_type
  auto *ptr = &v[0]; // hint for `ptr`: value_type *

These hints are useless for most of the time. It would be nice if we
desugar the type of `value_type` and print `int`, `int *` respectively
in this situation. However, things are complicated if user introduces type-
alias for brevity: we don't want to make the length of hints be too long!

This patch introduces a heuristic method that displays the desugared type
for type-aliases that depend on some template parameters or simply
reduce to builtin types e.g. int, double.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151785

Files:
  clang-tools-extra/clangd/InlayHints.cpp
  clang-tools-extra/clangd/unittests/InlayHintTests.cpp

Index: clang-tools-extra/clangd/unittests/InlayHintTests.cpp
===
--- clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -1417,6 +1417,81 @@
   ExpectedHint{": int", "h"}, ExpectedHint{": int", "i"});
 }
 
+TEST(TypeHints, DependentAliases) {
+  assertTypeHints(
+  R"cpp(
+  template  struct allocator {};
+
+  template 
+  struct vector_base {
+using pointer = T*;
+  };
+
+  template 
+  struct internal_iterator_type_template_we_dont_expect {};
+
+  struct my_iterator {};
+
+  template >
+  struct vector : vector_base {
+using base = vector_base;
+typedef T value_type;
+typedef base::pointer pointer;
+using allocator_type = A;
+using size_type = int;
+using iterator = internal_iterator_type_template_we_dont_expect;
+using non_template_iterator = my_iterator;
+
+value_type& operator[](int index) { return elements[index]; }
+const value_type& at(int index) const { return elements[index]; }
+pointer data() { return &elements[0]; }
+allocator_type get_allocator() { return A(); }
+size_type size() const { return 10; }
+iterator begin() { return iterator(); }
+non_template_iterator end() { return non_template_iterator(); }
+
+T elements[10];
+  };
+
+  vector array;
+
+  auto $no_modifier[[by_value]] = array[3];
+  auto* $ptr_modifier[[ptr]] = &array[3];
+  auto& $ref_modifier[[ref]] = array[3];
+  auto& $at[[immutable]] = array.at(3);
+
+  auto $data[[data]] = array.data();
+  auto $allocator[[alloc]] = array.get_allocator();
+  auto $size[[size]] = array.size();
+  auto $begin[[begin]] = array.begin();
+  auto $end[[end]] = array.end();
+
+
+  // If the type alias is not type-dependent or non-trivial, do not show desugared type.
+  using VeryLongLongTypeName = my_iterator;
+  using Short = VeryLongLongTypeName;
+
+  auto $short_name[[my_value]] = Short();
+
+  // Same applies with templates.
+  template 
+  using basic_static_vector = vector;
+  template 
+  using static_vector = basic_static_vector>;
+
+  auto $vector_name[[vec]] = static_vector();
+  )cpp",
+  ExpectedHint{": int", "no_modifier"},
+  ExpectedHint{": int *", "ptr_modifier"},
+  ExpectedHint{": int &", "ref_modifier"},
+  ExpectedHint{": const int &", "at"}, ExpectedHint{": int *", "data"},
+  ExpectedHint{": allocator", "allocator"},
+  ExpectedHint{": int", "size"}, ExpectedHint{": iterator", "begin"},
+  ExpectedHint{": non_template_iterator", "end"},
+  ExpectedHint{": Short", "short_name"},
+  ExpectedHint{": static_vector", "vector_name"});
+}
+
 TEST(DesignatorHints, Basic) {
   assertDesignatorHints(R"cpp(
 struct S { int x, y, z; };
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -11,10 +11,12 @@
 #include "HeuristicResolver.h"
 #include "ParsedAST.h"
 #include "SourceCode.h"
+#include "clang/AST/ASTDiagnostic.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Type.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/ScopeExit.h"
@@ -190,6 +192,52 @@
   return Designators;
 }
 
+// Determines if any part in desugaring steps of QualType QT is a dependent or
+// builtin t

[PATCH] D151634: [clang] Add test for CWG253

2023-05-31 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill added a comment.

@shafik Thank you for letting me know! Now I wonder if it was possible to 
realize by myself without prior knowledge of CWG 2536, because I feel like some 
cross-references are missing.
Can we proceed if I strip CWG 78 out, leaving only CWG 253?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151634/new/

https://reviews.llvm.org/D151634

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


[PATCH] D148702: [clang] Add Parse and Sema support for RegularKeyword attributes

2023-05-31 Thread Richard Sandiford via Phabricator via cfe-commits
rsandifo-arm updated this revision to Diff 526936.
rsandifo-arm marked an inline comment as done.
rsandifo-arm added a comment.

Rebase to account for a diagnostic that has moved.
No other changes from the previous version.

I'll wait for the build results before pushing.

Thanks for the review!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148702/new/

https://reviews.llvm.org/D148702

Files:
  clang/examples/Attribute/Attribute.cpp
  clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/DeclSpec.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Parse/ParseTentative.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/ParsedAttr.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaStmtAttr.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/Parser/c2x-attribute-keywords.c
  clang/test/Parser/c2x-attribute-keywords.m
  clang/test/Parser/cxx0x-keyword-attributes.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3882,7 +3882,8 @@
   OS << "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
   OS << "const Decl *D) const override {\n";
   OS << "  S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
-  OS << "<< AL << D->getLocation();\n";
+  OS << "<< AL << AL.isRegularKeywordAttribute() << "
+"D->getLocation();\n";
   OS << "  return false;\n";
   OS << "}\n\n";
 }
@@ -3911,7 +3912,7 @@
 OS << (Warn ? "warn_attribute_wrong_decl_type_str"
 : "err_attribute_wrong_decl_type_str");
 OS << ")\n";
-OS << "  << Attr << ";
+OS << "  << Attr << Attr.isRegularKeywordAttribute() << ";
 OS << CalculateDiagnostic(*SubjectObj) << ";\n";
 OS << "return false;\n";
 OS << "  }\n";
@@ -3926,7 +3927,8 @@
   OS << "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
   OS << "const Stmt *St) const override {\n";
   OS << "  S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
-  OS << "<< AL << St->getBeginLoc();\n";
+  OS << "<< AL << AL.isRegularKeywordAttribute() << "
+"St->getBeginLoc();\n";
   OS << "  return false;\n";
   OS << "}\n\n";
 }
@@ -3945,7 +3947,7 @@
 OS << (Warn ? "warn_attribute_wrong_decl_type_str"
 : "err_attribute_wrong_decl_type_str");
 OS << ")\n";
-OS << "  << Attr << ";
+OS << "  << Attr << Attr.isRegularKeywordAttribute() << ";
 OS << CalculateDiagnostic(*SubjectObj) << ";\n";
 OS << "return false;\n";
 OS << "  }\n";
@@ -4016,7 +4018,8 @@
 for (const std::string &A : DeclAttrs) {
   OS << "if (const auto *A = D->getAttr<" << A << ">()) {\n";
   OS << "  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
- << " << AL << A;\n";
+ << " << AL << A << (AL.isRegularKeywordAttribute() ||"
+ << " A->isRegularKeywordAttribute());\n";
   OS << "  S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
   OS << "  \nreturn false;\n";
   OS << "}\n";
@@ -4037,7 +4040,8 @@
 << ">()) {\n";
 MergeDeclOS << "  S.Diag(First->getLocation(), "
 << "diag::err_attributes_are_not_compatible) << First << "
-<< "Second;\n";
+<< "Second << (First->isRegularKeywordAttribute() || "
+<< "Second->isRegularKeywordAttribute());\n";
 MergeDeclOS << "  S.Diag(Second->getLocation(), "
 << "diag::note_conflicting_attribute);\n";
 MergeDeclOS << "  return false;\n";
@@ -4077,7 +4081,8 @@
 MergeStmtOS << "  if (Iter != C.end()) {\n";
 MergeStmtOS << "S.Diag((*Iter)->getLocation(), "
 << "diag::err_attributes_are_not_compatible) << *Iter << "
-<< "Second;\n";
+<< "Second << ((*Iter)->isRegularKeywordAttribute() || "
+<< "Second->isRegularKeywordAttribute());\n";
 MergeStmtOS << "S.Diag(Second->getLocation(), "
 << "diag::note_conflicting_attribute);\n";
 MergeStmtOS << "return false;\n";
Index: clang/test/Parser/cxx0x-keyword-attributes.cpp
===
--- /dev/null
+++ clang/test/Parse

[PATCH] D151608: [Sema] Remove unused function getFloat128Identifier

2023-05-31 Thread Kazu Hirata via Phabricator via cfe-commits
kazu added a comment.

Please take a look.  Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151608/new/

https://reviews.llvm.org/D151608

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


[clang] 49843c5 - [clang][Diagnostics] Simplify emitSnippet()

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T09:40:24+02:00
New Revision: 49843c5036847a8e2f83852c8a515c2784a1645e

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

LOG: [clang][Diagnostics] Simplify emitSnippet()

Don't try to minimize the times we invoke operator<< on the output
stream by keeping a ToPrint string around. Instead, just print the
characters as we iterate over them.

Differential Revision: https://reviews.llvm.org/D151075

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 51b901180ee5..9b11294224ed 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1314,30 +1314,27 @@ void TextDiagnostic::emitSnippet(StringRef SourceLine,
 OS << " | ";
   }
 
+  // Print the source line one character at a time.
   bool PrintReversed = false;
-  std::string ToPrint;
   size_t I = 0;
   while (I < SourceLine.size()) {
 auto [Str, WasPrintable] =
 printableTextForNextCharacter(SourceLine, &I, DiagOpts->TabStop);
 
-if (DiagOpts->ShowColors && WasPrintable == PrintReversed) {
-  if (PrintReversed)
-OS.reverseColor();
-  OS << ToPrint;
-  ToPrint.clear();
-  if (DiagOpts->ShowColors)
-OS.resetColor();
+// Toggle inverted colors on or off for this character.
+if (DiagOpts->ShowColors) {
+  if (WasPrintable == PrintReversed) {
+PrintReversed = !PrintReversed;
+if (PrintReversed)
+  OS.reverseColor();
+else
+  OS.resetColor();
+  }
 }
-
-PrintReversed = !WasPrintable;
-ToPrint += Str;
+OS << Str;
   }
 
-  if (PrintReversed && DiagOpts->ShowColors)
-OS.reverseColor();
-  OS << ToPrint;
-  if (PrintReversed && DiagOpts->ShowColors)
+  if (DiagOpts->ShowColors)
 OS.resetColor();
 
   OS << '\n';



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


[PATCH] D151075: [clang][Diagnostics] Simplify emitSnippet()

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG49843c503684: [clang][Diagnostics] Simplify emitSnippet() 
(authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151075/new/

https://reviews.llvm.org/D151075

Files:
  clang/lib/Frontend/TextDiagnostic.cpp


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1314,30 +1314,27 @@
 OS << " | ";
   }
 
+  // Print the source line one character at a time.
   bool PrintReversed = false;
-  std::string ToPrint;
   size_t I = 0;
   while (I < SourceLine.size()) {
 auto [Str, WasPrintable] =
 printableTextForNextCharacter(SourceLine, &I, DiagOpts->TabStop);
 
-if (DiagOpts->ShowColors && WasPrintable == PrintReversed) {
-  if (PrintReversed)
-OS.reverseColor();
-  OS << ToPrint;
-  ToPrint.clear();
-  if (DiagOpts->ShowColors)
-OS.resetColor();
+// Toggle inverted colors on or off for this character.
+if (DiagOpts->ShowColors) {
+  if (WasPrintable == PrintReversed) {
+PrintReversed = !PrintReversed;
+if (PrintReversed)
+  OS.reverseColor();
+else
+  OS.resetColor();
+  }
 }
-
-PrintReversed = !WasPrintable;
-ToPrint += Str;
+OS << Str;
   }
 
-  if (PrintReversed && DiagOpts->ShowColors)
-OS.reverseColor();
-  OS << ToPrint;
-  if (PrintReversed && DiagOpts->ShowColors)
+  if (DiagOpts->ShowColors)
 OS.resetColor();
 
   OS << '\n';


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1314,30 +1314,27 @@
 OS << " | ";
   }
 
+  // Print the source line one character at a time.
   bool PrintReversed = false;
-  std::string ToPrint;
   size_t I = 0;
   while (I < SourceLine.size()) {
 auto [Str, WasPrintable] =
 printableTextForNextCharacter(SourceLine, &I, DiagOpts->TabStop);
 
-if (DiagOpts->ShowColors && WasPrintable == PrintReversed) {
-  if (PrintReversed)
-OS.reverseColor();
-  OS << ToPrint;
-  ToPrint.clear();
-  if (DiagOpts->ShowColors)
-OS.resetColor();
+// Toggle inverted colors on or off for this character.
+if (DiagOpts->ShowColors) {
+  if (WasPrintable == PrintReversed) {
+PrintReversed = !PrintReversed;
+if (PrintReversed)
+  OS.reverseColor();
+else
+  OS.resetColor();
+  }
 }
-
-PrintReversed = !WasPrintable;
-ToPrint += Str;
+OS << Str;
   }
 
-  if (PrintReversed && DiagOpts->ShowColors)
-OS.reverseColor();
-  OS << ToPrint;
-  if (PrintReversed && DiagOpts->ShowColors)
+  if (DiagOpts->ShowColors)
 OS.resetColor();
 
   OS << '\n';
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D150185: [include-cleaner] Allow multiple strategies for spelling includes.

2023-05-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

It looks good overall. I left some comments around the interfaces. Let me know 
if I miss/misunderstand something.




Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h:88
 
+class IncludeSpeller {
+public:

I think this is an important API (we will create a subclass for our internal 
use), probably worth a dedicated `IncludeSpeller.h/.cpp` file. 



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h:88
 
+class IncludeSpeller {
+public:

hokein wrote:
> I think this is an important API (we will create a subclass for our internal 
> use), probably worth a dedicated `IncludeSpeller.h/.cpp` file. 
I think it would be nice to have a unittest for it.

You can create a subclass `TestIncludeSpeller` in the unittest, which 
implements a dummy  include spelling for a particular absolute file path (e.g. 
a file path starting with `/include-cleaner-test/`), and verify `spellHeader` 
API return expected results.






Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h:96
+  /// or an empty string to indicate no customizations are needed.
+  virtual std::string operator()(llvm::StringRef HeaderPhysicalPath) const = 0;
+};

nit: maybe name the parameter `AbsolutePath`? I think it is better to mention 
the absolute file path in the name.



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h:99
+
+typedef llvm::Registry IncludeSpellingStrategy;
+

nit: consider using `using IncludeSpellingStrategy = 
llvm::Registry;`, which is a more modernized way. 



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h:104
+/// order is not specified.
+std::function defaultHeaderMapper();
+

It is unclear to me why we need `defaultHeaderMapper` and the parameter 
`MapHeader` in `spellHeader` in the header.

Do we want the caller of `spellHeader` to provide a different HeaderMapper? I 
don't see a usecase for that -- the current strategy of is to iterate all 
extension points, if we find the first available one, we just return it; 
otherwise we use the default fallback (`suggestPathToFileForDiagnostics`). I 
believe it is enough for `spellHeader` to cover all our cases.



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150185/new/

https://reviews.llvm.org/D150185

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


[PATCH] D151786: [Tooling] Remove unused function setRestoreWorkingDir

2023-05-31 Thread Kazu Hirata via Phabricator via cfe-commits
kazu created this revision.
Herald added a project: All.
kazu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The last use was removed by:

  commit 146ec74a8382dc820809d0a2bf4b918d0b5e6603
  Author: Jan Svoboda 
  Date:   Fri Sep 10 10:24:16 2021 +0200

Once I remove the function, RestoreCWD is always true, so this patch
removes the variable and propagates the constant.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151786

Files:
  clang/include/clang/Tooling/Tooling.h
  clang/lib/Tooling/Tooling.cpp


Index: clang/lib/Tooling/Tooling.cpp
===
--- clang/lib/Tooling/Tooling.cpp
+++ clang/lib/Tooling/Tooling.cpp
@@ -542,13 +542,11 @@
 
   // Remember the working directory in case we need to restore it.
   std::string InitialWorkingDir;
-  if (RestoreCWD) {
-if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) {
-  InitialWorkingDir = std::move(*CWD);
-} else {
-  llvm::errs() << "Could not get working directory: "
-   << CWD.getError().message() << "\n";
-}
+  if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) {
+InitialWorkingDir = std::move(*CWD);
+  } else {
+llvm::errs() << "Could not get working directory: "
+ << CWD.getError().message() << "\n";
   }
 
   for (llvm::StringRef File : AbsolutePaths) {
@@ -662,10 +660,6 @@
   return run(&Action);
 }
 
-void ClangTool::setRestoreWorkingDir(bool RestoreCWD) {
-  this->RestoreCWD = RestoreCWD;
-}
-
 void ClangTool::setPrintErrorMessage(bool PrintErrorMessage) {
   this->PrintErrorMessage = PrintErrorMessage;
 }
Index: clang/include/clang/Tooling/Tooling.h
===
--- clang/include/clang/Tooling/Tooling.h
+++ clang/include/clang/Tooling/Tooling.h
@@ -361,11 +361,6 @@
   /// append them to ASTs.
   int buildASTs(std::vector> &ASTs);
 
-  /// Sets whether working directory should be restored after calling run(). By
-  /// default, working directory is restored. However, it could be useful to
-  /// turn this off when running on multiple threads to avoid the raciness.
-  void setRestoreWorkingDir(bool RestoreCWD);
-
   /// Sets whether an error message should be printed out if an action fails. 
By
   /// default, if an action fails, a message is printed out to stderr.
   void setPrintErrorMessage(bool PrintErrorMessage);
@@ -395,7 +390,6 @@
 
   DiagnosticConsumer *DiagConsumer = nullptr;
 
-  bool RestoreCWD = true;
   bool PrintErrorMessage = true;
 };
 


Index: clang/lib/Tooling/Tooling.cpp
===
--- clang/lib/Tooling/Tooling.cpp
+++ clang/lib/Tooling/Tooling.cpp
@@ -542,13 +542,11 @@
 
   // Remember the working directory in case we need to restore it.
   std::string InitialWorkingDir;
-  if (RestoreCWD) {
-if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) {
-  InitialWorkingDir = std::move(*CWD);
-} else {
-  llvm::errs() << "Could not get working directory: "
-   << CWD.getError().message() << "\n";
-}
+  if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) {
+InitialWorkingDir = std::move(*CWD);
+  } else {
+llvm::errs() << "Could not get working directory: "
+ << CWD.getError().message() << "\n";
   }
 
   for (llvm::StringRef File : AbsolutePaths) {
@@ -662,10 +660,6 @@
   return run(&Action);
 }
 
-void ClangTool::setRestoreWorkingDir(bool RestoreCWD) {
-  this->RestoreCWD = RestoreCWD;
-}
-
 void ClangTool::setPrintErrorMessage(bool PrintErrorMessage) {
   this->PrintErrorMessage = PrintErrorMessage;
 }
Index: clang/include/clang/Tooling/Tooling.h
===
--- clang/include/clang/Tooling/Tooling.h
+++ clang/include/clang/Tooling/Tooling.h
@@ -361,11 +361,6 @@
   /// append them to ASTs.
   int buildASTs(std::vector> &ASTs);
 
-  /// Sets whether working directory should be restored after calling run(). By
-  /// default, working directory is restored. However, it could be useful to
-  /// turn this off when running on multiple threads to avoid the raciness.
-  void setRestoreWorkingDir(bool RestoreCWD);
-
   /// Sets whether an error message should be printed out if an action fails. By
   /// default, if an action fails, a message is printed out to stderr.
   void setPrintErrorMessage(bool PrintErrorMessage);
@@ -395,7 +390,6 @@
 
   DiagnosticConsumer *DiagConsumer = nullptr;
 
-  bool RestoreCWD = true;
   bool PrintErrorMessage = true;
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151785: [clangd] Desugar dependent type aliases for auto type hints

2023-05-31 Thread Younan Zhang via Phabricator via cfe-commits
zyounan added a comment.

Before
F27754400: before.png 

After
F27754403: after.png 

(Sorry for posting screenshots directly and bringing any inconvenience for 
email users.)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151785/new/

https://reviews.llvm.org/D151785

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


[clang] 1c76548 - [clang][Diagnostics] Use llvm::raw_ostream::indent()

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T09:40:24+02:00
New Revision: 1c765483fd34efe3ff7f71a9d2d5781bdf3d4517

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

LOG: [clang][Diagnostics] Use llvm::raw_ostream::indent()

Differential Revision: https://reviews.llvm.org/D151078

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 9b11294224ed..930033a7d552 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -615,9 +615,6 @@ static bool printWordWrapped(raw_ostream &OS, StringRef Str,
   const unsigned Length = std::min(Str.find('\n'), Str.size());
   bool TextNormal = true;
 
-  // The string used to indent each line.
-  SmallString<16> IndentStr;
-  IndentStr.assign(Indentation, ' ');
   bool Wrapped = false;
   for (unsigned WordStart = 0, WordEnd; WordStart < Length;
WordStart = WordEnd) {
@@ -646,7 +643,7 @@ static bool printWordWrapped(raw_ostream &OS, StringRef Str,
 // This word does not fit on the current line, so wrap to the next
 // line.
 OS << '\n';
-OS.write(&IndentStr[0], Indentation);
+OS.indent(Indentation);
 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
   TextNormal, Bold);
 Column = Indentation + WordLength;
@@ -1188,12 +1185,8 @@ void TextDiagnostic::emitSnippetAndCaret(
   ? std::max(4u, getNumDisplayWidth(DisplayLineNo + MaxLines))
   : 0;
   auto indentForLineNumbers = [&] {
-if (MaxLineNoDisplayWidth > 0) {
-  OS << ' ';
-  for (unsigned I = 0; I != MaxLineNoDisplayWidth; ++I)
-OS << ' ';
-  OS << " | ";
-}
+if (MaxLineNoDisplayWidth > 0)
+  OS.indent(MaxLineNoDisplayWidth + 2) << "| ";
   };
 
   for (unsigned LineNo = Lines.first; LineNo != Lines.second + 1;
@@ -1307,11 +1300,8 @@ void TextDiagnostic::emitSnippet(StringRef SourceLine,
   // Emit line number.
   if (MaxLineNoDisplayWidth > 0) {
 unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);
-OS << ' ';
-for (unsigned I = LineNoDisplayWidth; I < MaxLineNoDisplayWidth; ++I)
-  OS << ' ';
-OS << LineNo;
-OS << " | ";
+OS.indent(MaxLineNoDisplayWidth - LineNoDisplayWidth + 1)
+<< LineNo << " | ";
   }
 
   // Print the source line one character at a time.



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


[PATCH] D151078: [clang][Diagnostics] Use llvm::raw_ostream::indent()

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1c765483fd34: [clang][Diagnostics] Use 
llvm::raw_ostream::indent() (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151078/new/

https://reviews.llvm.org/D151078

Files:
  clang/lib/Frontend/TextDiagnostic.cpp


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -615,9 +615,6 @@
   const unsigned Length = std::min(Str.find('\n'), Str.size());
   bool TextNormal = true;
 
-  // The string used to indent each line.
-  SmallString<16> IndentStr;
-  IndentStr.assign(Indentation, ' ');
   bool Wrapped = false;
   for (unsigned WordStart = 0, WordEnd; WordStart < Length;
WordStart = WordEnd) {
@@ -646,7 +643,7 @@
 // This word does not fit on the current line, so wrap to the next
 // line.
 OS << '\n';
-OS.write(&IndentStr[0], Indentation);
+OS.indent(Indentation);
 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
   TextNormal, Bold);
 Column = Indentation + WordLength;
@@ -1188,12 +1185,8 @@
   ? std::max(4u, getNumDisplayWidth(DisplayLineNo + MaxLines))
   : 0;
   auto indentForLineNumbers = [&] {
-if (MaxLineNoDisplayWidth > 0) {
-  OS << ' ';
-  for (unsigned I = 0; I != MaxLineNoDisplayWidth; ++I)
-OS << ' ';
-  OS << " | ";
-}
+if (MaxLineNoDisplayWidth > 0)
+  OS.indent(MaxLineNoDisplayWidth + 2) << "| ";
   };
 
   for (unsigned LineNo = Lines.first; LineNo != Lines.second + 1;
@@ -1307,11 +1300,8 @@
   // Emit line number.
   if (MaxLineNoDisplayWidth > 0) {
 unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);
-OS << ' ';
-for (unsigned I = LineNoDisplayWidth; I < MaxLineNoDisplayWidth; ++I)
-  OS << ' ';
-OS << LineNo;
-OS << " | ";
+OS.indent(MaxLineNoDisplayWidth - LineNoDisplayWidth + 1)
+<< LineNo << " | ";
   }
 
   // Print the source line one character at a time.


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -615,9 +615,6 @@
   const unsigned Length = std::min(Str.find('\n'), Str.size());
   bool TextNormal = true;
 
-  // The string used to indent each line.
-  SmallString<16> IndentStr;
-  IndentStr.assign(Indentation, ' ');
   bool Wrapped = false;
   for (unsigned WordStart = 0, WordEnd; WordStart < Length;
WordStart = WordEnd) {
@@ -646,7 +643,7 @@
 // This word does not fit on the current line, so wrap to the next
 // line.
 OS << '\n';
-OS.write(&IndentStr[0], Indentation);
+OS.indent(Indentation);
 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
   TextNormal, Bold);
 Column = Indentation + WordLength;
@@ -1188,12 +1185,8 @@
   ? std::max(4u, getNumDisplayWidth(DisplayLineNo + MaxLines))
   : 0;
   auto indentForLineNumbers = [&] {
-if (MaxLineNoDisplayWidth > 0) {
-  OS << ' ';
-  for (unsigned I = 0; I != MaxLineNoDisplayWidth; ++I)
-OS << ' ';
-  OS << " | ";
-}
+if (MaxLineNoDisplayWidth > 0)
+  OS.indent(MaxLineNoDisplayWidth + 2) << "| ";
   };
 
   for (unsigned LineNo = Lines.first; LineNo != Lines.second + 1;
@@ -1307,11 +1300,8 @@
   // Emit line number.
   if (MaxLineNoDisplayWidth > 0) {
 unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);
-OS << ' ';
-for (unsigned I = LineNoDisplayWidth; I < MaxLineNoDisplayWidth; ++I)
-  OS << ' ';
-OS << LineNo;
-OS << " | ";
+OS.indent(MaxLineNoDisplayWidth - LineNoDisplayWidth + 1)
+<< LineNo << " | ";
   }
 
   // Print the source line one character at a time.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c113cbb - [clang][Diagnostic][NFC] Simplify emitDiagnosticLoc

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T09:40:24+02:00
New Revision: c113cbb51005108d1380a4b9d501ddeb1366a406

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

LOG: [clang][Diagnostic][NFC] Simplify emitDiagnosticLoc

We don't use the offset returned from SourceManager::getDecomposedLoc
here, so we might as well just use getFileID().

Differential Revision: https://reviews.llvm.org/D151093

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 930033a7d552..83f254f7de83 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -850,30 +850,26 @@ void TextDiagnostic::emitDiagnosticLoc(FullSourceLoc Loc, 
PresumedLoc PLoc,
   if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
 FileID CaretFileID = Loc.getExpansionLoc().getFileID();
 bool PrintedRange = false;
+const SourceManager &SM = Loc.getManager();
 
 for (const auto &R : Ranges) {
   // Ignore invalid ranges.
   if (!R.isValid())
 continue;
 
-  auto &SM = Loc.getManager();
   SourceLocation B = SM.getExpansionLoc(R.getBegin());
   CharSourceRange ERange = SM.getExpansionRange(R.getEnd());
   SourceLocation E = ERange.getEnd();
-  bool IsTokenRange = ERange.isTokenRange();
 
-  std::pair BInfo = SM.getDecomposedLoc(B);
-  std::pair EInfo = SM.getDecomposedLoc(E);
-
-  // If the start or end of the range is in another file, just discard
-  // it.
-  if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
+  // If the start or end of the range is in another file, just
+  // discard it.
+  if (SM.getFileID(B) != CaretFileID || SM.getFileID(E) != CaretFileID)
 continue;
 
   // Add in the length of the token, so that we cover multi-char
   // tokens.
   unsigned TokSize = 0;
-  if (IsTokenRange)
+  if (ERange.isTokenRange())
 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
 
   FullSourceLoc BF(B, SM), EF(E, SM);



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


[PATCH] D151093: [clang][Diagnostic] Simplify emitDiagnosticLoc

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc113cbb51005: [clang][Diagnostic][NFC] Simplify 
emitDiagnosticLoc (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151093/new/

https://reviews.llvm.org/D151093

Files:
  clang/lib/Frontend/TextDiagnostic.cpp


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -850,30 +850,26 @@
   if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
 FileID CaretFileID = Loc.getExpansionLoc().getFileID();
 bool PrintedRange = false;
+const SourceManager &SM = Loc.getManager();
 
 for (const auto &R : Ranges) {
   // Ignore invalid ranges.
   if (!R.isValid())
 continue;
 
-  auto &SM = Loc.getManager();
   SourceLocation B = SM.getExpansionLoc(R.getBegin());
   CharSourceRange ERange = SM.getExpansionRange(R.getEnd());
   SourceLocation E = ERange.getEnd();
-  bool IsTokenRange = ERange.isTokenRange();
 
-  std::pair BInfo = SM.getDecomposedLoc(B);
-  std::pair EInfo = SM.getDecomposedLoc(E);
-
-  // If the start or end of the range is in another file, just discard
-  // it.
-  if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
+  // If the start or end of the range is in another file, just
+  // discard it.
+  if (SM.getFileID(B) != CaretFileID || SM.getFileID(E) != CaretFileID)
 continue;
 
   // Add in the length of the token, so that we cover multi-char
   // tokens.
   unsigned TokSize = 0;
-  if (IsTokenRange)
+  if (ERange.isTokenRange())
 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
 
   FullSourceLoc BF(B, SM), EF(E, SM);


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -850,30 +850,26 @@
   if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
 FileID CaretFileID = Loc.getExpansionLoc().getFileID();
 bool PrintedRange = false;
+const SourceManager &SM = Loc.getManager();
 
 for (const auto &R : Ranges) {
   // Ignore invalid ranges.
   if (!R.isValid())
 continue;
 
-  auto &SM = Loc.getManager();
   SourceLocation B = SM.getExpansionLoc(R.getBegin());
   CharSourceRange ERange = SM.getExpansionRange(R.getEnd());
   SourceLocation E = ERange.getEnd();
-  bool IsTokenRange = ERange.isTokenRange();
 
-  std::pair BInfo = SM.getDecomposedLoc(B);
-  std::pair EInfo = SM.getDecomposedLoc(E);
-
-  // If the start or end of the range is in another file, just discard
-  // it.
-  if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
+  // If the start or end of the range is in another file, just
+  // discard it.
+  if (SM.getFileID(B) != CaretFileID || SM.getFileID(E) != CaretFileID)
 continue;
 
   // Add in the length of the token, so that we cover multi-char
   // tokens.
   unsigned TokSize = 0;
-  if (IsTokenRange)
+  if (ERange.isTokenRange())
 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
 
   FullSourceLoc BF(B, SM), EF(E, SM);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D148699: [clang] Mark keywords that have their own parsing rules

2023-05-31 Thread Richard Sandiford via Phabricator via cfe-commits
rsandifo-arm updated this revision to Diff 526944.
rsandifo-arm added a comment.

Update base commit.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148699/new/

https://reviews.llvm.org/D148699

Files:
  clang/include/clang/Basic/Attr.td

Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -311,7 +311,13 @@
   string Namespace = namespace;
 }
 
-class Keyword : Spelling;
+class Keyword
+: Spelling {
+  bit HasOwnParseRules = hasOwnParseRules;
+}
+// A keyword that has its own individual parsing rules.
+class CustomKeyword : Keyword {}
+
 class Pragma : Spelling {
   string Namespace = namespace;
 }
@@ -709,13 +715,13 @@
 }
 
 def Aligned : InheritableAttr {
-  let Spellings = [GCC<"aligned">, Declspec<"align">, Keyword<"alignas">,
-   Keyword<"_Alignas">];
+  let Spellings = [GCC<"aligned">, Declspec<"align">, CustomKeyword<"alignas">,
+   CustomKeyword<"_Alignas">];
   let Args = [AlignedArgument<"Alignment", 1>];
   let Accessors = [Accessor<"isGNU", [GCC<"aligned">]>,
-   Accessor<"isC11", [Keyword<"_Alignas">]>,
-   Accessor<"isAlignas", [Keyword<"alignas">,
-  Keyword<"_Alignas">]>,
+   Accessor<"isC11", [CustomKeyword<"_Alignas">]>,
+   Accessor<"isAlignas", [CustomKeyword<"alignas">,
+  CustomKeyword<"_Alignas">]>,
Accessor<"isDeclspec",[Declspec<"align">]>];
   let Documentation = [Undocumented];
 }
@@ -756,7 +762,7 @@
 
 def AlwaysInline : DeclOrStmtAttr {
   let Spellings = [GCC<"always_inline">, CXX11<"clang", "always_inline">,
-   C2x<"clang", "always_inline">, Keyword<"__forceinline">];
+   C2x<"clang", "always_inline">, CustomKeyword<"__forceinline">];
   let Accessors = [Accessor<"isClangAlwaysInline", [CXX11<"clang", "always_inline">,
 C2x<"clang", "always_inline">]>];
   let Subjects = SubjectList<[Function, Stmt], WarnDiag,
@@ -879,7 +885,7 @@
 }
 
 def AsmLabel : InheritableAttr {
-  let Spellings = [Keyword<"asm">, Keyword<"__asm__">];
+  let Spellings = [CustomKeyword<"asm">, CustomKeyword<"__asm__">];
   let Args = [
 // Label specifies the mangled name for the decl.
 StringArgument<"Label">,
@@ -997,7 +1003,7 @@
 }
 
 def CDecl : DeclOrTypeAttr {
-  let Spellings = [GCC<"cdecl">, Keyword<"__cdecl">, Keyword<"_cdecl">];
+  let Spellings = [GCC<"cdecl">, CustomKeyword<"__cdecl">, CustomKeyword<"_cdecl">];
 //  let Subjects = [Function, ObjCMethod];
   let Documentation = [Undocumented];
 }
@@ -1122,10 +1128,10 @@
 def ConstInit : InheritableAttr {
   // This attribute does not have a C [[]] spelling because it requires the
   // CPlusPlus language option.
-  let Spellings = [Keyword<"constinit">,
+  let Spellings = [CustomKeyword<"constinit">,
Clang<"require_constant_initialization", 0>];
   let Subjects = SubjectList<[GlobalVar], ErrorDiag>;
-  let Accessors = [Accessor<"isConstinit", [Keyword<"constinit">]>];
+  let Accessors = [Accessor<"isConstinit", [CustomKeyword<"constinit">]>];
   let Documentation = [ConstInitDocs];
   let LangOpts = [CPlusPlus];
   let SimpleHandler = 1;
@@ -1276,7 +1282,7 @@
 }
 
 def C11NoReturn : InheritableAttr {
-  let Spellings = [Keyword<"_Noreturn">];
+  let Spellings = [CustomKeyword<"_Noreturn">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let SemaHandler = 0;
   let Documentation = [C11NoReturnDocs];
@@ -1292,7 +1298,7 @@
 // Similar to CUDA, OpenCL attributes do not receive a [[]] spelling because
 // the specification does not expose them with one currently.
 def OpenCLKernel : InheritableAttr {
-  let Spellings = [Keyword<"__kernel">, Keyword<"kernel">];
+  let Spellings = [CustomKeyword<"__kernel">, CustomKeyword<"kernel">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
   let SimpleHandler = 1;
@@ -1316,26 +1322,28 @@
 // This attribute is both a type attribute, and a declaration attribute (for
 // parameter variables).
 def OpenCLAccess : Attr {
-  let Spellings = [Keyword<"__read_only">, Keyword<"read_only">,
-   Keyword<"__write_only">, Keyword<"write_only">,
-   Keyword<"__read_write">, Keyword<"read_write">];
+  let Spellings = [CustomKeyword<"__read_only">, CustomKeyword<"read_only">,
+   CustomKeyword<"__write_only">, CustomKeyword<"write_only">,
+   CustomKeyword<"__read_write">, CustomKeyword<"read_write">];
   let Subjects = SubjectList<[ParmVar, TypedefName], ErrorDiag>;
-  let Accessors = [Accessor<"isReadOnly", [Keyword<"__read_only">,
-   Keyword<"read_only">]>,
- 

[clang-tools-extra] b0bab14 - [clang-tidy] Add check bugprone-unique-ptr-array-mismatch.

2023-05-31 Thread Balázs Kéri via cfe-commits
Author: Balázs Kéri
Date: 2023-05-31T09:55:01+02:00
New Revision: b0bab14b8b5305ddcb4e8b4d8a0e64004fc5425e

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

LOG: [clang-tidy] Add check bugprone-unique-ptr-array-mismatch.

Reviewed By: PiotrZSL

Differential Revision: https://reviews.llvm.org/D151431

Added: 
clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.cpp
clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.h

clang-tools-extra/docs/clang-tidy/checks/bugprone/unique-ptr-array-mismatch.rst

clang-tools-extra/test/clang-tidy/checkers/bugprone/unique-ptr-array-mismatch.cpp

Modified: 
clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 5e9c7d0add4f8..e62e536555c29 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -73,6 +73,7 @@
 #include "UndelegatedConstructorCheck.h"
 #include "UnhandledExceptionAtNewCheck.h"
 #include "UnhandledSelfAssignmentCheck.h"
+#include "UniquePtrArrayMismatchCheck.h"
 #include "UnsafeFunctionsCheck.h"
 #include "UnusedRaiiCheck.h"
 #include "UnusedReturnValueCheck.h"
@@ -207,6 +208,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-unhandled-self-assignment");
 CheckFactories.registerCheck(
 "bugprone-unhandled-exception-at-new");
+CheckFactories.registerCheck(
+"bugprone-unique-ptr-array-mismatch");
 CheckFactories.registerCheck(
 "bugprone-unsafe-functions");
 CheckFactories.registerCheck("bugprone-unused-raii");

diff  --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index e70d1b426a1c6..363d1a85b0ae5 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -69,6 +69,7 @@ add_clang_library(clangTidyBugproneModule
   UndelegatedConstructorCheck.cpp
   UnhandledExceptionAtNewCheck.cpp
   UnhandledSelfAssignmentCheck.cpp
+  UniquePtrArrayMismatchCheck.cpp
   UnsafeFunctionsCheck.cpp
   UnusedRaiiCheck.cpp
   UnusedReturnValueCheck.cpp

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.cpp
new file mode 100644
index 0..8d09b4b320c2c
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.cpp
@@ -0,0 +1,33 @@
+//===--- UniquePtrArrayMismatchCheck.cpp - clang-tidy 
-===//
+//
+// 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 "UniquePtrArrayMismatchCheck.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+UniquePtrArrayMismatchCheck::UniquePtrArrayMismatchCheck(
+StringRef Name, ClangTidyContext *Context)
+: SmartPtrArrayMismatchCheck(Name, Context, "unique") {}
+
+UniquePtrArrayMismatchCheck::SmartPtrClassMatcher
+UniquePtrArrayMismatchCheck::getSmartPointerClassMatcher() const {
+  auto DeleterDecl = classTemplateSpecializationDecl(
+  hasName("::std::default_delete"), templateArgumentCountIs(1),
+  hasTemplateArgument(0, templateArgument(refersToType(
+ qualType(equalsBoundNode(PointerTypeN));
+  return classTemplateSpecializationDecl(
+  hasName("::std::unique_ptr"), templateArgumentCountIs(2),
+  hasTemplateArgument(
+  0, templateArgument(refersToType(qualType().bind(PointerTypeN,
+  hasTemplateArgument(1, templateArgument(refersToType(
+ qualType(hasDeclaration(DeleterDecl));
+}
+
+} // namespace clang::tidy::bugprone

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.h
new file mode 100644
index 0..fb7531ab146c6
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.h
@@ -0,0 +1,34 @@
+//===--- UniquePtrArrayMismatchCheck.h - clang-tidy -*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license info

[PATCH] D151431: [clang-tidy] Add check bugprone-unique-ptr-array-mismatch.

2023-05-31 Thread Balázs Kéri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb0bab14b8b53: [clang-tidy] Add check 
bugprone-unique-ptr-array-mismatch. (authored by balazske).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151431/new/

https://reviews.llvm.org/D151431

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/unique-ptr-array-mismatch.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/unique-ptr-array-mismatch.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/unique-ptr-array-mismatch.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/unique-ptr-array-mismatch.cpp
@@ -0,0 +1,127 @@
+// RUN: %check_clang_tidy %s bugprone-unique-ptr-array-mismatch %t
+
+namespace std {
+
+template struct default_delete {};
+template struct default_delete {};
+
+template>
+class unique_ptr {
+public:
+  explicit unique_ptr(T* p) noexcept;
+  unique_ptr(T* p, Deleter d1 ) noexcept;
+};
+
+template 
+class unique_ptr {
+public:
+  template
+  explicit unique_ptr(U p) noexcept;
+  template
+  unique_ptr(U p, Deleter d1) noexcept;
+};
+
+} // namespace std
+
+struct A {};
+
+using PtrT = std::unique_ptr;
+using PtrTArr = std::unique_ptr;
+
+void f1() {
+  std::unique_ptr P1{new int};
+  std::unique_ptr P2{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr P2{new int[10]};
+  // clang-format off
+  std::unique_ptr<  int  > P3{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr<  int[]  > P3{new int[10]};
+  // clang-format on
+  std::unique_ptr P4(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr P4(new int[10]);
+  new std::unique_ptr(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  std::unique_ptr P5(new int[10]);
+
+  A deleter;
+  std::unique_ptr P6(new int[10], deleter);
+  std::unique_ptr P7(new int[10]);
+  std::default_delete def_del;
+  std::unique_ptr> P8(new int[10], def_del);
+
+  new PtrT(new A[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  new PtrTArr(new A[10]);
+}
+
+void f2() {
+  std::unique_ptr P1(new A);
+  std::unique_ptr P2(new A[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr P2(new A[10]);
+  std::unique_ptr P3(new A[10]);
+}
+
+void f3() {
+  std::unique_ptr P1{new int}, P2{new int[10]}, P3{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-MESSAGES: :[[@LINE-2]]:57: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+}
+
+struct S {
+  std::unique_ptr P1;
+  std::unique_ptr P2{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  std::unique_ptr P3{new int}, P4{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  S() : P1{new int[10]} {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+};
+
+void f_parm(std::unique_ptr);
+
+void f4() {
+  f_parm(std::unique_ptr{new int[10]});
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+}
+
+std::unique_ptr f_ret() {
+  return std::unique_ptr(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+}
+
+template 
+void f_tmpl() {
+  std::unique_ptr P1{new T[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr P1{new T[10]};
+}
+
+void 

[clang] bb6c036 - [clang][Diagnostics][NFC] Use getFileID() directly

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T09:57:16+02:00
New Revision: bb6c036ef378de321d5b7fc0ada317f91c88570d

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

LOG: [clang][Diagnostics][NFC] Use getFileID() directly

Instead of calling getDecomposedLoc() and then only using the FileID.

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 83f254f7de83..a03c1856eaeb 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1144,9 +1144,7 @@ void TextDiagnostic::emitSnippetAndCaret(
   (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
 return;
 
-  // Decompose the location into a FID/Offset pair.
-  std::pair LocInfo = Loc.getDecomposedLoc();
-  FileID FID = LocInfo.first;
+  FileID FID = Loc.getFileID();
   const SourceManager &SM = Loc.getManager();
 
   // Get information about the buffer it points into.



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


[PATCH] D151595: [BOLT][CMake] Redo the build and install targets

2023-05-31 Thread Petr Hosek via Phabricator via cfe-commits
phosek updated this revision to Diff 526948.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151595/new/

https://reviews.llvm.org/D151595

Files:
  bolt/CMakeLists.txt
  bolt/cmake/modules/AddBOLT.cmake
  bolt/test/CMakeLists.txt
  bolt/tools/CMakeLists.txt
  bolt/tools/bat-dump/CMakeLists.txt
  bolt/tools/driver/CMakeLists.txt
  bolt/tools/heatmap/CMakeLists.txt
  bolt/tools/merge-fdata/CMakeLists.txt
  clang/cmake/caches/Fuchsia-stage2.cmake
  llvm/cmake/modules/AddLLVM.cmake

Index: llvm/cmake/modules/AddLLVM.cmake
===
--- llvm/cmake/modules/AddLLVM.cmake
+++ llvm/cmake/modules/AddLLVM.cmake
@@ -2121,7 +2121,7 @@
   if (NOT LLVM_ENABLE_IDE AND NOT ARG_ALWAYS_GENERATE)
 add_llvm_install_targets(install-${name}
  DEPENDS ${name} ${dest}
- COMPONENT ${name}
+ COMPONENT ${component}
  SYMLINK ${dest})
   endif()
 endfunction()
Index: clang/cmake/caches/Fuchsia-stage2.cmake
===
--- clang/cmake/caches/Fuchsia-stage2.cmake
+++ clang/cmake/caches/Fuchsia-stage2.cmake
@@ -6,7 +6,7 @@
 
 set(PACKAGE_VENDOR Fuchsia CACHE STRING "")
 
-set(_FUCHSIA_ENABLE_PROJECTS "clang;clang-tools-extra;lld;llvm;polly")
+set(_FUCHSIA_ENABLE_PROJECTS "bolt;clang;clang-tools-extra;lld;llvm;polly")
 set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING "")
 
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
@@ -328,6 +328,7 @@
   CACHE STRING "")
 
 set(LLVM_Toolchain_DISTRIBUTION_COMPONENTS
+  bolt
   clang
   lld
   clang-apply-replacements
Index: bolt/tools/merge-fdata/CMakeLists.txt
===
--- bolt/tools/merge-fdata/CMakeLists.txt
+++ bolt/tools/merge-fdata/CMakeLists.txt
@@ -8,14 +8,8 @@
   DEPENDS
   intrinsics_gen
 )
-set_target_properties(merge-fdata PROPERTIES FOLDER "BOLT")
 
 add_dependencies(bolt merge-fdata)
-install(PROGRAMS
-  ${CMAKE_BINARY_DIR}/bin/merge-fdata
-  DESTINATION ${CMAKE_INSTALL_BINDIR}
-  COMPONENT bolt
-  )
 
 # Emit relocations for BOLT meta test (bolt/test/runtime/meta-merge-fdata.test)
 if (BOLT_INCLUDE_TESTS AND UNIX AND NOT APPLE)
Index: bolt/tools/heatmap/CMakeLists.txt
===
--- bolt/tools/heatmap/CMakeLists.txt
+++ bolt/tools/heatmap/CMakeLists.txt
@@ -5,7 +5,7 @@
   Support
   )
 
-add_bolt_tool(llvm-bolt-heatmap
+add_bolt_executable(llvm-bolt-heatmap
   heatmap.cpp
   DISABLE_LLVM_LINK_LLVM_DYLIB
   )
@@ -16,5 +16,3 @@
   LLVMBOLTRewrite
   LLVMBOLTUtils
   )
-
-set_target_properties(llvm-bolt-heatmap PROPERTIES FOLDER "BOLT")
Index: bolt/tools/driver/CMakeLists.txt
===
--- bolt/tools/driver/CMakeLists.txt
+++ bolt/tools/driver/CMakeLists.txt
@@ -30,22 +30,6 @@
 add_bolt_tool_symlink(perf2bolt llvm-bolt)
 add_bolt_tool_symlink(llvm-boltdiff llvm-bolt)
 
-set(BOLT_DEPENDS
-  llvm-bolt
-  perf2bolt
-  llvm-boltdiff
-  )
-
-add_custom_target(bolt DEPENDS ${BOLT_DEPENDS})
-install(PROGRAMS
-  ${CMAKE_BINARY_DIR}/bin/llvm-bolt
-  ${CMAKE_BINARY_DIR}/bin/perf2bolt
-  ${CMAKE_BINARY_DIR}/bin/llvm-boltdiff
-  DESTINATION ${CMAKE_INSTALL_BINDIR}
-  COMPONENT bolt
-  )
-add_llvm_install_targets(install-bolt DEPENDS bolt COMPONENT bolt)
-set_target_properties(bolt PROPERTIES FOLDER "BOLT")
-set_target_properties(install-bolt PROPERTIES FOLDER "BOLT")
+add_dependencies(bolt llvm-bolt)
 
-include_directories( ${BOLT_SOURCE_DIR}/lib )
+include_directories(${BOLT_SOURCE_DIR}/lib)
Index: bolt/tools/bat-dump/CMakeLists.txt
===
--- bolt/tools/bat-dump/CMakeLists.txt
+++ bolt/tools/bat-dump/CMakeLists.txt
@@ -3,7 +3,7 @@
   Support
   )
 
-add_llvm_tool(llvm-bat-dump
+add_bolt_executable(llvm-bat-dump
   bat-dump.cpp
 
   DISABLE_LLVM_LINK_LLVM_DYLIB
@@ -13,5 +13,3 @@
   PRIVATE
   LLVMBOLTProfile
   )
-
-set_target_properties(llvm-bat-dump PROPERTIES FOLDER "BOLT")
Index: bolt/tools/CMakeLists.txt
===
--- bolt/tools/CMakeLists.txt
+++ bolt/tools/CMakeLists.txt
@@ -2,16 +2,6 @@
 "Path for binary subdirectory (defaults to '${CMAKE_INSTALL_BINDIR}')")
 mark_as_advanced(BOLT_TOOLS_INSTALL_DIR)
 
-# Move these macros to AddBolt if such a CMake module is ever created.
-
-macro(add_bolt_tool name)
-  llvm_add_tool(BOLT ${ARGV})
-endmacro()
-
-macro(add_bolt_tool_symlink name)
-  llvm_add_tool_symlink(BOLT ${ARGV})
-endmacro()
-
 add_subdirectory(driver)
 add_subdirectory(llvm-bolt-fuzzer)
 add_subdirectory(bat-dump)
Index: bolt/test/CMakeLists.txt
===
--- bolt/test

[PATCH] D151100: [clang][Diagnostics] Merge byte/column mapping functions into one.

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG50f0b8d219cb: [clang][Diagnostics][NFC] Merge byte/column 
mapping functions into one. (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151100/new/

https://reviews.llvm.org/D151100

Files:
  clang/lib/Frontend/TextDiagnostic.cpp

Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -173,7 +173,21 @@
   }
 }
 
-/// This function takes a raw source line and produces a mapping from the bytes
+/// \p BytesOut:
+///  A mapping from columns to the byte of the source line that produced the
+///  character displaying at that column. This is the inverse of \p ColumnsOut.
+///
+/// The last element in the array is the number of bytes in the source string.
+///
+/// example: (given a tabstop of 8)
+///
+///"a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
+///
+///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
+///   display)
+///
+/// \p ColumnsOut:
+///  A mapping from the bytes
 ///  of the printable representation of the line to the columns those printable
 ///  characters will appear at (numbering the first column as 0).
 ///
@@ -195,60 +209,34 @@
 ///
 ///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
 ///   display)
-static void byteToColumn(StringRef SourceLine, unsigned TabStop,
- SmallVectorImpl &out) {
-  out.clear();
+static void genColumnByteMapping(StringRef SourceLine, unsigned TabStop,
+ SmallVectorImpl &BytesOut,
+ SmallVectorImpl &ColumnsOut) {
+  assert(BytesOut.empty());
+  assert(ColumnsOut.empty());
 
   if (SourceLine.empty()) {
-out.resize(1u,0);
+BytesOut.resize(1u, 0);
+ColumnsOut.resize(1u, 0);
 return;
   }
 
-  out.resize(SourceLine.size()+1, -1);
-
-  int columns = 0;
-  size_t i = 0;
-  while (i,bool> res
-  = printableTextForNextCharacter(SourceLine, &i, TabStop);
-columns += llvm::sys::locale::columnWidth(res.first);
-  }
-  out.back() = columns;
-}
-
-/// This function takes a raw source line and produces a mapping from columns
-///  to the byte of the source line that produced the character displaying at
-///  that column. This is the inverse of the mapping produced by byteToColumn()
-///
-/// The last element in the array is the number of bytes in the source string
-///
-/// example: (given a tabstop of 8)
-///
-///"a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
-///
-///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
-///   display)
-static void columnToByte(StringRef SourceLine, unsigned TabStop,
- SmallVectorImpl &out) {
-  out.clear();
+  ColumnsOut.resize(SourceLine.size() + 1, -1);
 
-  if (SourceLine.empty()) {
-out.resize(1u, 0);
-return;
+  int Columns = 0;
+  size_t I = 0;
+  while (I < SourceLine.size()) {
+ColumnsOut[I] = Columns;
+BytesOut.resize(Columns + 1, -1);
+BytesOut.back() = I;
+auto [Str, Printable] =
+printableTextForNextCharacter(SourceLine, &I, TabStop);
+Columns += llvm::sys::locale::columnWidth(Str);
   }
 
-  int columns = 0;
-  size_t i = 0;
-  while (i,bool> res
-  = printableTextForNextCharacter(SourceLine, &i, TabStop);
-columns += llvm::sys::locale::columnWidth(res.first);
-  }
-  out.resize(columns+1, -1);
-  out.back() = i;
+  ColumnsOut.back() = Columns;
+  BytesOut.resize(Columns + 1, -1);
+  BytesOut.back() = I;
 }
 
 namespace {
@@ -256,8 +244,7 @@
   SourceColumnMap(StringRef SourceLine, unsigned TabStop)
   : m_SourceLine(SourceLine) {
 
-::byteToColumn(SourceLine, TabStop, m_byteToColumn);
-::columnToByte(SourceLine, TabStop, m_columnToByte);
+genColumnByteMapping(SourceLine, TabStop, m_columnToByte, m_byteToColumn);
 
 assert(m_byteToColumn.size()==SourceLine.size()+1);
 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 50f0b8d - [clang][Diagnostics][NFC] Merge byte/column mapping functions into one.

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T10:00:08+02:00
New Revision: 50f0b8d219cb1557625ce768ea78670d13671e1d

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

LOG: [clang][Diagnostics][NFC] Merge byte/column mapping functions into one.

They were both only called from one place and did very similar things.
Merge them into one, so we only have to iterate the source line once to
generate the SourceMap.

Differential Revision: https://reviews.llvm.org/D151100

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index a03c1856eaeb..7a2d78b504f8 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -173,7 +173,21 @@ static void expandTabs(std::string &SourceLine, unsigned 
TabStop) {
   }
 }
 
-/// This function takes a raw source line and produces a mapping from the bytes
+/// \p BytesOut:
+///  A mapping from columns to the byte of the source line that produced the
+///  character displaying at that column. This is the inverse of \p ColumnsOut.
+///
+/// The last element in the array is the number of bytes in the source string.
+///
+/// example: (given a tabstop of 8)
+///
+///"a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
+///
+///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
+///   display)
+///
+/// \p ColumnsOut:
+///  A mapping from the bytes
 ///  of the printable representation of the line to the columns those printable
 ///  characters will appear at (numbering the first column as 0).
 ///
@@ -195,60 +209,34 @@ static void expandTabs(std::string &SourceLine, unsigned 
TabStop) {
 ///
 ///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
 ///   display)
-static void byteToColumn(StringRef SourceLine, unsigned TabStop,
- SmallVectorImpl &out) {
-  out.clear();
+static void genColumnByteMapping(StringRef SourceLine, unsigned TabStop,
+ SmallVectorImpl &BytesOut,
+ SmallVectorImpl &ColumnsOut) {
+  assert(BytesOut.empty());
+  assert(ColumnsOut.empty());
 
   if (SourceLine.empty()) {
-out.resize(1u,0);
+BytesOut.resize(1u, 0);
+ColumnsOut.resize(1u, 0);
 return;
   }
 
-  out.resize(SourceLine.size()+1, -1);
-
-  int columns = 0;
-  size_t i = 0;
-  while (i,bool> res
-  = printableTextForNextCharacter(SourceLine, &i, TabStop);
-columns += llvm::sys::locale::columnWidth(res.first);
-  }
-  out.back() = columns;
-}
-
-/// This function takes a raw source line and produces a mapping from columns
-///  to the byte of the source line that produced the character displaying at
-///  that column. This is the inverse of the mapping produced by byteToColumn()
-///
-/// The last element in the array is the number of bytes in the source string
-///
-/// example: (given a tabstop of 8)
-///
-///"a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
-///
-///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
-///   display)
-static void columnToByte(StringRef SourceLine, unsigned TabStop,
- SmallVectorImpl &out) {
-  out.clear();
+  ColumnsOut.resize(SourceLine.size() + 1, -1);
 
-  if (SourceLine.empty()) {
-out.resize(1u, 0);
-return;
+  int Columns = 0;
+  size_t I = 0;
+  while (I < SourceLine.size()) {
+ColumnsOut[I] = Columns;
+BytesOut.resize(Columns + 1, -1);
+BytesOut.back() = I;
+auto [Str, Printable] =
+printableTextForNextCharacter(SourceLine, &I, TabStop);
+Columns += llvm::sys::locale::columnWidth(Str);
   }
 
-  int columns = 0;
-  size_t i = 0;
-  while (i,bool> res
-  = printableTextForNextCharacter(SourceLine, &i, TabStop);
-columns += llvm::sys::locale::columnWidth(res.first);
-  }
-  out.resize(columns+1, -1);
-  out.back() = i;
+  ColumnsOut.back() = Columns;
+  BytesOut.resize(Columns + 1, -1);
+  BytesOut.back() = I;
 }
 
 namespace {
@@ -256,8 +244,7 @@ struct SourceColumnMap {
   SourceColumnMap(StringRef SourceLine, unsigned TabStop)
   : m_SourceLine(SourceLine) {
 
-::byteToColumn(SourceLine, TabStop, m_byteToColumn);
-::columnToByte(SourceLine, TabStop, m_columnToByte);
+genColumnByteMapping(SourceLine, TabStop, m_columnToByte, m_byteToColumn);
 
 assert(m_byteToColumn.size()==SourceLine.size()+1);
 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());



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


[PATCH] D151741: [Lex] Only warn on defining or undefining language-defined builtins

2023-05-31 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

Thanks! +1 from me, this does clear up all the issues I've had - it supersedes 
D151662  and makes the external patch to 
avoid doing `-U__STRICT_ANSI__` unnecessary.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151741/new/

https://reviews.llvm.org/D151741

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


[clang] 543c929 - [clang][Diagnostics][NFC] Remove unused Indentation parameter

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T10:17:03+02:00
New Revision: 543c92969ba867434af6688808998b82496e9dc1

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

LOG: [clang][Diagnostics][NFC] Remove unused Indentation parameter

printWordWrapped() is only called in one place, which passes all
parameters except `Indentation`. So, remove that parameter and use its
default value instead. Also remove the other default parameter values,
since those are unneeded.

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 7a2d78b504f8..74c555e30689 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -590,15 +590,10 @@ static unsigned findEndOfWord(unsigned Start, StringRef 
Str,
 /// Str will be printed. This will be non-zero when part of the first
 /// line has already been printed.
 /// \param Bold if the current text should be bold
-/// \param Indentation the number of spaces to indent any lines beyond
-/// the first line.
 /// \returns true if word-wrapping was required, or false if the
 /// string fit on the first line.
-static bool printWordWrapped(raw_ostream &OS, StringRef Str,
- unsigned Columns,
- unsigned Column = 0,
- bool Bold = false,
- unsigned Indentation = WordWrapIndentation) {
+static bool printWordWrapped(raw_ostream &OS, StringRef Str, unsigned Columns,
+ unsigned Column, bool Bold) {
   const unsigned Length = std::min(Str.find('\n'), Str.size());
   bool TextNormal = true;
 
@@ -630,10 +625,10 @@ static bool printWordWrapped(raw_ostream &OS, StringRef 
Str,
 // This word does not fit on the current line, so wrap to the next
 // line.
 OS << '\n';
-OS.indent(Indentation);
+OS.indent(WordWrapIndentation);
 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
   TextNormal, Bold);
-Column = Indentation + WordLength;
+Column = WordWrapIndentation + WordLength;
 Wrapped = true;
   }
 



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


[clang] 0157815 - [clang][Diagnostics][NFC] Don't create oversized CaretLine

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T10:21:24+02:00
New Revision: 01578153ee8228562d0f64d3847e7fc91573da36

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

LOG: [clang][Diagnostics][NFC] Don't create oversized CaretLine

Instead of creating a CaretLine the size of the SourceLine, just leave
it empty at first, let HighlightRange resize it to fit all the ~, then
resize it to fit the ^. Then we can save ourselves the work to remove
the trailing whitespace again.

Differential Revision: https://reviews.llvm.org/D151286

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 74c555e30689..d285b8873977 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1199,20 +1199,16 @@ void TextDiagnostic::emitSnippetAndCaret(
 // Build the byte to column map.
 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
 
-// Create a line for the caret that is filled with spaces that is the same
-// number of columns as the line of source code.
-std::string CaretLine(sourceColMap.columns(), ' ');
-
+std::string CaretLine;
 // Highlight all of the characters covered by Ranges with ~ characters.
 for (const auto &I : Ranges)
   highlightRange(I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
 
 // Next, insert the caret itself.
 if (CaretLineNo == LineNo) {
-  CaretColNo = sourceColMap.byteToContainingColumn(CaretColNo - 1);
-  if (CaretLine.size() < CaretColNo + 1)
-CaretLine.resize(CaretColNo + 1, ' ');
-  CaretLine[CaretColNo] = '^';
+  size_t Col = sourceColMap.byteToContainingColumn(CaretColNo - 1);
+  CaretLine.resize(std::max(Col + 1, CaretLine.size()), ' ');
+  CaretLine[Col] = '^';
 }
 
 std::string FixItInsertionLine = buildFixItInsertionLine(
@@ -1234,10 +1230,6 @@ void TextDiagnostic::emitSnippetAndCaret(
   CaretLine = ' ' + CaretLine;
 }
 
-// Finally, remove any blank spaces from the end of CaretLine.
-while (!CaretLine.empty() && CaretLine[CaretLine.size() - 1] == ' ')
-  CaretLine.erase(CaretLine.end() - 1);
-
 // Emit what we have computed.
 emitSnippet(SourceLine, MaxLineNoDisplayWidth, DisplayLineNo);
 



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


[PATCH] D151286: [clang][Diagnostics][NFC] Don't create oversized CaretLine

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG01578153ee82: [clang][Diagnostics][NFC] Don't create 
oversized CaretLine (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D151286?vs=524996&id=526952#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151286/new/

https://reviews.llvm.org/D151286

Files:
  clang/lib/Frontend/TextDiagnostic.cpp


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1199,20 +1199,16 @@
 // Build the byte to column map.
 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
 
-// Create a line for the caret that is filled with spaces that is the same
-// number of columns as the line of source code.
-std::string CaretLine(sourceColMap.columns(), ' ');
-
+std::string CaretLine;
 // Highlight all of the characters covered by Ranges with ~ characters.
 for (const auto &I : Ranges)
   highlightRange(I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
 
 // Next, insert the caret itself.
 if (CaretLineNo == LineNo) {
-  CaretColNo = sourceColMap.byteToContainingColumn(CaretColNo - 1);
-  if (CaretLine.size() < CaretColNo + 1)
-CaretLine.resize(CaretColNo + 1, ' ');
-  CaretLine[CaretColNo] = '^';
+  size_t Col = sourceColMap.byteToContainingColumn(CaretColNo - 1);
+  CaretLine.resize(std::max(Col + 1, CaretLine.size()), ' ');
+  CaretLine[Col] = '^';
 }
 
 std::string FixItInsertionLine = buildFixItInsertionLine(
@@ -1234,10 +1230,6 @@
   CaretLine = ' ' + CaretLine;
 }
 
-// Finally, remove any blank spaces from the end of CaretLine.
-while (!CaretLine.empty() && CaretLine[CaretLine.size() - 1] == ' ')
-  CaretLine.erase(CaretLine.end() - 1);
-
 // Emit what we have computed.
 emitSnippet(SourceLine, MaxLineNoDisplayWidth, DisplayLineNo);
 


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1199,20 +1199,16 @@
 // Build the byte to column map.
 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
 
-// Create a line for the caret that is filled with spaces that is the same
-// number of columns as the line of source code.
-std::string CaretLine(sourceColMap.columns(), ' ');
-
+std::string CaretLine;
 // Highlight all of the characters covered by Ranges with ~ characters.
 for (const auto &I : Ranges)
   highlightRange(I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
 
 // Next, insert the caret itself.
 if (CaretLineNo == LineNo) {
-  CaretColNo = sourceColMap.byteToContainingColumn(CaretColNo - 1);
-  if (CaretLine.size() < CaretColNo + 1)
-CaretLine.resize(CaretColNo + 1, ' ');
-  CaretLine[CaretColNo] = '^';
+  size_t Col = sourceColMap.byteToContainingColumn(CaretColNo - 1);
+  CaretLine.resize(std::max(Col + 1, CaretLine.size()), ' ');
+  CaretLine[Col] = '^';
 }
 
 std::string FixItInsertionLine = buildFixItInsertionLine(
@@ -1234,10 +1230,6 @@
   CaretLine = ' ' + CaretLine;
 }
 
-// Finally, remove any blank spaces from the end of CaretLine.
-while (!CaretLine.empty() && CaretLine[CaretLine.size() - 1] == ' ')
-  CaretLine.erase(CaretLine.end() - 1);
-
 // Emit what we have computed.
 emitSnippet(SourceLine, MaxLineNoDisplayWidth, DisplayLineNo);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151789: [test] Add llc to the list of known tools for clang tests (NFCI)

2023-05-31 Thread Sergei Barannikov via Phabricator via cfe-commits
barannikov88 created this revision.
Herald added a project: All.
barannikov88 added a reviewer: erichkeane.
barannikov88 published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Some tests such as CodeGen/2005-09-24-AsmUserPrefix.c use llc. This
change makes sure llc is picked up from the bin directory rather than
from the PATH.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151789

Files:
  clang/test/lit.cfg.py


Index: clang/test/lit.cfg.py
===
--- clang/test/lit.cfg.py
+++ clang/test/lit.cfg.py
@@ -86,17 +86,18 @@
 "c-index-test",
 "clang-diff",
 "clang-format",
-"clang-repl",
+"clang-linker-wrapper",
 "clang-offload-packager",
-"clang-tblgen",
+"clang-repl",
 "clang-scan-deps",
-"opt",
+"clang-tblgen",
+"llc",
 "llvm-ifs",
-"yaml2obj",
-"clang-linker-wrapper",
 "llvm-lto",
 "llvm-lto2",
 "llvm-profdata",
+"opt",
+"yaml2obj",
 ToolSubst(
 "%clang_extdef_map",
 command=FindTool("clang-extdef-mapping"),


Index: clang/test/lit.cfg.py
===
--- clang/test/lit.cfg.py
+++ clang/test/lit.cfg.py
@@ -86,17 +86,18 @@
 "c-index-test",
 "clang-diff",
 "clang-format",
-"clang-repl",
+"clang-linker-wrapper",
 "clang-offload-packager",
-"clang-tblgen",
+"clang-repl",
 "clang-scan-deps",
-"opt",
+"clang-tblgen",
+"llc",
 "llvm-ifs",
-"yaml2obj",
-"clang-linker-wrapper",
 "llvm-lto",
 "llvm-lto2",
 "llvm-profdata",
+"opt",
+"yaml2obj",
 ToolSubst(
 "%clang_extdef_map",
 command=FindTool("clang-extdef-mapping"),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D150549: Move SubtargetFeature.h from MC to TargetParser

2023-05-31 Thread Job Noorman via Phabricator via cfe-commits
jobnoorman added a comment.

In D150549#4380786 , @MaskRay wrote:

> If we are certain this will not be reverted and cause churn, making the 
> header switch in one single patch looks fine to me...

Great. I'm not sure if we can ever be a 100% certain it will not get reverted. 
To increase our chances, I'll wait a bit before landing this. Does anyone else 
have thoughts about this patch?

> I have checked that this patch has migrated things that might be neglected: 
> `unittest` directories, openmp,mlir,clang, etc.

Thanks for checking this!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150549/new/

https://reviews.llvm.org/D150549

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


[clang] 3184fb9 - [clang][Diagnostics] Print empty lines in multiline snippets

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T10:21:24+02:00
New Revision: 3184fb958091f6b119c878e2eab894d799432686

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

LOG: [clang][Diagnostics] Print empty lines in multiline snippets

We should preserve empty lines in output snippets.

Differential Revision: https://reviews.llvm.org/D151301

Added: 
clang/test/Misc/diag-style.cpp

Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index d285b8873977..d2cbb55dea87 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1225,7 +1225,7 @@ void TextDiagnostic::emitSnippetAndCaret(
 // to produce easily machine parsable output.  Add a space before the
 // source line and the caret to make it trivial to tell the main diagnostic
 // line from what the user is intended to see.
-if (DiagOpts->ShowSourceRanges) {
+if (DiagOpts->ShowSourceRanges && !SourceLine.empty()) {
   SourceLine = ' ' + SourceLine;
   CaretLine = ' ' + CaretLine;
 }
@@ -1262,9 +1262,6 @@ void TextDiagnostic::emitSnippetAndCaret(
 void TextDiagnostic::emitSnippet(StringRef SourceLine,
  unsigned MaxLineNoDisplayWidth,
  unsigned LineNo) {
-  if (SourceLine.empty())
-return;
-
   // Emit line number.
   if (MaxLineNoDisplayWidth > 0) {
 unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);

diff  --git a/clang/test/Misc/diag-style.cpp b/clang/test/Misc/diag-style.cpp
new file mode 100644
index ..b12afb2cd923
--- /dev/null
+++ b/clang/test/Misc/diag-style.cpp
@@ -0,0 +1,12 @@
+// RUN: not %clang_cc1 -fsyntax-only %s 2>&1 | FileCheck -strict-whitespace %s
+
+/// empty lines in multi-line diagnostic snippets are preserved.
+static_assert(false &&
+
+  true, "");
+// CHECK: static assertion failed
+// CHECK-NEXT: {{^}}4 | static_assert(false &&{{$}}
+// CHECK-NEXT: {{^}}  |   ^~~~{{$}}
+// CHECK-NEXT: {{^}}5 | {{$}}
+// CHECK-NEXT: {{^}}6 |   true, "");{{$}}
+// CHECK-NEXT: {{^}}  |   {{$}}



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


[PATCH] D151301: [clang][Diagnostics] Print empty lines in multiline snippets

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3184fb958091: [clang][Diagnostics] Print empty lines in 
multiline snippets (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151301/new/

https://reviews.llvm.org/D151301

Files:
  clang/lib/Frontend/TextDiagnostic.cpp
  clang/test/Misc/diag-style.cpp


Index: clang/test/Misc/diag-style.cpp
===
--- /dev/null
+++ clang/test/Misc/diag-style.cpp
@@ -0,0 +1,12 @@
+// RUN: not %clang_cc1 -fsyntax-only %s 2>&1 | FileCheck -strict-whitespace %s
+
+/// empty lines in multi-line diagnostic snippets are preserved.
+static_assert(false &&
+
+  true, "");
+// CHECK: static assertion failed
+// CHECK-NEXT: {{^}}4 | static_assert(false &&{{$}}
+// CHECK-NEXT: {{^}}  |   ^~~~{{$}}
+// CHECK-NEXT: {{^}}5 | {{$}}
+// CHECK-NEXT: {{^}}6 |   true, "");{{$}}
+// CHECK-NEXT: {{^}}  |   {{$}}
Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1225,7 +1225,7 @@
 // to produce easily machine parsable output.  Add a space before the
 // source line and the caret to make it trivial to tell the main diagnostic
 // line from what the user is intended to see.
-if (DiagOpts->ShowSourceRanges) {
+if (DiagOpts->ShowSourceRanges && !SourceLine.empty()) {
   SourceLine = ' ' + SourceLine;
   CaretLine = ' ' + CaretLine;
 }
@@ -1262,9 +1262,6 @@
 void TextDiagnostic::emitSnippet(StringRef SourceLine,
  unsigned MaxLineNoDisplayWidth,
  unsigned LineNo) {
-  if (SourceLine.empty())
-return;
-
   // Emit line number.
   if (MaxLineNoDisplayWidth > 0) {
 unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);


Index: clang/test/Misc/diag-style.cpp
===
--- /dev/null
+++ clang/test/Misc/diag-style.cpp
@@ -0,0 +1,12 @@
+// RUN: not %clang_cc1 -fsyntax-only %s 2>&1 | FileCheck -strict-whitespace %s
+
+/// empty lines in multi-line diagnostic snippets are preserved.
+static_assert(false &&
+
+  true, "");
+// CHECK: static assertion failed
+// CHECK-NEXT: {{^}}4 | static_assert(false &&{{$}}
+// CHECK-NEXT: {{^}}  |   ^~~~{{$}}
+// CHECK-NEXT: {{^}}5 | {{$}}
+// CHECK-NEXT: {{^}}6 |   true, "");{{$}}
+// CHECK-NEXT: {{^}}  |   {{$}}
Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1225,7 +1225,7 @@
 // to produce easily machine parsable output.  Add a space before the
 // source line and the caret to make it trivial to tell the main diagnostic
 // line from what the user is intended to see.
-if (DiagOpts->ShowSourceRanges) {
+if (DiagOpts->ShowSourceRanges && !SourceLine.empty()) {
   SourceLine = ' ' + SourceLine;
   CaretLine = ' ' + CaretLine;
 }
@@ -1262,9 +1262,6 @@
 void TextDiagnostic::emitSnippet(StringRef SourceLine,
  unsigned MaxLineNoDisplayWidth,
  unsigned LineNo) {
-  if (SourceLine.empty())
-return;
-
   // Emit line number.
   if (MaxLineNoDisplayWidth > 0) {
 unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a806b3f - [clang][Diagnostics][NFC] Remove unnecessary StringRef

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T10:21:24+02:00
New Revision: a806b3f49667f3aa0800572b84f91b77654e29fd

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

LOG: [clang][Diagnostics][NFC] Remove unnecessary StringRef

Seems unnecessary to create a StringRef here just so we can drop the
trailing null bytes. We can do that with the std::string we
create anyway.

Differential Revision: https://reviews.llvm.org/D151300

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index d2cbb55dea87..f817ab7d3613 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1187,14 +1187,12 @@ void TextDiagnostic::emitSnippetAndCaret(
 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
   return;
 
-// Trim trailing null-bytes.
-StringRef Line(LineStart, LineEnd - LineStart);
-while (!Line.empty() && Line.back() == '\0' &&
-   (LineNo != CaretLineNo || Line.size() > CaretColNo))
-  Line = Line.drop_back();
-
 // Copy the line of code into an std::string for ease of manipulation.
-std::string SourceLine(Line.begin(), Line.end());
+std::string SourceLine(LineStart, LineEnd);
+// Remove trailing null bytes.
+while (!SourceLine.empty() && SourceLine.back() == '\0' &&
+   (LineNo != CaretLineNo || SourceLine.size() > CaretColNo))
+  SourceLine.pop_back();
 
 // Build the byte to column map.
 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);



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


[PATCH] D151300: [clang][Diagnostics][NFC] Remove unnecessary StringRef

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa806b3f49667: [clang][Diagnostics][NFC] Remove unnecessary 
StringRef (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151300/new/

https://reviews.llvm.org/D151300

Files:
  clang/lib/Frontend/TextDiagnostic.cpp


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1187,14 +1187,12 @@
 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
   return;
 
-// Trim trailing null-bytes.
-StringRef Line(LineStart, LineEnd - LineStart);
-while (!Line.empty() && Line.back() == '\0' &&
-   (LineNo != CaretLineNo || Line.size() > CaretColNo))
-  Line = Line.drop_back();
-
 // Copy the line of code into an std::string for ease of manipulation.
-std::string SourceLine(Line.begin(), Line.end());
+std::string SourceLine(LineStart, LineEnd);
+// Remove trailing null bytes.
+while (!SourceLine.empty() && SourceLine.back() == '\0' &&
+   (LineNo != CaretLineNo || SourceLine.size() > CaretColNo))
+  SourceLine.pop_back();
 
 // Build the byte to column map.
 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -1187,14 +1187,12 @@
 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
   return;
 
-// Trim trailing null-bytes.
-StringRef Line(LineStart, LineEnd - LineStart);
-while (!Line.empty() && Line.back() == '\0' &&
-   (LineNo != CaretLineNo || Line.size() > CaretColNo))
-  Line = Line.drop_back();
-
 // Copy the line of code into an std::string for ease of manipulation.
-std::string SourceLine(Line.begin(), Line.end());
+std::string SourceLine(LineStart, LineEnd);
+// Remove trailing null bytes.
+while (!SourceLine.empty() && SourceLine.back() == '\0' &&
+   (LineNo != CaretLineNo || SourceLine.size() > CaretColNo))
+  SourceLine.pop_back();
 
 // Build the byte to column map.
 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] b5c7892 - [clang][Diagnostics][NFC] Move Buf{Start,End} out of the loop

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T10:21:24+02:00
New Revision: b5c7892d54f8d415e3e0198e067886c825f26e0c

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

LOG: [clang][Diagnostics][NFC] Move Buf{Start,End} out of the loop

They don't change inside the loop.

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index f817ab7d3613..11ae2667dfa8 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1134,6 +1134,8 @@ void TextDiagnostic::emitSnippetAndCaret(
   StringRef BufData = Loc.getBufferData(&Invalid);
   if (Invalid)
 return;
+  const char *BufStart = BufData.data();
+  const char *BufEnd = BufStart + BufData.size();
 
   unsigned CaretLineNo = Loc.getLineNumber();
   unsigned CaretColNo = Loc.getColumnNumber();
@@ -1167,9 +1169,6 @@ void TextDiagnostic::emitSnippetAndCaret(
 
   for (unsigned LineNo = Lines.first; LineNo != Lines.second + 1;
++LineNo, ++DisplayLineNo) {
-const char *BufStart = BufData.data();
-const char *BufEnd = BufStart + BufData.size();
-
 // Rewind from the current position to the start of the line.
 const char *LineStart =
 BufStart +



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


[clang] 895b555 - [clang][Diagnostics][NFC] Move variable decl into if statement

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T10:49:06+02:00
New Revision: 895b55537870cdaf6e4c304a09f4bf01954ccbd6

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

LOG: [clang][Diagnostics][NFC] Move variable decl into if statement

Added: 


Modified: 
clang/lib/Frontend/TextDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 11ae2667dfa8..ad5f1d45cb63 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -773,8 +773,7 @@ void TextDiagnostic::emitDiagnosticLoc(FullSourceLoc Loc, 
PresumedLoc PLoc,
ArrayRef Ranges) {
   if (PLoc.isInvalid()) {
 // At least print the file name if available:
-FileID FID = Loc.getFileID();
-if (FID.isValid()) {
+if (FileID FID = Loc.getFileID(); FID.isValid()) {
   if (const FileEntry *FE = Loc.getFileEntry()) {
 emitFilename(FE->getName(), Loc.getManager());
 OS << ": ";



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


[PATCH] D151753: [Clang][Sema] Do not try to analyze dependent alignment during -Wcast-align

2023-05-31 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added reviewers: erichkeane, shafik.
Fznamznon added a comment.

The change looks reasonable for me, though I'm not experienced in related code. 
Have you checked that it fixes the non-reduced original example?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151753/new/

https://reviews.llvm.org/D151753

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


[PATCH] D148793: [clang-tidy] Implement an include-cleaner check.

2023-05-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:45
+  SourceLocation SymRefLocation;
+  std::string MissingHeaderSpelling;
+};

storing a string instance for header per system reference is expensive (we 
might have many missing-include symbols, and we might have many duplications). 
We can store the a `clang::include_cleaner::Header` in the struct here, and 
call the `spellHeader` when generating the FixIts.



Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:88
+SourceLocation Loc = D->getLocation();
+if (!SM->isWrittenInMainFile(SM->getSpellingLoc(Loc)))
+  continue;

We should use the `getExpansionLoc` rather than the `SpellingLoc` here, 
otherwise we might miss the case like `TEST_F(WalkUsedTest, MultipleProviders) 
{... }` where the decl location is spelled in another file, but the function 
body is spelled in main-file.




Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:89
+if (!SM->isWrittenInMainFile(SM->getSpellingLoc(Loc)))
+  continue;
+MainFileDecls.push_back(D);

and we probably need the same logic to filtering out implicit template 
specialization, similar to 
https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/include-cleaner/lib/Record.cpp#L408-L410.
 

It is fine to leave it in this patch, but please add a FIXME.



Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:130
+  // header mappings. But that's not different than rest of the places.
+  if (ClangTidyCheck::getCurrentMainFile().endswith(PHeader))
+continue;

nit: the prefix `ClangTidyCheck::` qualifier is not needed, you can remove it. 



Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:149
+  for (const auto *Inc : Unused) {
+diag(Inc->HashLocation, "unused include %0")
+<< Inc->quote()

The diagnostic message "unused include ..." seems too short for users to 
understand what's the issue here, it would be better to make it more 
descriptive, in clangd, we emit `included header ... is not used directly`, we 
can follow this pattern.

The same for the missing-includes.



Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h:36
+  IncludeCleanerCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {
+std::optional IgnoreHeaders =

nit: the function body is long, consider moving it to .cpp file.



Comment at: clang-tools-extra/clangd/TidyProvider.cpp:220
+  // include-cleaner is directly integrated in IncludeCleaner.cpp
+  "-misc-include-cleaner",
+

nit: the entry here is under the `Crashing Checks` category, this doesn't seem 
a good fit. Maybe move it right after the above empty string `""`. 



Comment at: clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst:13
+
+.. option:: IgnoreHeader
+

IgnoreHeader => IgnoreHeaders, in the implementation, we use the plural form.  



Comment at: clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp:1
+#include "ClangTidyDiagnosticConsumer.h"
+#include "ClangTidyOptions.h"

nit: missing the license file comment.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148793/new/

https://reviews.llvm.org/D148793

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


[PATCH] D151783: [clang] Use the appropriate definition when checking FunctionDecl::isInlineBuiltinDeclaration

2023-05-31 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo accepted this revision.
mstorsjo added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!

I'm not familiar with the code in question to know whether this really is the 
right thing to do etc, but this fixes my testcase (both the reduced one and the 
full one).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151783/new/

https://reviews.llvm.org/D151783

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


[PATCH] D150427: [AMDGPU] Non hostcall printf support for HIP

2023-05-31 Thread Vikram Hegde via Phabricator via cfe-commits
vikramRH updated this revision to Diff 526963.
vikramRH added a comment.

Handled most review comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150427/new/

https://reviews.llvm.org/D150427

Files:
  clang/include/clang/Basic/TargetOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGGPUBuiltin.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGenHIP/printf_nonhostcall.cpp
  clang/test/Driver/hip-options.hip
  llvm/include/llvm/Transforms/Utils/AMDGPUEmitPrintf.h
  llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp

Index: llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp
===
--- llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp
+++ llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp
@@ -17,6 +17,9 @@
 #include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h"
 #include "llvm/ADT/SparseBitVector.h"
 #include "llvm/Analysis/ValueTracking.h"
+#include "llvm/Support/DataExtractor.h"
+#include "llvm/Support/MD5.h"
+#include "llvm/Support/MathExtras.h"
 
 using namespace llvm;
 
@@ -179,11 +182,7 @@
 
 // Scan the format string to locate all specifiers, and mark the ones that
 // specify a string, i.e, the "%s" specifier with optional '*' characters.
-static void locateCStrings(SparseBitVector<8> &BV, Value *Fmt) {
-  StringRef Str;
-  if (!getConstantStringInfo(Fmt, Str) || Str.empty())
-return;
-
+static void locateCStrings(SparseBitVector<8> &BV, StringRef Str) {
   static const char ConvSpecifiers[] = "diouxXfFeEgGaAcspn";
   size_t SpecPos = 0;
   // Skip the first argument, the format string.
@@ -207,14 +206,305 @@
   }
 }
 
-Value *llvm::emitAMDGPUPrintfCall(IRBuilder<> &Builder,
-  ArrayRef Args) {
+// helper struct to package the string related data
+struct StringData {
+  std::string Str;
+  Value *RealSize = nullptr;
+  Value *AlignedSize = nullptr;
+  bool isConst = true;
+
+  StringData(std::string str, Value *RS, Value *AS, bool IC)
+  : Str(str), RealSize(RS), AlignedSize(AS), isConst(IC) {}
+};
+
+// Calculates frame size required for current printf expansion and allocates
+// space on printf buffer. Printf frame includes following contents
+// [ ControlDWord , format string/Hash , Arguments (each aligned to 8 byte) ]
+static Value *callBufferedPrintfStart(
+IRBuilder<> &Builder, ArrayRef Args, Value *Fmt,
+bool isConstFmtStr, SparseBitVector<8> &SpecIsCString,
+SmallVectorImpl &StringContents, Value *&ArgSize) {
+  Module *M = Builder.GetInsertBlock()->getModule();
+  Value *NonConstStrLen = nullptr;
+  Value *LenWithNull = nullptr;
+  Value *LenWithNullAligned = nullptr;
+  Value *TempAdd = nullptr;
+
+  // First 4 bytes to be reserved for control dword
+  size_t BufSize = 4;
+  if (isConstFmtStr)
+// First 8 bytes of MD5 hash
+BufSize += 8;
+  else {
+LenWithNull = getStrlenWithNull(Builder, Fmt);
+
+// Align the computed length to next 8 byte boundary
+TempAdd = Builder.CreateAdd(LenWithNull,
+ConstantInt::get(LenWithNull->getType(), 7U));
+NonConstStrLen = Builder.CreateAnd(
+TempAdd, ConstantInt::get(LenWithNull->getType(), ~7U));
+
+StringContents.push_back(
+StringData("", LenWithNull, NonConstStrLen, false));
+  }
+
+  for (size_t i = 1; i < Args.size(); i++) {
+if (SpecIsCString.test(i)) {
+  StringRef ArgStr;
+  if (getConstantStringInfo(Args[i], ArgStr)) {
+auto alignedLen = alignTo(ArgStr.size() + 1, 8);
+StringContents.push_back(StringData(
+(ArgStr.str() + '\0'),
+/*RealSize*/ nullptr, /*AlignedSize*/ nullptr, /*isConst*/ true));
+BufSize += alignedLen;
+  } else {
+LenWithNull = getStrlenWithNull(Builder, Args[i]);
+
+// Align the computed length to next 8 byte boundary
+TempAdd = Builder.CreateAdd(
+LenWithNull, ConstantInt::get(LenWithNull->getType(), 7U));
+LenWithNullAligned = Builder.CreateAnd(
+TempAdd, ConstantInt::get(LenWithNull->getType(), ~7U));
+
+if (NonConstStrLen) {
+  auto Val = Builder.CreateAdd(LenWithNullAligned, NonConstStrLen,
+   "cumulativeAdd");
+  NonConstStrLen = Val;
+} else
+  NonConstStrLen = LenWithNullAligned;
+
+StringContents.push_back(
+StringData("", LenWithNull, LenWithNullAligned, false));
+  }
+} else
+  // We end up expanding non string arguments to 8 bytes
+  BufSize += 8;
+  }
+
+  // calculate final size value to be passed to printf_alloc
+  Value *SizeToReserve = ConstantInt::get(Builder.getInt64Ty(), BufSize, false);
+  SmallVector Alloc_args;
+  if (NonConstStrLen)
+SizeToReserve = Builder.CreateAdd(NonConstStrLen, SizeToReserve);
+
+  ArgSize = Builder.CreateTrunc(SizeToReserve, Builder.getInt32Ty());
+  Alloc_args.push_back(ArgSize);
+
+  // call the pr

[PATCH] D150209: [clang][Interp] Add more shift error checking

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 526965.
tbaeder marked an inline comment as done.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150209/new/

https://reviews.llvm.org/D150209

Files:
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.h
  clang/test/AST/Interp/shifts.cpp

Index: clang/test/AST/Interp/shifts.cpp
===
--- clang/test/AST/Interp/shifts.cpp
+++ clang/test/AST/Interp/shifts.cpp
@@ -152,4 +152,39 @@
   constexpr signed int R = (sizeof(unsigned) * 8) + 1;
   constexpr decltype(L) M  = (R > 32 && R < 64) ?  L << R : 0;
   constexpr decltype(L) M2 = (R > 32 && R < 64) ?  L >> R : 0;
+
+
+  constexpr int signedShift() { // cxx17-error {{never produces a constant expression}} \
+// ref-cxx17-error {{never produces a constant expression}}
+return 1024 << 31; // cxx17-warning {{signed shift result}} \
+   // ref-cxx17-warning {{signed shift result}} \
+   // cxx17-note {{signed left shift discards bits}} \
+   // ref-cxx17-note {{signed left shift discards bits}}
+  }
+
+  constexpr int negativeShift() { // cxx17-error {{never produces a constant expression}} \
+  // ref-cxx17-error {{never produces a constant expression}}
+return -1 << 2; // cxx17-warning {{shifting a negative signed value is undefined}} \
+// ref-cxx17-warning {{shifting a negative signed value is undefined}} \
+// cxx17-note {{left shift of negative value -1}} \
+// ref-cxx17-note {{left shift of negative value -1}}
+  }
+
+  constexpr int foo(int a) {
+return -a << 2; // cxx17-note {{left shift of negative value -10}} \
+// ref-cxx17-note {{left shift of negative value -10}} \
+// cxx17-note {{left shift of negative value -2}} \
+// ref-cxx17-note {{left shift of negative value -2}}
+  }
+  static_assert(foo(10)); // cxx17-error {{not an integral constant expression}} \
+  // cxx17-note {{in call to 'foo(10)'}} \
+  // ref-cxx17-error {{not an integral constant expression}} \
+  // ref-cxx17-note {{in call to 'foo(10)'}}
+
+  constexpr int a = -2;
+  static_assert(foo(a));
+  static_assert(foo(-a)); // cxx17-error {{not an integral constant expression}} \
+  // cxx17-note {{in call to 'foo(2)'}} \
+  // ref-cxx17-error {{not an integral constant expression}} \
+  // ref-cxx17-note {{in call to 'foo(2)'}}
 };
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -109,8 +109,9 @@
 bool CheckCtorCall(InterpState &S, CodePtr OpPC, const Pointer &This);
 
 /// Checks if the shift operation is legal.
-template 
-bool CheckShift(InterpState &S, CodePtr OpPC, const RT &RHS, unsigned Bits) {
+template 
+bool CheckShift(InterpState &S, CodePtr OpPC, const LT &LHS, const RT &RHS,
+unsigned Bits) {
   if (RHS.isNegative()) {
 const SourceInfo &Loc = S.Current->getSource(OpPC);
 S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
@@ -126,6 +127,20 @@
 S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
 return false;
   }
+
+  if (LHS.isSigned() && !S.getLangOpts().CPlusPlus20) {
+const Expr *E = S.Current->getExpr(OpPC);
+// C++11 [expr.shift]p2: A signed left shift must have a non-negative
+// operand, and must not overflow the corresponding unsigned type.
+if (LHS.isNegative())
+  S.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS.toAPSInt();
+else if (LHS.toUnsigned().countLeadingZeros() < static_cast(RHS))
+  S.CCEDiag(E, diag::note_constexpr_lshift_discards);
+  }
+
+  // C++2a [expr.shift]p2: [P0907R4]:
+  //E1 << E2 is the unique value congruent to
+  //E1 x 2^E2 module 2^N.
   return true;
 }
 
@@ -1612,7 +1627,7 @@
   const auto &LHS = S.Stk.pop();
   const unsigned Bits = LHS.bitWidth();
 
-  if (!CheckShift(S, OpPC, RHS, Bits))
+  if (!CheckShift(S, OpPC, LHS, RHS, Bits))
 return false;
 
   Integral R;
@@ -1629,7 +1644,7 @@
   const auto &LHS = S.Stk.pop();
   const unsigned Bits = LHS.bitWidth();
 
-  if (!CheckShift(S, OpPC, RHS, Bits))
+  if (!CheckShift(S, OpPC, LHS, RHS, Bits))
 return false;
 
   Integral R;
Index: clang/lib/AST/Interp/Integral.h
===
--- clang/lib/AST/Interp/Integral.h
+++ clang/lib/AST/Interp/Integral.h
@@ -127,7 +127,11 @@
 return Compare(V, RHS.V);
   }
 
-  unsigned countLeadingZeros() const { return llvm::countl_zero(V); }
+  unsigned countLeadingZeros() const {
+if constexpr (!Signed)
+  return llvm::countl_zer

[PATCH] D148793: [clang-tidy] Implement an include-cleaner check.

2023-05-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:170-175
+diag(Inc.SymRefLocation, "missing include %0")
+<< Inc.MissingHeaderSpelling
+<< FixItHint::CreateInsertion(
+   SM->getComposedLoc(SM->getMainFileID(),
+  Replacement->getOffset()),
+   Replacement->getReplacementText());

PiotrZSL wrote:
> Use IncludeInserter::createIncludeInsertion if possible...
> So include style would be properly handled.
`tooling::HeaderIncludes` already handles the include style well (and more). In 
general,  we recommend to use `tooling::headerIncludes` --  it was built for 
generic toolings that need to perform #include manipulations, it has been 
heavily used in clangd/clang-format/clang-include-cleaner etc.

`IncludeInserter::createIncludeInsertion` is an old implementation in 
clang-tidy, and it was built before `tooling::HeaderIncludes` is thing.  In the 
long-term, I think we should probably consider deprecating it and replacing it 
with `tooling::HeaderIncludes`.



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148793/new/

https://reviews.llvm.org/D148793

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


[PATCH] D151088: [flang][hlfir] Separate -emit-fir and -emit-hlfir for flang-new

2023-05-31 Thread Tom Eccles via Phabricator via cfe-commits
tblah added inline comments.



Comment at: flang/include/flang/Frontend/FrontendOptions.h:42
+  /// resulting FIR
+  EmitHLFIRToFIR,
+

awarzynski wrote:
> To me having `EmitFIR` and `EmitHLFIR` would make more sense. With 2 
> dialects, `EmitMLIR` becomes rather confusing (and, I suspect, rarely used).
EmitMLIR emits whichever one Lowering was configured for (depending on the 
-flang-experimental-hlfir flag).

EmitHLFIRToFIR always emits FIR after lowering via HLFIR and running all of the 
passes to convert HLFIR into FIR.

I didn't add EmitFIR and EmitHLFIR because the frontend action is exactly the 
same for these two (run lowering and print out the MLIR it generates).



Comment at: flang/lib/Frontend/FrontendActions.cpp:651
+// Lower using HLFIR then run the FIR to HLFIR pipeline
+void CodeGenAction::lowerHLFIRToFIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");

awarzynski wrote:
> I wouldn't really consider this hook as a separate action. Instead, I'd use 
> it here: 
> https://github.com/llvm/llvm-project/blob/6130c9df99a7a7eb9c6adc118a48f8f2acc534ab/flang/lib/Frontend/FrontendActions.cpp#L917-L920.
>  As in, it basically "tweaks" `EmitMLIR` (which I would rename as `EmitFIR`).
This is very different to `EmitMLIR`.

`EmitMLIR` will print the MLIR produced by lowering (HLFIR or FIR depending 
upon the `-flang-experimental-hlfir` flag).

This action will run lowering, always generating HLFIR. Then it will run the 
HLFIR pass pipeline to lower the HLFIR into FIR, and output that FIR (which 
will be very different to FIR generated directly from lowering without going 
through HLFIR).



Comment at: flang/lib/Frontend/FrontendActions.cpp:652
+void CodeGenAction::lowerHLFIRToFIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");
+

awarzynski wrote:
> This `mlirModule` comes from here: 
> https://github.com/llvm/llvm-project/blob/6130c9df99a7a7eb9c6adc118a48f8f2acc534ab/flang/lib/Frontend/FrontendActions.cpp#L277.
>  That will either be FIR or HLFIR, depending on whether 
> `-flang-experimental-hlfir` was used or not, right?
Yes. In this case, lowering will have always produced HLFIR because we don't 
enter this action unless `-flang-experimental-hlfir` has been specified.



Comment at: flang/lib/Frontend/FrontendActions.cpp:673
+unsigned diagID = ci.getDiagnostics().getCustomDiagID(
+clang::DiagnosticsEngine::Error, "Lowering to LLVM IR failed");
+ci.getDiagnostics().Report(diagID);

awarzynski wrote:
> "Lowering to LLVM IR"? ;-)
Thanks for spotting this


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151088/new/

https://reviews.llvm.org/D151088

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


[PATCH] D150427: [AMDGPU] Non hostcall printf support for HIP

2023-05-31 Thread Vikram Hegde via Phabricator via cfe-commits
vikramRH marked 11 inline comments as done.
vikramRH added inline comments.



Comment at: clang/test/CodeGenHIP/printf_nonhostcall.cpp:64
+// CHECK-NEXT:[[PRINTBUFFNEXTPTR4:%.*]] = getelementptr inbounds i8, ptr 
addrspace(1) [[PRINTBUFFNEXTPTR3]], i64 [[TMP13]]
+// CHECK-NEXT:[[TMP21:%.*]] = ptrtoint ptr [[TMP1]] to i64
+// CHECK-NEXT:store i64 [[TMP21]], ptr addrspace(1) [[PRINTBUFFNEXTPTR4]], 
align 8

arsenm wrote:
> Can directly store the pointer, don't ptrtoint? Should have some other 
> pointer address spaces tested, the spec is quiet on how %p is supposed to 
> work with different sized pointers 
Added few more address space cases in foo2(), do you think we need more ?



Comment at: clang/test/CodeGenHIP/printf_nonhostcall.cpp:228
+  return printf(s, 10);
+}

arsenm wrote:
> Need some vector tests, especially 3 x vectors 
vectors are not yet supported as in the hostcall case since the code currently 
runs for HIP only. I plan to port the OpenCL lowering also here along with 
hostcall support . we would need to extend hostcall and this implementation to 
support vectors as part of the porting activity.



Comment at: llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp:211
+struct StringData {
+  std::string Str = "";
+  bool isConst = true;

arsenm wrote:
> arsenm wrote:
> > Don't need = ""
> Can't you just use the raw StringRef out of getConstantStringInfo
The structure just caches the string calculated from getConstantStringInfo



Comment at: llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp:381
+} else {
+  if (Args[i]->getType()->isDoubleTy())
+WhatToStore.push_back(Args[i]);

arsenm wrote:
> Don't see why isDoubleTy would be special cased here and not part of 
> fitArgInto64Bits
The redundant cast instructions and this case were due to function 
"fitArgInto64Bits", which I reused from hostcall Implementation and did not 
want to modify. This dependency has been removed now and I have inlined the code



Comment at: llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp:458
+auto CreateControlDWord = M->getOrInsertFunction(
+StringRef("__ockl_create_control_dword"), Builder.getInt32Ty(),
+Builder.getInt32Ty(), Int1Ty, Int1Ty);

arsenm wrote:
> sameerds wrote:
> > vikramRH wrote:
> > > arsenm wrote:
> > > > vikramRH wrote:
> > > > > arsenm wrote:
> > > > > > Do we really need another ockl control variable for this? Why isn't 
> > > > > > it a parameter? printf=stdout always 
> > > > > There are certain HIP API's such as "hip_assert" that output to 
> > > > > stderr. currently such API's are supported via hostcalls. Although 
> > > > > this implementation does not currently support the API's ,its kept as 
> > > > > an option. 
> > > > Right but the way to handle that would be a parameter for where to 
> > > > output, not an externally set global 
> > > I am not clear here, you expect additional inputs to device lib function ?
> > @arsenm, this "control word" written into the buffer. In that sense, it is 
> > indeed a parameter passed from device to host as part of the printf packet. 
> > It is not yet another global variable.
> I'm not following why this part requires introducing another call into device 
> libs. It's expanding this not-really defined API. I'd expect this to be a 
> trivial function we can expand inline here and write directly into the 
> parameter buffer?
I started the implementation keeping in mind the device side asserts currenlty 
supported via hostcall. They use explicit calls to such device lib functions in 
their definitions. I could not support them now but these would be required if 
I ever decide to. also I never ended up inlining this call. do you think its 
really necessary ?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150427/new/

https://reviews.llvm.org/D150427

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


[clang] 40c26ec - [clang][Interp] Fix diagnosing uninitialized ctor record arrays

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T11:39:40+02:00
New Revision: 40c26ec48c8a8ec3c72dde912d3d7118917c8e71

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

LOG: [clang][Interp] Fix diagnosing uninitialized ctor record arrays

Differential Revision: https://reviews.llvm.org/D143334

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/test/AST/Interp/cxx20.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 4d331467f8f2e..0479f4c60c16c 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -386,7 +386,7 @@ static bool CheckArrayInitialized(InterpState &S, CodePtr 
OpPC,
   size_t NumElems = CAT->getSize().getZExtValue();
   QualType ElemType = CAT->getElementType();
 
-  if (isa(ElemType.getTypePtr())) {
+  if (ElemType->isRecordType()) {
 const Record *R = BasePtr.getElemRecord();
 for (size_t I = 0; I != NumElems; ++I) {
   Pointer ElemPtr = BasePtr.atIndex(I).narrow();

diff  --git a/clang/test/AST/Interp/cxx20.cpp b/clang/test/AST/Interp/cxx20.cpp
index 2bf935ef2375b..5d9fa90b482ea 100644
--- a/clang/test/AST/Interp/cxx20.cpp
+++ b/clang/test/AST/Interp/cxx20.cpp
@@ -138,8 +138,8 @@ static_assert(!b4); // ref-error {{not an integral constant 
expression}} \
 namespace UninitializedFields {
   class A {
   public:
-int a; // expected-note 2{{subobject declared here}} \
-   // ref-note 2{{subobject declared here}}
+int a; // expected-note 3{{subobject declared here}} \
+   // ref-note 3{{subobject declared here}}
 constexpr A() {}
   };
   constexpr A a; // expected-error {{must be initialized by a constant 
expression}} \
@@ -174,19 +174,15 @@ namespace UninitializedFields {
// ref-error {{must be initialized by a constant 
expression}} \
// ref-note {{subobject 'a' is not initialized}}
 
-
-  // FIXME: These two are currently disabled because the array fields
-  //   cannot be initialized.
-#if 0
   class C3 {
   public:
 A a[2];
 constexpr C3() {}
   };
   constexpr C3 c3; // expected-error {{must be initialized by a constant 
expression}} \
-   // expected-note {{subobject of type 'int' is not 
initialized}} \
+   // expected-note {{subobject 'a' is not initialized}} \
// ref-error {{must be initialized by a constant 
expression}} \
-   // ref-note {{subobject of type 'int' is not initialized}}
+   // ref-note {{subobject 'a' is not initialized}}
 
   class C4 {
   public:
@@ -195,10 +191,9 @@ namespace UninitializedFields {
 constexpr C4(){}
   };
   constexpr C4 c4; // expected-error {{must be initialized by a constant 
expression}} \
-   // expected-note {{subobject of type 'bool' is not 
initialized}} \
+   // expected-note {{subobject 'B' is not initialized}} \
// ref-error {{must be initialized by a constant 
expression}} \
-   // ref-note {{subobject of type 'bool' is not initialized}}
-#endif
+   // ref-note {{subobject 'B' is not initialized}}
 };
 
 namespace ConstThis {



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


[PATCH] D143334: [clang][Interp] Fix diagnosing uninitialized ctor record arrays

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG40c26ec48c8a: [clang][Interp] Fix diagnosing uninitialized 
ctor record arrays (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D143334?vs=494879&id=526970#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D143334/new/

https://reviews.llvm.org/D143334

Files:
  clang/lib/AST/Interp/Interp.cpp
  clang/test/AST/Interp/cxx20.cpp


Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -138,8 +138,8 @@
 namespace UninitializedFields {
   class A {
   public:
-int a; // expected-note 2{{subobject declared here}} \
-   // ref-note 2{{subobject declared here}}
+int a; // expected-note 3{{subobject declared here}} \
+   // ref-note 3{{subobject declared here}}
 constexpr A() {}
   };
   constexpr A a; // expected-error {{must be initialized by a constant 
expression}} \
@@ -174,19 +174,15 @@
// ref-error {{must be initialized by a constant 
expression}} \
// ref-note {{subobject 'a' is not initialized}}
 
-
-  // FIXME: These two are currently disabled because the array fields
-  //   cannot be initialized.
-#if 0
   class C3 {
   public:
 A a[2];
 constexpr C3() {}
   };
   constexpr C3 c3; // expected-error {{must be initialized by a constant 
expression}} \
-   // expected-note {{subobject of type 'int' is not 
initialized}} \
+   // expected-note {{subobject 'a' is not initialized}} \
// ref-error {{must be initialized by a constant 
expression}} \
-   // ref-note {{subobject of type 'int' is not initialized}}
+   // ref-note {{subobject 'a' is not initialized}}
 
   class C4 {
   public:
@@ -195,10 +191,9 @@
 constexpr C4(){}
   };
   constexpr C4 c4; // expected-error {{must be initialized by a constant 
expression}} \
-   // expected-note {{subobject of type 'bool' is not 
initialized}} \
+   // expected-note {{subobject 'B' is not initialized}} \
// ref-error {{must be initialized by a constant 
expression}} \
-   // ref-note {{subobject of type 'bool' is not initialized}}
-#endif
+   // ref-note {{subobject 'B' is not initialized}}
 };
 
 namespace ConstThis {
Index: clang/lib/AST/Interp/Interp.cpp
===
--- clang/lib/AST/Interp/Interp.cpp
+++ clang/lib/AST/Interp/Interp.cpp
@@ -386,7 +386,7 @@
   size_t NumElems = CAT->getSize().getZExtValue();
   QualType ElemType = CAT->getElementType();
 
-  if (isa(ElemType.getTypePtr())) {
+  if (ElemType->isRecordType()) {
 const Record *R = BasePtr.getElemRecord();
 for (size_t I = 0; I != NumElems; ++I) {
   Pointer ElemPtr = BasePtr.atIndex(I).narrow();


Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -138,8 +138,8 @@
 namespace UninitializedFields {
   class A {
   public:
-int a; // expected-note 2{{subobject declared here}} \
-   // ref-note 2{{subobject declared here}}
+int a; // expected-note 3{{subobject declared here}} \
+   // ref-note 3{{subobject declared here}}
 constexpr A() {}
   };
   constexpr A a; // expected-error {{must be initialized by a constant expression}} \
@@ -174,19 +174,15 @@
// ref-error {{must be initialized by a constant expression}} \
// ref-note {{subobject 'a' is not initialized}}
 
-
-  // FIXME: These two are currently disabled because the array fields
-  //   cannot be initialized.
-#if 0
   class C3 {
   public:
 A a[2];
 constexpr C3() {}
   };
   constexpr C3 c3; // expected-error {{must be initialized by a constant expression}} \
-   // expected-note {{subobject of type 'int' is not initialized}} \
+   // expected-note {{subobject 'a' is not initialized}} \
// ref-error {{must be initialized by a constant expression}} \
-   // ref-note {{subobject of type 'int' is not initialized}}
+   // ref-note {{subobject 'a' is not initialized}}
 
   class C4 {
   public:
@@ -195,10 +191,9 @@
 constexpr C4(){}
   };
   constexpr C4 c4; // expected-error {{must be initialized by a constant expression}} \
-   // expected-note {{subobject of type 'bool' is not initialized}} \
+   // expected-note {{subobject 'B' is not initialized}} \
// ref-error {{must be initialized by a constant expression}} \
-   // ref-note {{su

[PATCH] D150427: [AMDGPU] Non hostcall printf support for HIP

2023-05-31 Thread Vikram Hegde via Phabricator via cfe-commits
vikramRH marked 2 inline comments as done.
vikramRH added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1030
   NegFlag>;
+def mprintf_kind_EQ : Joined<["-"], "mprintf-kind=">, Group,
+  HelpText<"Specify the printf lowering scheme (AMDGPU only), allowed values 
are "

arsenm wrote:
> I'm a bit worried this is introducing a side-ABI option not captured in the 
> triple or at least module flags 
I did not understand the concern here. I agree The usage of option itself is 
not the most robust solution and it would have been better if we could do this 
without user intervention. but I do not see ways to do that now (atleast not 
immediately).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150427/new/

https://reviews.llvm.org/D150427

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


[clang] ac5c996 - [clang] Mark keywords that have their own parsing rules

2023-05-31 Thread Richard Sandiford via cfe-commits
Author: Richard Sandiford
Date: 2023-05-31T10:43:10+01:00
New Revision: ac5c996d5aaab5f4508531e815e7ee408284e968

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

LOG: [clang] Mark keywords that have their own parsing rules

This patch retroactively classifies all existing keyword attributes
as “custom” keyword attributes, in the sense that the keywords have
their own custom parsing rules.  A follow-on patch will add an
alternative type of keyword.

No functional change intended.

Differential Revision: https://reviews.llvm.org/D148699

Added: 


Modified: 
clang/include/clang/Basic/Attr.td

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 8507e6513769..63593dd2e822 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -311,7 +311,13 @@ class C2x
   string Namespace = namespace;
 }
 
-class Keyword : Spelling;
+class Keyword
+: Spelling {
+  bit HasOwnParseRules = hasOwnParseRules;
+}
+// A keyword that has its own individual parsing rules.
+class CustomKeyword : Keyword {}
+
 class Pragma : Spelling {
   string Namespace = namespace;
 }
@@ -709,13 +715,13 @@ def ArmBuiltinAlias : InheritableAttr, 
TargetSpecificAttr {
 }
 
 def Aligned : InheritableAttr {
-  let Spellings = [GCC<"aligned">, Declspec<"align">, Keyword<"alignas">,
-   Keyword<"_Alignas">];
+  let Spellings = [GCC<"aligned">, Declspec<"align">, CustomKeyword<"alignas">,
+   CustomKeyword<"_Alignas">];
   let Args = [AlignedArgument<"Alignment", 1>];
   let Accessors = [Accessor<"isGNU", [GCC<"aligned">]>,
-   Accessor<"isC11", [Keyword<"_Alignas">]>,
-   Accessor<"isAlignas", [Keyword<"alignas">,
-  Keyword<"_Alignas">]>,
+   Accessor<"isC11", [CustomKeyword<"_Alignas">]>,
+   Accessor<"isAlignas", [CustomKeyword<"alignas">,
+  CustomKeyword<"_Alignas">]>,
Accessor<"isDeclspec",[Declspec<"align">]>];
   let Documentation = [Undocumented];
 }
@@ -756,7 +762,7 @@ def AlignNatural : InheritableAttr {
 
 def AlwaysInline : DeclOrStmtAttr {
   let Spellings = [GCC<"always_inline">, CXX11<"clang", "always_inline">,
-   C2x<"clang", "always_inline">, Keyword<"__forceinline">];
+   C2x<"clang", "always_inline">, 
CustomKeyword<"__forceinline">];
   let Accessors = [Accessor<"isClangAlwaysInline", [CXX11<"clang", 
"always_inline">,
 C2x<"clang", 
"always_inline">]>];
   let Subjects = SubjectList<[Function, Stmt], WarnDiag,
@@ -879,7 +885,7 @@ def AVRSignal : InheritableAttr, 
TargetSpecificAttr {
 }
 
 def AsmLabel : InheritableAttr {
-  let Spellings = [Keyword<"asm">, Keyword<"__asm__">];
+  let Spellings = [CustomKeyword<"asm">, CustomKeyword<"__asm__">];
   let Args = [
 // Label specifies the mangled name for the decl.
 StringArgument<"Label">,
@@ -997,7 +1003,7 @@ def CarriesDependency : InheritableParamAttr {
 }
 
 def CDecl : DeclOrTypeAttr {
-  let Spellings = [GCC<"cdecl">, Keyword<"__cdecl">, Keyword<"_cdecl">];
+  let Spellings = [GCC<"cdecl">, CustomKeyword<"__cdecl">, 
CustomKeyword<"_cdecl">];
 //  let Subjects = [Function, ObjCMethod];
   let Documentation = [Undocumented];
 }
@@ -1122,10 +1128,10 @@ def Const : InheritableAttr {
 def ConstInit : InheritableAttr {
   // This attribute does not have a C [[]] spelling because it requires the
   // CPlusPlus language option.
-  let Spellings = [Keyword<"constinit">,
+  let Spellings = [CustomKeyword<"constinit">,
Clang<"require_constant_initialization", 0>];
   let Subjects = SubjectList<[GlobalVar], ErrorDiag>;
-  let Accessors = [Accessor<"isConstinit", [Keyword<"constinit">]>];
+  let Accessors = [Accessor<"isConstinit", [CustomKeyword<"constinit">]>];
   let Documentation = [ConstInitDocs];
   let LangOpts = [CPlusPlus];
   let SimpleHandler = 1;
@@ -1276,7 +1282,7 @@ def SYCLSpecialClass: InheritableAttr {
 }
 
 def C11NoReturn : InheritableAttr {
-  let Spellings = [Keyword<"_Noreturn">];
+  let Spellings = [CustomKeyword<"_Noreturn">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let SemaHandler = 0;
   let Documentation = [C11NoReturnDocs];
@@ -1292,7 +1298,7 @@ def CXX11NoReturn : InheritableAttr {
 // Similar to CUDA, OpenCL attributes do not receive a [[]] spelling because
 // the specification does not expose them with one currently.
 def OpenCLKernel : InheritableAttr {
-  let Spellings = [Keyword<"__kernel">, Keyword<"kernel">];
+  let Spellings = [CustomKeyword<"__kernel">, CustomKeyword<"kernel">];
   let Subjects = SubjectList<[Funct

[clang-tools-extra] 301eb6b - [clang] Add support for “regular” keyword attributes

2023-05-31 Thread Richard Sandiford via cfe-commits
Author: Richard Sandiford
Date: 2023-05-31T10:43:10+01:00
New Revision: 301eb6b68f30074ee3a90e2dfbd11dfd87076323

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

LOG: [clang] Add support for “regular” keyword attributes

Platform-specific language extensions often want to provide a way of
indicating that certain functions should be called in a different way,
compiled in a different way, or otherwise treated differently from a
“normal” function.  Honoring these indications is often required for
correctness, rather being than an optimization/QoI thing.

If a function declaration has a property P that matters for correctness,
it will be ODR-incompatible with a function that does not have property P.
If a function type has a property P that affects the calling convention,
it will not be two-way compatible with a function type that does not
have property P.  These properties therefore affect language semantics.
That in turn means that they cannot be treated as standard [[]]
attributes.

Until now, many of these properties have been specified using GNU-style
attributes instead.  GNU attributes have traditionally been more lax
than standard attributes, with many of them having semantic meaning.
Examples include calling conventions and the vector_size attribute.

However, there is a big drawback to using GNU attributes for semantic
information: compilers that don't understand the attributes will
(by default) emit a warning rather than an error.  They will go on to
compile the code as though the attributes weren't present, which will
inevitably lead to wrong code in most cases.  For users who live
dangerously and disable the warning, this wrong code could even be
generated silently.

A more robust approach would be to specify the properties using
keywords, which older compilers would then reject.  Some vendor-specific
extensions have already taken this approach.  But traditionally, each
such keyword has been treated as a language extension in its own right.
This has three major drawbacks:

(1) The parsing rules need to be kept up-to-date as the language evolves.

(2) There are often corner cases that similar extensions handle differently.

(3) Each extension requires more custom code than a standard attribute.

The underlying problem for all three is that, unlike for true attributes,
there is no established template that extensions can reuse.  The purpose
of this patch series is to try to provide such a template.

One option would have been to pick an existing keyword and do whatever
that keyword does.  The problem with that is that most keywords only
apply to specific kinds of types, kinds of decls, etc., and so the
parsing rules are (for good reason) not generally applicable to all
types and decls.

Really, the “only” thing wrong with using standard attributes is that
standard attributes cannot affect semantics.  In all other respects
they provide exactly what we need: a well-defined grammar that evolves
with the language, clear rules about what an attribute appertains to,
and so on.

This series therefore adds keyword “attributes” that can appear
exactly where a standard attribute can appear and that appertain
to exactly what a standard attribute would appertain to.  The link is
mechanical and no opt-outs or variations are allowed.  This should
make the keywords predictable for programmers who are already
familiar with standard attributes.

This does mean that these keywords will be accepted for parsing purposes
in many more places than necessary.  Inappropriate uses will then be
diagnosed during semantic analysis.  However, the compiler would need
to reject the keywords in those positions whatever happens, and treating
them as ostensible attributes shouldn't be any worse than the alternative.
In some cases it might even be better.  For example, SME's
__arm_streaming attribute would make conceptual sense as a statement
attribute, so someone who takes a “try-it-and-see” approach might write:

  __arm_streaming { …block-of-code…; }

In fact, we did consider supporting this originally.  The reason for
rejecting it was that it was too difficult to implement, rather than
because it didn't make conceptual sense.

One slight disadvantage of the keyword-based approach is that it isn't
possible to use #pragma clang attribute with the keywords.  Perhaps we
could add support for that in future, if it turns out to be useful.

For want of a better term, I've called the new attributes "regular"
keyword attributes (in the sense that their parsing is regular wrt
standard attributes), as opposed to "custom" keyword attributes that
have their own parsing rules.

This patch adds the Attr.td support for regular keyword attributes.
Adding an attribute with a RegularKeyword spelling causes tablegen
to define the associated tokens and to record that attributes created
with that syntax are regula

[PATCH] D148699: [clang] Mark keywords that have their own parsing rules

2023-05-31 Thread Richard Sandiford via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGac5c996d5aaa: [clang] Mark keywords that have their own 
parsing rules (authored by rsandifo-arm).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148699/new/

https://reviews.llvm.org/D148699

Files:
  clang/include/clang/Basic/Attr.td

Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -311,7 +311,13 @@
   string Namespace = namespace;
 }
 
-class Keyword : Spelling;
+class Keyword
+: Spelling {
+  bit HasOwnParseRules = hasOwnParseRules;
+}
+// A keyword that has its own individual parsing rules.
+class CustomKeyword : Keyword {}
+
 class Pragma : Spelling {
   string Namespace = namespace;
 }
@@ -709,13 +715,13 @@
 }
 
 def Aligned : InheritableAttr {
-  let Spellings = [GCC<"aligned">, Declspec<"align">, Keyword<"alignas">,
-   Keyword<"_Alignas">];
+  let Spellings = [GCC<"aligned">, Declspec<"align">, CustomKeyword<"alignas">,
+   CustomKeyword<"_Alignas">];
   let Args = [AlignedArgument<"Alignment", 1>];
   let Accessors = [Accessor<"isGNU", [GCC<"aligned">]>,
-   Accessor<"isC11", [Keyword<"_Alignas">]>,
-   Accessor<"isAlignas", [Keyword<"alignas">,
-  Keyword<"_Alignas">]>,
+   Accessor<"isC11", [CustomKeyword<"_Alignas">]>,
+   Accessor<"isAlignas", [CustomKeyword<"alignas">,
+  CustomKeyword<"_Alignas">]>,
Accessor<"isDeclspec",[Declspec<"align">]>];
   let Documentation = [Undocumented];
 }
@@ -756,7 +762,7 @@
 
 def AlwaysInline : DeclOrStmtAttr {
   let Spellings = [GCC<"always_inline">, CXX11<"clang", "always_inline">,
-   C2x<"clang", "always_inline">, Keyword<"__forceinline">];
+   C2x<"clang", "always_inline">, CustomKeyword<"__forceinline">];
   let Accessors = [Accessor<"isClangAlwaysInline", [CXX11<"clang", "always_inline">,
 C2x<"clang", "always_inline">]>];
   let Subjects = SubjectList<[Function, Stmt], WarnDiag,
@@ -879,7 +885,7 @@
 }
 
 def AsmLabel : InheritableAttr {
-  let Spellings = [Keyword<"asm">, Keyword<"__asm__">];
+  let Spellings = [CustomKeyword<"asm">, CustomKeyword<"__asm__">];
   let Args = [
 // Label specifies the mangled name for the decl.
 StringArgument<"Label">,
@@ -997,7 +1003,7 @@
 }
 
 def CDecl : DeclOrTypeAttr {
-  let Spellings = [GCC<"cdecl">, Keyword<"__cdecl">, Keyword<"_cdecl">];
+  let Spellings = [GCC<"cdecl">, CustomKeyword<"__cdecl">, CustomKeyword<"_cdecl">];
 //  let Subjects = [Function, ObjCMethod];
   let Documentation = [Undocumented];
 }
@@ -1122,10 +1128,10 @@
 def ConstInit : InheritableAttr {
   // This attribute does not have a C [[]] spelling because it requires the
   // CPlusPlus language option.
-  let Spellings = [Keyword<"constinit">,
+  let Spellings = [CustomKeyword<"constinit">,
Clang<"require_constant_initialization", 0>];
   let Subjects = SubjectList<[GlobalVar], ErrorDiag>;
-  let Accessors = [Accessor<"isConstinit", [Keyword<"constinit">]>];
+  let Accessors = [Accessor<"isConstinit", [CustomKeyword<"constinit">]>];
   let Documentation = [ConstInitDocs];
   let LangOpts = [CPlusPlus];
   let SimpleHandler = 1;
@@ -1276,7 +1282,7 @@
 }
 
 def C11NoReturn : InheritableAttr {
-  let Spellings = [Keyword<"_Noreturn">];
+  let Spellings = [CustomKeyword<"_Noreturn">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let SemaHandler = 0;
   let Documentation = [C11NoReturnDocs];
@@ -1292,7 +1298,7 @@
 // Similar to CUDA, OpenCL attributes do not receive a [[]] spelling because
 // the specification does not expose them with one currently.
 def OpenCLKernel : InheritableAttr {
-  let Spellings = [Keyword<"__kernel">, Keyword<"kernel">];
+  let Spellings = [CustomKeyword<"__kernel">, CustomKeyword<"kernel">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
   let Documentation = [Undocumented];
   let SimpleHandler = 1;
@@ -1316,26 +1322,28 @@
 // This attribute is both a type attribute, and a declaration attribute (for
 // parameter variables).
 def OpenCLAccess : Attr {
-  let Spellings = [Keyword<"__read_only">, Keyword<"read_only">,
-   Keyword<"__write_only">, Keyword<"write_only">,
-   Keyword<"__read_write">, Keyword<"read_write">];
+  let Spellings = [CustomKeyword<"__read_only">, CustomKeyword<"read_only">,
+   CustomKeyword<"__write_only">, CustomKeyword<"write_only">,
+   CustomKeyword<"__read_write">, CustomKeyword<"read_write">];
   let Subjects = SubjectList<[ParmVar, TypedefName], ErrorDiag>;
-  let Accessors = [Accessor<"isReadOnly", [Keyword<"__read_only"

[clang] 33ee5c4 - [clang] Add Parse and Sema support for RegularKeyword attributes

2023-05-31 Thread Richard Sandiford via cfe-commits
Author: Richard Sandiford
Date: 2023-05-31T10:43:10+01:00
New Revision: 33ee5c4663465022ffe288817968e90064d88a09

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

LOG: [clang] Add Parse and Sema support for RegularKeyword attributes

This patch adds the Parse and Sema support for RegularKeyword attributes,
following on from a previous patch that added Attr.td support.

The patch is quite large.  However, nothing outside the tests is
specific to the first RegularKeyword attribute (__arm_streaming).
The patch should therefore be a one-off, up-front cost.  Other
attributes just need an entry in Attr.td and the usual Sema support.

The approach taken in the patch is that the keywords can be used with
any language version.  If standard attributes were added in language
version Y, the keyword rules for version Xhttps://reviews.llvm.org/D148702

Added: 
clang/test/Parser/c2x-attribute-keywords.c
clang/test/Parser/c2x-attribute-keywords.m
clang/test/Parser/cxx0x-keyword-attributes.cpp

Modified: 
clang/examples/Attribute/Attribute.cpp
clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
clang/include/clang/Basic/DiagnosticCommonKinds.td
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/DeclSpec.h
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Parse/ParseExprCXX.cpp
clang/lib/Parse/ParsePragma.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Parse/ParseTentative.cpp
clang/lib/Parse/Parser.cpp
clang/lib/Sema/ParsedAttr.cpp
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaStmtAttr.cpp
clang/lib/Sema/SemaType.cpp
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/examples/Attribute/Attribute.cpp 
b/clang/examples/Attribute/Attribute.cpp
index 24b95dde4e559..008da2e18e44f 100644
--- a/clang/examples/Attribute/Attribute.cpp
+++ b/clang/examples/Attribute/Attribute.cpp
@@ -43,7 +43,7 @@ struct ExampleAttrInfo : public ParsedAttrInfo {
 // This attribute appertains to functions only.
 if (!isa(D)) {
   S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type_str)
-  << Attr << "functions";
+  << Attr << Attr.isRegularKeywordAttribute() << "functions";
   return false;
 }
 return true;

diff  --git a/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp 
b/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
index 21460e4f6bd06..12d4c311586e6 100644
--- a/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
+++ b/clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
@@ -169,7 +169,7 @@ struct CallSuperAttrInfo : public ParsedAttrInfo {
 const auto *TheMethod = dyn_cast_or_null(D);
 if (!TheMethod || !TheMethod->isVirtual()) {
   S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type_str)
-  << Attr << "virtual functions";
+  << Attr << Attr.isRegularKeywordAttribute() << "virtual functions";
   return false;
 }
 MarkedMethods.insert(TheMethod);

diff  --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td 
b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index 42d8a0abfbceb..eb1649cc238a5 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -121,7 +121,7 @@ def note_pragma_entered_here : Note<"#pragma entered here">;
 def note_decl_hiding_tag_type : Note<
   "%1 %0 is hidden by a non-type declaration of %0 here">;
 def err_attribute_not_type_attr : Error<
-  "%0 attribute cannot be applied to types">;
+  "%0%select{ attribute|}1 cannot be applied to types">;
 def err_enum_template : Error<"enumeration cannot be a template">;
 
 def warn_cxx20_compat_consteval : Warning<
@@ -175,6 +175,8 @@ def warn_unknown_attribute_ignored : Warning<
   "unknown attribute %0 ignored">, InGroup;
 def warn_attribute_ignored : Warning<"%0 attribute ignored">,
   InGroup;
+def err_keyword_not_supported_on_target : Error<
+  "%0 is not supported on this target">;
 def err_use_of_tag_name_without_tag : Error<
   "must use '%1' tag to refer to type %0%select{| in this scope}2">;
 

diff  --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 5d5048a7d2c04..d015628db7f23 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -733,10 +733,12 @@ def ext_using_attribute_ns : ExtWarn<
 def err_using_attribute_ns_conflict : Error<
   "attribute with scope specifier cannot follow default scope sp

[PATCH] D148700: [clang] Add support for “regular” keyword attributes

2023-05-31 Thread Richard Sandiford via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG301eb6b68f30: [clang] Add support for “regular” keyword 
attributes (authored by rsandifo-arm).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148700/new/

https://reviews.llvm.org/D148700

Files:
  clang-tools-extra/pseudo/lib/grammar/CMakeLists.txt
  clang/docs/InternalsManual.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/AttributeCommonInfo.h
  clang/include/clang/Basic/CMakeLists.txt
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Basic/TokenKinds.h
  clang/include/clang/Lex/Token.h
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/unittests/AST/AttrTest.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp
  clang/utils/TableGen/TableGen.cpp
  clang/utils/TableGen/TableGenBackends.h

Index: clang/utils/TableGen/TableGenBackends.h
===
--- clang/utils/TableGen/TableGenBackends.h
+++ clang/utils/TableGen/TableGenBackends.h
@@ -43,6 +43,8 @@
llvm::raw_ostream &OS);
 void EmitClangAttrPCHRead(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 void EmitClangAttrPCHWrite(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
+void EmitClangAttrTokenKinds(llvm::RecordKeeper &Records,
+ llvm::raw_ostream &OS);
 void EmitClangAttrHasAttrImpl(llvm::RecordKeeper &Records,
   llvm::raw_ostream &OS);
 void EmitClangAttrSpellingListIndex(llvm::RecordKeeper &Records,
Index: clang/utils/TableGen/TableGen.cpp
===
--- clang/utils/TableGen/TableGen.cpp
+++ clang/utils/TableGen/TableGen.cpp
@@ -35,6 +35,7 @@
   GenClangAttrSubjectMatchRuleList,
   GenClangAttrPCHRead,
   GenClangAttrPCHWrite,
+  GenClangAttrTokenKinds,
   GenClangAttrHasAttributeImpl,
   GenClangAttrSpellingListIndex,
   GenClangAttrASTVisitor,
@@ -135,6 +136,8 @@
"Generate clang PCH attribute reader"),
 clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
"Generate clang PCH attribute writer"),
+clEnumValN(GenClangAttrTokenKinds, "gen-clang-attr-token-kinds",
+   "Generate a list of attribute-related clang tokens"),
 clEnumValN(GenClangAttrHasAttributeImpl,
"gen-clang-attr-has-attribute-impl",
"Generate a clang attribute spelling list"),
@@ -324,6 +327,9 @@
   case GenClangAttrPCHWrite:
 EmitClangAttrPCHWrite(Records, OS);
 break;
+  case GenClangAttrTokenKinds:
+EmitClangAttrTokenKinds(Records, OS);
+break;
   case GenClangAttrHasAttributeImpl:
 EmitClangAttrHasAttrImpl(Records, OS);
 break;
Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2381,6 +2381,11 @@
   OS << "#endif // CLANG_ATTR_ACCEPTS_EXPR_PACK\n\n";
 }
 
+static bool isRegularKeywordAttribute(const FlattenedSpelling &S) {
+  return (S.variety() == "Keyword" &&
+  !S.getSpellingRecord().getValueAsBit("HasOwnParseRules"));
+}
+
 static void emitFormInitializer(raw_ostream &OS,
 const FlattenedSpelling &Spelling,
 StringRef SpellingIndex) {
@@ -2388,7 +2393,9 @@
   (Spelling.variety() == "Keyword" && Spelling.name() == "alignas");
   OS << "{AttributeCommonInfo::AS_" << Spelling.variety() << ", "
  << SpellingIndex << ", " << (IsAlignas ? "true" : "false")
- << " /*IsAlignas*/}";
+ << " /*IsAlignas*/, "
+ << (isRegularKeywordAttribute(Spelling) ? "true" : "false")
+ << " /*IsRegularKeywordAttribute*/}";
 }
 
 static void emitAttributes(RecordKeeper &Records, raw_ostream &OS,
@@ -3407,6 +3414,26 @@
   OS << ".Default(0);\n";
 }
 
+// Emits the list of tokens for regular keyword attributes.
+void EmitClangAttrTokenKinds(RecordKeeper &Records, raw_ostream &OS) {
+  emitSourceFileHeader("A list of tokens generated from the attribute"
+   " definitions",
+   OS);
+  // Assume for now that the same token is not used in multiple regular
+  // keyword attributes.
+  for (auto *R : Records.getAllDerivedDefinitions("Attr"))
+for (const auto &S : GetFlattenedSpellings(*R))
+  if (isRegularKeywordAttribute(S)) {
+if (!R->getValueAsListOfDefs("Args").empty())
+  PrintError(R->getLoc(),
+ "RegularKeyword attributes with arguments are not "
+ "yet supported");
+OS << "KE

[PATCH] D148702: [clang] Add Parse and Sema support for RegularKeyword attributes

2023-05-31 Thread Richard Sandiford via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG33ee5c466346: [clang] Add Parse and Sema support for 
RegularKeyword attributes (authored by rsandifo-arm).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148702/new/

https://reviews.llvm.org/D148702

Files:
  clang/examples/Attribute/Attribute.cpp
  clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/DeclSpec.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Parse/ParseTentative.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/ParsedAttr.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaStmtAttr.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/Parser/c2x-attribute-keywords.c
  clang/test/Parser/c2x-attribute-keywords.m
  clang/test/Parser/cxx0x-keyword-attributes.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3882,7 +3882,8 @@
   OS << "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
   OS << "const Decl *D) const override {\n";
   OS << "  S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
-  OS << "<< AL << D->getLocation();\n";
+  OS << "<< AL << AL.isRegularKeywordAttribute() << "
+"D->getLocation();\n";
   OS << "  return false;\n";
   OS << "}\n\n";
 }
@@ -3911,7 +3912,7 @@
 OS << (Warn ? "warn_attribute_wrong_decl_type_str"
 : "err_attribute_wrong_decl_type_str");
 OS << ")\n";
-OS << "  << Attr << ";
+OS << "  << Attr << Attr.isRegularKeywordAttribute() << ";
 OS << CalculateDiagnostic(*SubjectObj) << ";\n";
 OS << "return false;\n";
 OS << "  }\n";
@@ -3926,7 +3927,8 @@
   OS << "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
   OS << "const Stmt *St) const override {\n";
   OS << "  S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
-  OS << "<< AL << St->getBeginLoc();\n";
+  OS << "<< AL << AL.isRegularKeywordAttribute() << "
+"St->getBeginLoc();\n";
   OS << "  return false;\n";
   OS << "}\n\n";
 }
@@ -3945,7 +3947,7 @@
 OS << (Warn ? "warn_attribute_wrong_decl_type_str"
 : "err_attribute_wrong_decl_type_str");
 OS << ")\n";
-OS << "  << Attr << ";
+OS << "  << Attr << Attr.isRegularKeywordAttribute() << ";
 OS << CalculateDiagnostic(*SubjectObj) << ";\n";
 OS << "return false;\n";
 OS << "  }\n";
@@ -4016,7 +4018,8 @@
 for (const std::string &A : DeclAttrs) {
   OS << "if (const auto *A = D->getAttr<" << A << ">()) {\n";
   OS << "  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
- << " << AL << A;\n";
+ << " << AL << A << (AL.isRegularKeywordAttribute() ||"
+ << " A->isRegularKeywordAttribute());\n";
   OS << "  S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
   OS << "  \nreturn false;\n";
   OS << "}\n";
@@ -4037,7 +4040,8 @@
 << ">()) {\n";
 MergeDeclOS << "  S.Diag(First->getLocation(), "
 << "diag::err_attributes_are_not_compatible) << First << "
-<< "Second;\n";
+<< "Second << (First->isRegularKeywordAttribute() || "
+<< "Second->isRegularKeywordAttribute());\n";
 MergeDeclOS << "  S.Diag(Second->getLocation(), "
 << "diag::note_conflicting_attribute);\n";
 MergeDeclOS << "  return false;\n";
@@ -4077,7 +4081,8 @@
 MergeStmtOS << "  if (Iter != C.end()) {\n";
 MergeStmtOS << "S.Diag((*Iter)->getLocation(), "
 << "diag::err_attributes_are_not_compatible) << *Iter << "
-<< "Second;\n";
+<< "Second << ((*Iter)->isRegularKeywordAttribute() || "
+<< "Second->isRegularKeywordAttribute());\n";
 MergeStmtOS << "S.Diag(Second->getLocation(), "
 << "diag::note_conflicting_attribute);\n";
 MergeStmtOS << "return false;\n";
Index: clang/test/Parser/cxx0x-keyword-attributes.cpp
===
--- /dev/null
+++ clang/test/Parser/cxx0x-keyword-attributes.cpp
@@ -0,0 +1,345 @@
+// RUN: %clang_cc1 -fcxx-exceptions -fdeclspec 

[clang] da836b3 - [clang][Interp] Track frame depth

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T12:08:03+02:00
New Revision: da836b36bc3540d21c947a95474d2bb6cc458951

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

LOG: [clang][Interp] Track frame depth

Save the depth of each InterpFrame and bail out if we're too deep.

Differential Revision: https://reviews.llvm.org/D148614

Added: 
clang/test/AST/Interp/depth-limit.cpp
clang/test/AST/Interp/depth-limit2.cpp

Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/InterpFrame.cpp
clang/lib/AST/Interp/InterpFrame.h
clang/lib/AST/Interp/InterpState.cpp
clang/lib/AST/Interp/InterpState.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 0479f4c60c16..3798146b32d1 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -341,6 +341,17 @@ bool CheckCallable(InterpState &S, CodePtr OpPC, const 
Function *F) {
   return true;
 }
 
+bool CheckCallDepth(InterpState &S, CodePtr OpPC) {
+  if ((S.Current->getDepth() + 1) > S.getLangOpts().ConstexprCallDepth) {
+S.FFDiag(S.Current->getSource(OpPC),
+ diag::note_constexpr_depth_limit_exceeded)
+<< S.getLangOpts().ConstexprCallDepth;
+return false;
+  }
+
+  return true;
+}
+
 bool CheckThis(InterpState &S, CodePtr OpPC, const Pointer &This) {
   if (!This.isZero())
 return true;

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 64bdd872221a..fd5ce3c32596 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -88,6 +88,10 @@ bool CheckInit(InterpState &S, CodePtr OpPC, const Pointer 
&Ptr);
 /// Checks if a method can be called.
 bool CheckCallable(InterpState &S, CodePtr OpPC, const Function *F);
 
+/// Checks if calling the currently active function would exceed
+/// the allowed call depth.
+bool CheckCallDepth(InterpState &S, CodePtr OpPC);
+
 /// Checks the 'this' pointer.
 bool CheckThis(InterpState &S, CodePtr OpPC, const Pointer &This);
 
@@ -158,7 +162,6 @@ enum class ArithOp { Add, Sub };
 template ::T>
 bool Ret(InterpState &S, CodePtr &PC, APValue &Result) {
-  S.CallStackDepth--;
   const T &Ret = S.Stk.pop();
 
   assert(S.Current->getFrameOffset() == S.Stk.size() && "Invalid frame");
@@ -181,8 +184,6 @@ bool Ret(InterpState &S, CodePtr &PC, APValue &Result) {
 
 template 
 inline bool RetVoid(InterpState &S, CodePtr &PC, APValue &Result) {
-  S.CallStackDepth--;
-
   assert(S.Current->getFrameOffset() == S.Stk.size() && "Invalid frame");
   if (Builtin || !S.checkingPotentialConstantExpression())
 S.Current->popArgs();
@@ -1598,6 +1599,9 @@ inline bool Call(InterpState &S, CodePtr OpPC, const 
Function *Func) {
   if (!CheckCallable(S, OpPC, Func))
 return false;
 
+  if (!CheckCallDepth(S, OpPC))
+return false;
+
   auto NewFrame = std::make_unique(S, Func, OpPC);
   InterpFrame *FrameBefore = S.Current;
   S.Current = NewFrame.get();

diff  --git a/clang/lib/AST/Interp/InterpFrame.cpp 
b/clang/lib/AST/Interp/InterpFrame.cpp
index e20f283c2855..14b55bea8820 100644
--- a/clang/lib/AST/Interp/InterpFrame.cpp
+++ b/clang/lib/AST/Interp/InterpFrame.cpp
@@ -23,8 +23,8 @@ using namespace clang::interp;
 
 InterpFrame::InterpFrame(InterpState &S, const Function *Func,
  InterpFrame *Caller, CodePtr RetPC)
-: Caller(Caller), S(S), Func(Func), RetPC(RetPC),
-  ArgSize(Func ? Func->getArgSize() : 0),
+: Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),
+  RetPC(RetPC), ArgSize(Func ? Func->getArgSize() : 0),
   Args(static_cast(S.Stk.top())), FrameOffset(S.Stk.size()) {
   if (!Func)
 return;

diff  --git a/clang/lib/AST/Interp/InterpFrame.h 
b/clang/lib/AST/Interp/InterpFrame.h
index c0f4825096be..7988e74a61fe 100644
--- a/clang/lib/AST/Interp/InterpFrame.h
+++ b/clang/lib/AST/Interp/InterpFrame.h
@@ -15,7 +15,6 @@
 
 #include "Frame.h"
 #include "Program.h"
-#include "State.h"
 #include 
 #include 
 
@@ -120,6 +119,8 @@ class InterpFrame final : public Frame {
   const Expr *getExpr(CodePtr PC) const;
   SourceLocation getLocation(CodePtr PC) const;
 
+  unsigned getDepth() const { return Depth; }
+
 private:
   /// Returns an original argument from the stack.
   template  const T &stackRef(unsigned Offset) const {
@@ -145,6 +146,8 @@ class InterpFrame final : public Frame {
 private:
   /// Reference to the interpreter state.
   InterpState &S;
+  /// Depth of this frame.
+  unsigned Depth;
   /// Reference to the function being executed.
   const Function *Func;
   /// Current object pointer for methods.

diff  --git a/clang/lib/AST/Interp/InterpState.cpp 
b/clang/lib/AST/Interp/InterpState.cpp
index 6ae4ecd78c0f..bd7daf38796c 

[PATCH] D148614: [clang][Interp] Add frame depth checking

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGda836b36bc35: [clang][Interp] Track frame depth (authored by 
tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148614/new/

https://reviews.llvm.org/D148614

Files:
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpFrame.cpp
  clang/lib/AST/Interp/InterpFrame.h
  clang/lib/AST/Interp/InterpState.cpp
  clang/lib/AST/Interp/InterpState.h
  clang/test/AST/Interp/depth-limit.cpp
  clang/test/AST/Interp/depth-limit2.cpp

Index: clang/test/AST/Interp/depth-limit2.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/depth-limit2.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -fconstexpr-depth 2 -verify %s
+// RUN: %clang_cc1 -fconstexpr-depth 2 -verify=ref %s
+
+
+constexpr int func() {
+  return 12;
+}
+
+constexpr int foo() {
+  return func(); // expected-note {{exceeded maximum depth of 2 calls}} \
+ // ref-note {{exceeded maximum depth of 2 calls}}
+}
+
+constexpr int bar() {
+  return foo(); // expected-note {{in call to 'foo()'}} \
+// ref-note {{in call to 'foo()'}}
+}
+
+static_assert(bar() == 12); // expected-error {{not an integral constant expression}} \
+// expected-note {{in call to 'bar()'}} \
+// ref-error {{not an integral constant expression}} \
+// ref-note {{in call to 'bar()'}}
+
Index: clang/test/AST/Interp/depth-limit.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/depth-limit.cpp
@@ -0,0 +1,35 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -fconstexpr-depth 100 -verify %s
+// RUN: %clang_cc1 -fconstexpr-depth 100 -verify=ref %s
+
+constexpr int f(int a) {
+  if (a == 100)
+return 1 / 0; // expected-warning {{division by zero is undefined}} \
+  // ref-warning {{division by zero is undefined}}
+
+  return f(a + 1); // ref-note {{exceeded maximum depth of 100 calls}} \
+   // ref-note {{in call to 'f(99)'}} \
+   // ref-note {{in call to 'f(98)'}} \
+   // ref-note {{in call to 'f(97)'}} \
+   // ref-note {{in call to 'f(96)'}} \
+   // ref-note {{in call to 'f(95)'}} \
+   // ref-note {{skipping 90 calls in backtrace}} \
+   // ref-note {{in call to 'f(4)'}} \
+   // ref-note {{in call to 'f(3)'}} \
+   // ref-note {{in call to 'f(2)'}} \
+   // ref-note {{in call to 'f(1)'}} \
+   // expected-note {{exceeded maximum depth of 100 calls}} \
+   // expected-note {{in call to 'f(99)'}} \
+   // expected-note {{in call to 'f(98)'}} \
+   // expected-note {{in call to 'f(97)'}} \
+   // expected-note {{in call to 'f(96)'}} \
+   // expected-note {{in call to 'f(95)'}} \
+   // expected-note {{skipping 90 calls in backtrace}} \
+   // expected-note {{in call to 'f(4)'}} \
+   // expected-note {{in call to 'f(3)'}} \
+   // expected-note {{in call to 'f(2)'}} \
+   // expected-note {{in call to 'f(1)'}}
+}
+static_assert(f(0) == 100); // ref-error {{not an integral constant expression}} \
+// ref-note {{in call to 'f(0)'}} \
+// expected-error {{not an integral constant expression}} \
+// expected-note {{in call to 'f(0)'}}
Index: clang/lib/AST/Interp/InterpState.h
===
--- clang/lib/AST/Interp/InterpState.h
+++ clang/lib/AST/Interp/InterpState.h
@@ -15,6 +15,7 @@
 
 #include "Context.h"
 #include "Function.h"
+#include "InterpFrame.h"
 #include "InterpStack.h"
 #include "State.h"
 #include "clang/AST/APValue.h"
@@ -41,7 +42,9 @@
   // Stack frame accessors.
   Frame *getSplitFrame() { return Parent.getCurrentFrame(); }
   Frame *getCurrentFrame() override;
-  unsigned getCallStackDepth() override { return CallStackDepth; }
+  unsigned getCallStackDepth() override {
+return Current ? (Current->getDepth() + 1) : 1;
+  }
   const Frame *getBottomFrame() const override {
 return Parent.getBottomFrame();
   }
@@ -103,8 +106,6 @@
   Context &Ctx;
   /// The current frame.
   InterpFrame *Current = nullptr;
-  /// Call stack depth.
-  unsigned CallStackDepth;
 };
 
 } // namespace interp
Index: clang/lib/AST/Interp/InterpState.cpp
===
--- clang/lib/AST/Interp/InterpState.cpp
+++ clang/lib/AST/Interp/InterpState.cpp
@@ -17,8 +17,7 @@
 
 InterpState::InterpState(State &

[clang] 722fc7e - [clang][Interp] Add missing static_assert messages

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T12:28:22+02:00
New Revision: 722fc7e7ff8672d9b6b1493a28b850775082948e

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

LOG: [clang][Interp] Add missing static_assert messages

Added: 


Modified: 
clang/test/AST/Interp/depth-limit.cpp
clang/test/AST/Interp/depth-limit2.cpp

Removed: 




diff  --git a/clang/test/AST/Interp/depth-limit.cpp 
b/clang/test/AST/Interp/depth-limit.cpp
index 3e8a29c569ce..a6d5e56b141c 100644
--- a/clang/test/AST/Interp/depth-limit.cpp
+++ b/clang/test/AST/Interp/depth-limit.cpp
@@ -29,7 +29,7 @@ constexpr int f(int a) {
// expected-note {{in call to 'f(2)'}} \
// expected-note {{in call to 'f(1)'}}
 }
-static_assert(f(0) == 100); // ref-error {{not an integral constant 
expression}} \
-// ref-note {{in call to 'f(0)'}} \
-// expected-error {{not an integral constant 
expression}} \
-// expected-note {{in call to 'f(0)'}}
+static_assert(f(0) == 100, ""); // ref-error {{not an integral constant 
expression}} \
+// ref-note {{in call to 'f(0)'}} \
+// expected-error {{not an integral constant 
expression}} \
+// expected-note {{in call to 'f(0)'}}

diff  --git a/clang/test/AST/Interp/depth-limit2.cpp 
b/clang/test/AST/Interp/depth-limit2.cpp
index 614472c68ba9..3f6e64a5cf67 100644
--- a/clang/test/AST/Interp/depth-limit2.cpp
+++ b/clang/test/AST/Interp/depth-limit2.cpp
@@ -16,8 +16,8 @@ constexpr int bar() {
 // ref-note {{in call to 'foo()'}}
 }
 
-static_assert(bar() == 12); // expected-error {{not an integral constant 
expression}} \
-// expected-note {{in call to 'bar()'}} \
-// ref-error {{not an integral constant 
expression}} \
-// ref-note {{in call to 'bar()'}}
+static_assert(bar() == 12, ""); // expected-error {{not an integral constant 
expression}} \
+// expected-note {{in call to 'bar()'}} \
+// ref-error {{not an integral constant 
expression}} \
+// ref-note {{in call to 'bar()'}}
 



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


[PATCH] D151730: [WIP][RISCV] Support target attribute for function

2023-05-31 Thread Piyou Chen via Phabricator via cfe-commits
BeMg updated this revision to Diff 526988.
BeMg added a comment.

update


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151730/new/

https://reviews.llvm.org/D151730

Files:
  clang/include/clang/Basic/TargetInfo.h
  clang/lib/Basic/Targets/RISCV.cpp
  clang/lib/Basic/Targets/RISCV.h
  clang/test/CodeGen/RISCV/riscv-func-attr-target.c
  llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp

Index: llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp
===
--- llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp
+++ llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp
@@ -34,6 +34,7 @@
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCSymbol.h"
 #include "llvm/MC/TargetRegistry.h"
+#include "llvm/Support/RISCVISAInfo.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
 
@@ -44,6 +45,10 @@
 STATISTIC(RISCVNumInstrsCompressed,
   "Number of RISC-V Compressed instructions emitted");
 
+namespace llvm {
+extern const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures];
+} // namespace llvm
+
 namespace {
 class RISCVAsmPrinter : public AsmPrinter {
   const RISCVSubtarget *STI;
@@ -82,6 +87,8 @@
   void emitEndOfAsmFile(Module &M) override;
 
   void emitFunctionEntryLabel() override;
+  void emitDirectiveOptionArch();
+  bool isSameAttribute();
 
 private:
   void emitAttributes();
@@ -232,11 +239,44 @@
   return false;
 }
 
+void RISCVAsmPrinter::emitDirectiveOptionArch() {
+  RISCVTargetStreamer &RTS =
+  static_cast(*OutStreamer->getTargetStreamer());
+  std::vector NeedEmitStdOption;
+  const MCSubtargetInfo &MCSTI = *TM.getMCSubtargetInfo();
+  for (auto Feature : RISCVFeatureKV) {
+if (STI->hasFeature(Feature.Value) && !MCSTI.hasFeature(Feature.Value) &&
+llvm::RISCVISAInfo::isSupportedExtensionFeature(Feature.Key))
+  NeedEmitStdOption.push_back(Feature.Key);
+  }
+
+  bool PrefixEmitted = false;
+  unsigned NeedEmitStdOptionSize = NeedEmitStdOption.size();
+  for (unsigned i = 0; i < NeedEmitStdOptionSize; i++) {
+RTS.emitDirectiveOptionArchPlus(NeedEmitStdOption[i], PrefixEmitted,
+i < NeedEmitStdOptionSize - 1);
+  }
+}
+
+bool RISCVAsmPrinter::isSameAttribute() {
+  const MCSubtargetInfo &MCSTI = *TM.getMCSubtargetInfo();
+  return MCSTI.getFeatureBits() == STI->getFeatureBits();
+}
+
 bool RISCVAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
   STI = &MF.getSubtarget();
+  RISCVTargetStreamer &RTS =
+  static_cast(*OutStreamer->getTargetStreamer());
+  if (!isSameAttribute()) {
+RTS.emitDirectiveOptionPush();
+emitDirectiveOptionArch();
+  }
 
   SetupMachineFunction(MF);
   emitFunctionBody();
+
+  if (!isSameAttribute())
+RTS.emitDirectiveOptionPop();
   return false;
 }
 
Index: clang/test/CodeGen/RISCV/riscv-func-attr-target.c
===
--- /dev/null
+++ clang/test/CodeGen/RISCV/riscv-func-attr-target.c
@@ -0,0 +1,114 @@
+// REQUIRES: riscv-registered-target
+// RUN: %clang -target riscv64 -march=rv64g -S %s -o - | FileCheck %s --check-prefix=CHECK-ASM
+// RUN: %clang -target riscv64 -march=rv64g -emit-llvm -S %s -o - | FileCheck %s --check-prefix=CHECK-IR
+
+// clang-format off
+// CHECK-ASM: .option push
+// CHECK-ASM-NEXT: .optionarch,   +c, +v, +zve32f, +zve32x, +zve64d, +zve64f, +zve64x, +zvl128b, +zvl32b, +zvl64b
+// CHECK-ASM-LABEL: test1
+// CHECK-ASM: .option pop
+__attribute__((target("arch=rv64g,+c,+v"))) void test1 () {}
+
+// CHECK-ASM: .option push
+// CHECK-ASM-NEXT: .optionarch,   +c
+// CHECK-ASM-LABEL: test2
+// CHECK-ASM: .option pop
+__attribute__((target("arch=rv64gc"))) void test2 () {}
+
+// CHECK-ASM: .option push
+// CHECK-ASM-NEXT: .optionarch,   +c
+// CHECK-ASM-LABEL: test3
+// CHECK-ASM: .option pop
+__attribute__((target("arch=+c"))) void test3 () {}
+
+// CHECK-ASM: .option push
+// CHECK-ASM-NEXT: .optionarch,   +v, +zve32f, +zve32x, +zve64d, +zve64f, +zve64x, +zvl128b, +zvl32b, +zvl64b
+// CHECK-ASM-LABEL: test4
+// CHECK-ASM: .option pop
+__attribute__((target("arch=+v"))) void test4 () {}
+
+// CHECK-ASM: .option push
+// CHECK-ASM-NEXT: .optionarch,   +experimental-zihintntl
+// CHECK-ASM-LABEL: test5
+// CHECK-ASM: .option pop
+__attribute__((target("arch=+experimental-zihintntl"))) void test5 () {}
+
+// CHECK-ASM-LABEL: test7
+// CHECK-ASM-NOT: .option pop
+// CHECK-IR: void @test7() #4 
+__attribute__((target("cpu=rocket-rv64"))) void test7 () {}
+
+// CHECK-ASM-LABEL: test8
+// CHECK-ASM-NOT: .option pop
+// CHECK-IR: void @test8() #5
+__attribute__((target("tune=rocket-rv64"))) void test8 () {}
+
+// CHECK-ASM: .option push
+// CHECK-ASM-NEXT: .optionarch,   +c
+// CHECK-ASM-LABEL: test9
+// CHECK-ASM: .option pop
+// CHECK-IR: void @test9() #6
+__attribute__((target("cpu=rocket-rv64,arch=+c"))) void test9 () {}
+
+// CHECK-AS

[clang] 81522a0 - [clang][Interp] Optionally cast comparison result to non-bool

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T13:01:01+02:00
New Revision: 81522a012accfcc6bbf4dfa21a793aea6e4e532a

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

LOG: [clang][Interp] Optionally cast comparison result to non-bool

Our comparison opcodes always produce a Boolean value and push it on the
stack. However, the result of such a comparison in C is int, so the
later code expects an integer value on the stack.

Work around this problem by casting the boolean value to int in those
cases. This is not ideal for C however. The comparison is usually
wrapped in a IntegerToBool cast anyway.

Differential Revision: https://reviews.llvm.org/D149645

Added: 
clang/test/AST/Interp/c.c

Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index df7c4a72f21a..24663a15bcd0 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -237,19 +237,31 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
   if (!visit(LHS) || !visit(RHS))
 return false;
 
+  // For languages such as C, cast the result of one
+  // of our comparision opcodes to T (which is usually int).
+  auto MaybeCastToBool = [this, T, BO](bool Result) {
+if (!Result)
+  return false;
+if (DiscardResult)
+  return this->emitPop(*T, BO);
+if (T != PT_Bool)
+  return this->emitCast(PT_Bool, *T, BO);
+return true;
+  };
+
   switch (BO->getOpcode()) {
   case BO_EQ:
-return Discard(this->emitEQ(*LT, BO));
+return MaybeCastToBool(this->emitEQ(*LT, BO));
   case BO_NE:
-return Discard(this->emitNE(*LT, BO));
+return MaybeCastToBool(this->emitNE(*LT, BO));
   case BO_LT:
-return Discard(this->emitLT(*LT, BO));
+return MaybeCastToBool(this->emitLT(*LT, BO));
   case BO_LE:
-return Discard(this->emitLE(*LT, BO));
+return MaybeCastToBool(this->emitLE(*LT, BO));
   case BO_GT:
-return Discard(this->emitGT(*LT, BO));
+return MaybeCastToBool(this->emitGT(*LT, BO));
   case BO_GE:
-return Discard(this->emitGE(*LT, BO));
+return MaybeCastToBool(this->emitGE(*LT, BO));
   case BO_Sub:
 if (BO->getType()->isFloatingType())
   return Discard(this->emitSubf(getRoundingMode(BO), BO));

diff  --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c
new file mode 100644
index ..248494c95f5e
--- /dev/null
+++ b/clang/test/AST/Interp/c.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+/// expected-no-diagnostics
+/// ref-no-diagnostics
+
+_Static_assert(1, "");
+_Static_assert(0 != 1, "");
+_Static_assert(1.0 == 1.0, "");
+_Static_assert( (5 > 4) + (3 > 2) == 2, "");



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


[PATCH] D149645: [clang][Interp] Optionally cast comparison result to non-bool

2023-05-31 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG81522a012acc: [clang][Interp] Optionally cast comparison 
result to non-bool (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D149645?vs=518707&id=526989#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D149645/new/

https://reviews.llvm.org/D149645

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/c.c


Index: clang/test/AST/Interp/c.c
===
--- /dev/null
+++ clang/test/AST/Interp/c.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+/// expected-no-diagnostics
+/// ref-no-diagnostics
+
+_Static_assert(1, "");
+_Static_assert(0 != 1, "");
+_Static_assert(1.0 == 1.0, "");
+_Static_assert( (5 > 4) + (3 > 2) == 2, "");
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -237,19 +237,31 @@
   if (!visit(LHS) || !visit(RHS))
 return false;
 
+  // For languages such as C, cast the result of one
+  // of our comparision opcodes to T (which is usually int).
+  auto MaybeCastToBool = [this, T, BO](bool Result) {
+if (!Result)
+  return false;
+if (DiscardResult)
+  return this->emitPop(*T, BO);
+if (T != PT_Bool)
+  return this->emitCast(PT_Bool, *T, BO);
+return true;
+  };
+
   switch (BO->getOpcode()) {
   case BO_EQ:
-return Discard(this->emitEQ(*LT, BO));
+return MaybeCastToBool(this->emitEQ(*LT, BO));
   case BO_NE:
-return Discard(this->emitNE(*LT, BO));
+return MaybeCastToBool(this->emitNE(*LT, BO));
   case BO_LT:
-return Discard(this->emitLT(*LT, BO));
+return MaybeCastToBool(this->emitLT(*LT, BO));
   case BO_LE:
-return Discard(this->emitLE(*LT, BO));
+return MaybeCastToBool(this->emitLE(*LT, BO));
   case BO_GT:
-return Discard(this->emitGT(*LT, BO));
+return MaybeCastToBool(this->emitGT(*LT, BO));
   case BO_GE:
-return Discard(this->emitGE(*LT, BO));
+return MaybeCastToBool(this->emitGE(*LT, BO));
   case BO_Sub:
 if (BO->getType()->isFloatingType())
   return Discard(this->emitSubf(getRoundingMode(BO), BO));


Index: clang/test/AST/Interp/c.c
===
--- /dev/null
+++ clang/test/AST/Interp/c.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+/// expected-no-diagnostics
+/// ref-no-diagnostics
+
+_Static_assert(1, "");
+_Static_assert(0 != 1, "");
+_Static_assert(1.0 == 1.0, "");
+_Static_assert( (5 > 4) + (3 > 2) == 2, "");
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -237,19 +237,31 @@
   if (!visit(LHS) || !visit(RHS))
 return false;
 
+  // For languages such as C, cast the result of one
+  // of our comparision opcodes to T (which is usually int).
+  auto MaybeCastToBool = [this, T, BO](bool Result) {
+if (!Result)
+  return false;
+if (DiscardResult)
+  return this->emitPop(*T, BO);
+if (T != PT_Bool)
+  return this->emitCast(PT_Bool, *T, BO);
+return true;
+  };
+
   switch (BO->getOpcode()) {
   case BO_EQ:
-return Discard(this->emitEQ(*LT, BO));
+return MaybeCastToBool(this->emitEQ(*LT, BO));
   case BO_NE:
-return Discard(this->emitNE(*LT, BO));
+return MaybeCastToBool(this->emitNE(*LT, BO));
   case BO_LT:
-return Discard(this->emitLT(*LT, BO));
+return MaybeCastToBool(this->emitLT(*LT, BO));
   case BO_LE:
-return Discard(this->emitLE(*LT, BO));
+return MaybeCastToBool(this->emitLE(*LT, BO));
   case BO_GT:
-return Discard(this->emitGT(*LT, BO));
+return MaybeCastToBool(this->emitGT(*LT, BO));
   case BO_GE:
-return Discard(this->emitGE(*LT, BO));
+return MaybeCastToBool(this->emitGE(*LT, BO));
   case BO_Sub:
 if (BO->getType()->isFloatingType())
   return Discard(this->emitSubf(getRoundingMode(BO), BO));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D150670: [InstCombine] Disable generation of fshl/fshr for rotates

2023-05-31 Thread Nikita Popov via Phabricator via cfe-commits
nikic added a comment.

Can you please drop all wasm related tests and instead add an InstCombine test 
for the fsh+and pattern?

It would also be good to have a test where we can fold one side to a constant, 
but that constant is not zero. We should then consider whether that is 
profitable or not. (In that case we can't reduce to a simple shift and will 
reduce to a shift and or with constant instead -- is that better or worse than 
a rotate?)




Comment at: llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp:933
+Depth + 1)))
+return I;
+}

Calling SimplifyDemandedBits() for the case of known demanded bits is a bit 
odd, I'd probably write something like this instead:
```
KnownBits LHSKnown = computeKnownBits(I->getOperand(0), Depth + 1, I);
if (DemandedMaskLHS.isSubsetOf(LHSKnown.Zero | LHSKnown.One)) {
  replaceOperand(I, 0, Constant::getIntegerValue(VTy, LHSKnown.One);
  return &I;
}
KnownBits RHSKnown = computeKnownBits(I->getOperand(1), Depth + 1, I);
if (DemandedMaskRHS.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) {
  replaceOperand(I, 1, Constant::getIntegerValue(VTy, RHSKnown.One);
  return &I;
}
```


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150670/new/

https://reviews.llvm.org/D150670

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


[clang] 2e676fa - Revert "[clang][Interp] Optionally cast comparison result to non-bool"

2023-05-31 Thread Timm Bäder via cfe-commits
Author: Timm Bäder
Date: 2023-05-31T13:07:40+02:00
New Revision: 2e676fad2620a2ee41b7a00b27770fcfcb16f912

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

LOG: Revert "[clang][Interp] Optionally cast comparison result to non-bool"

This reverts commit 81522a012accfcc6bbf4dfa21a793aea6e4e532a.

Looks like we're not ready for this yet:
https://lab.llvm.org/buildbot/#/builders/139/builds/41797

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 
clang/test/AST/Interp/c.c



diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 24663a15bcd0..df7c4a72f21a 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -237,31 +237,19 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
   if (!visit(LHS) || !visit(RHS))
 return false;
 
-  // For languages such as C, cast the result of one
-  // of our comparision opcodes to T (which is usually int).
-  auto MaybeCastToBool = [this, T, BO](bool Result) {
-if (!Result)
-  return false;
-if (DiscardResult)
-  return this->emitPop(*T, BO);
-if (T != PT_Bool)
-  return this->emitCast(PT_Bool, *T, BO);
-return true;
-  };
-
   switch (BO->getOpcode()) {
   case BO_EQ:
-return MaybeCastToBool(this->emitEQ(*LT, BO));
+return Discard(this->emitEQ(*LT, BO));
   case BO_NE:
-return MaybeCastToBool(this->emitNE(*LT, BO));
+return Discard(this->emitNE(*LT, BO));
   case BO_LT:
-return MaybeCastToBool(this->emitLT(*LT, BO));
+return Discard(this->emitLT(*LT, BO));
   case BO_LE:
-return MaybeCastToBool(this->emitLE(*LT, BO));
+return Discard(this->emitLE(*LT, BO));
   case BO_GT:
-return MaybeCastToBool(this->emitGT(*LT, BO));
+return Discard(this->emitGT(*LT, BO));
   case BO_GE:
-return MaybeCastToBool(this->emitGE(*LT, BO));
+return Discard(this->emitGE(*LT, BO));
   case BO_Sub:
 if (BO->getType()->isFloatingType())
   return Discard(this->emitSubf(getRoundingMode(BO), BO));

diff  --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c
deleted file mode 100644
index 248494c95f5e..
--- a/clang/test/AST/Interp/c.c
+++ /dev/null
@@ -1,10 +0,0 @@
-// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
-// RUN: %clang_cc1 -verify=ref %s
-
-/// expected-no-diagnostics
-/// ref-no-diagnostics
-
-_Static_assert(1, "");
-_Static_assert(0 != 1, "");
-_Static_assert(1.0 == 1.0, "");
-_Static_assert( (5 > 4) + (3 > 2) == 2, "");



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


[PATCH] D151553: [clang] Fix consteval operators in template contexts

2023-05-31 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added a comment.

In D151553#4380667 , @erichkeane 
wrote:

> Like @cor3ntin I'm concerned about removing the transform call.  I'm just as 
> concerned that it caused no regressions...
>
> If we have to transform the arguments, then this can be a dependent thing, 
> which means the callee should be possible to be dependent, right? Thus needs 
> to be transformed somewhere?

Oh, I didn't get @cor3ntin 's question in the first place! The question was 
where it the callee instantiated, right? The callee is instantiated when the 
whole operator call expr is rebuilt in Sema::RebuildCXXOperatorCallExpr. From 
what I see, `Sema::RebuildCXXOperatorCallExpr` doesn't really care which callee 
is passed there. It checks which operation it represents and performs lookup 
depending on the arguments. This triggers instantiation.

Please see the test I'm adding. There is several cases where the operator 
callee is dependent. They work fine with the change. I also see the 
instantiated function decl in the AST, just the same as before the change.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151553/new/

https://reviews.llvm.org/D151553

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


[PATCH] D150910: [libclang] Add CXBinaryOperatorKind and CXUnaryOperatorKind (implements 29138)

2023-05-31 Thread MineGame159 via Phabricator via cfe-commits
MineGame159 added a comment.

ping?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150910/new/

https://reviews.llvm.org/D150910

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


[PATCH] D146987: [Assignment Tracking] Enable by default

2023-05-31 Thread Orlando Cazalet-Hyams via Phabricator via cfe-commits
Orlando added a comment.

In D146987#4375881 , @hctim wrote:

> Hey, found another error that occurs when building Android that looks to be 
> different from @maskray's revert.
> ...

Thanks for the report and the tiny reproducer! I've written D151795 
 to address this.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D146987/new/

https://reviews.llvm.org/D146987

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


[PATCH] D151749: [Headers][doc] Add "shuffle-like" intrinsic descriptions to avx2intrin.h

2023-05-31 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei accepted this revision.
pengfei added a comment.
This revision is now accepted and ready to land.

LGTM.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151749/new/

https://reviews.llvm.org/D151749

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


[PATCH] D148793: [clang-tidy] Implement an include-cleaner check.

2023-05-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 527001.
VitaNuo marked 25 inline comments as done.
VitaNuo added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148793/new/

https://reviews.llvm.org/D148793

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/clangd/TidyProvider.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/bar.h
  clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/baz.h
  clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/foo.h
  clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/private.h
  clang-tools-extra/test/clang-tidy/checkers/misc/include-cleaner.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc/system/string.h
  clang-tools-extra/test/clang-tidy/checkers/misc/system/vector.h
  clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
  clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
===
--- /dev/null
+++ clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
@@ -0,0 +1,198 @@
+//===--- IncludeCleanerCheck.cpp - clang-tidy -===//
+//
+// 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 "ClangTidyDiagnosticConsumer.h"
+#include "ClangTidyOptions.h"
+#include "ClangTidyTest.h"
+#include "misc/IncludeCleanerCheck.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Path.h"
+#include "gtest/gtest.h"
+
+#include 
+#include 
+#include 
+
+using namespace clang::tidy::misc;
+
+namespace clang {
+namespace tidy {
+namespace test {
+
+std::string
+appendPathSystemIndependent(std::initializer_list Segments) {
+  llvm::SmallString<32> Path;
+  for (const auto &Segment : Segments)
+llvm::sys::path::append(Path, llvm::sys::path::Style::native, Segment);
+  return std::string{Path};
+}
+
+TEST(IncludeCleanerCheckTest, BasicUnusedIncludes) {
+  const char *PreCode = R"(
+#include "bar.h"
+#include 
+#include "bar.h"
+)";
+  const char *PostCode = "\n";
+
+  std::vector Errors;
+  EXPECT_EQ(PostCode, runCheckOnCode(
+  PreCode, &Errors, "file.cpp", std::nullopt,
+  ClangTidyOptions(), {{"bar.h", ""}, {"vector", ""}}));
+}
+
+TEST(IncludeCleanerCheckTest, SuppressUnusedIncludes) {
+  const char *PreCode = R"(
+#include "bar.h"
+#include "foo/qux.h"
+#include "baz/qux/qux.h"
+#include 
+)";
+
+  const char *PostCode = R"(
+#include "bar.h"
+#include "foo/qux.h"
+#include 
+)";
+
+  std::vector Errors;
+  ClangTidyOptions Opts;
+  std::string IgnoreHeaders{"bar.h;"};
+  IgnoreHeaders += appendPathSystemIndependent({"foo", ".*"});
+  IgnoreHeaders += ";";
+  IgnoreHeaders += appendPathSystemIndependent({"baz", "qux"});
+  IgnoreHeaders += ";vector";
+  Opts.CheckOptions["IgnoreHeaders"] = llvm::StringRef{IgnoreHeaders};
+  EXPECT_EQ(PostCode,
+runCheckOnCode(
+PreCode, &Errors, "file.cpp", std::nullopt, Opts,
+{{"bar.h", ""},
+ {"vector", ""},
+ {appendPathSystemIndependent({"foo", "qux.h"}), ""},
+ {appendPathSystemIndependent({"baz", "qux", "qux.h"}), ""}}));
+}
+
+TEST(IncludeCleanerCheckTest, BasicMissingIncludes) {
+  const char *PreCode = R"(
+#include "bar.h"
+
+int BarResult = bar();
+int BazResult = baz();
+)";
+  const char *PostCode = R"(
+#include "bar.h"
+#include "baz.h"
+
+int BarResult = bar();
+int BazResult = baz();
+)";
+
+  std::vector Errors;
+  EXPECT_EQ(PostCode,
+runCheckOnCode(
+PreCode, &Errors, "file.cpp", std::nullopt, ClangTidyOptions(),
+{{"bar.h", R"(#pragma once
+  #include "baz.h"
+  int bar();
+   )"},
+ {"baz.h", R"(#pragma once
+  int baz();
+   )"}}));
+}
+
+TEST(IncludeCleanerCheckTest, SuppressMissingIncludes) {
+  const char *PreCode = R"(
+#include "bar.h"
+
+int BarResult = bar();
+int BazResult = baz();
+int QuxResult = qux();
+)";
+
+  std::string IgnoreHeaders{"baz.h;"};
+  IgnoreHeade

[PATCH] D148793: [clang-tidy] Implement an include-cleaner check.

2023-05-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added a comment.

Thanks for the comments!




Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:86
+  llvm::SmallVector MainFileDecls;
+  for (auto *D : Result.Nodes.getNodeAs("top")->decls()) {
+SourceLocation Loc = D->getLocation();

PiotrZSL wrote:
> auto -> const Decl* 
`const` will not work, since the container I need to populate has to have 
`llvm::SmallVector` type due to the include-cleaner library interfaces.



Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:88
+SourceLocation Loc = D->getLocation();
+if (!SM->isWrittenInMainFile(SM->getSpellingLoc(Loc)))
+  continue;

hokein wrote:
> We should use the `getExpansionLoc` rather than the `SpellingLoc` here, 
> otherwise we might miss the case like `TEST_F(WalkUsedTest, 
> MultipleProviders) {... }` where the decl location is spelled in another 
> file, but the function body is spelled in main-file.
> 
> we should actually use FileLoc of the decl location here (i.e. map it back to 
> spelling location) as the decl might be introduced by a macro expansion, but 
> if the spelling of "primary" location belongs to the main file we should 
> still analyze it (e.g. decls introduced via `TEST` macros)

> we actually want spelling location, not fileloc
> sorry for the confusion
> basically, spelling location will always map to where a name is spelled in a  
> > physical file, even if it's part of macro body
> whereas getFileLoc, will map tokens from macro body to their expansion 
> locations (i.e. place in a physical file where the macro is invoked)

These are earlier comments from Kadir on this topic. AFAIU we want the spelling 
location for `TEST_F(WalkUsedTest, MultipleProviders) {... }` because:

- for Decls introduced by the `TEST_F` expansion, we would like to analyze them 
only if they are spelled in the main file.
- for arguments, their transitive spelling location is where they're written. 
So if `TEST_F(WalkUsedTest, MultipleProviders) {... }` is written in the main 
file, the argument locations will be counted.




Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:81
+   Result.Nodes.getNodeAs("top")->decls()) {
+if (!SM->isInMainFile(D->getLocation()))
+  continue;

kadircet wrote:
> we should actually use FileLoc of the decl location here (i.e. map it back to 
> spelling location) as the decl might be introduced by a macro expansion, but 
> if the spelling of "primary" location belongs to the main file we should 
> still analyze it (e.g. decls introduced via `TEST` macros)
> 
> also `SourceManager::isInMainFile` will follow `#line` directives, which can 
> create confusion (a declaration from some other file will create a diagnostic 
> in the main file), so let's use `isWrittenInMainFile` instead?
> we should actually use FileLoc of the decl location here (i.e. map it back to 
> spelling location) as the decl might be introduced by a macro expansion, but 
> if the spelling of "primary" location belongs to the main file we should 
> still analyze it (e.g. decls introduced via `TEST` macros)
> 
> also `SourceManager::isInMainFile` will follow `#line` directives, which can 
> create confusion (a declaration from some other file will create a diagnostic 
> in the main file), so let's use `isWrittenInMainFile` instead?





Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h:42
+llvm::SmallVector SplitIgnoreHeaders;
+llvm::StringRef{*IgnoreHeaders}.split(SplitIgnoreHeaders, ",");
+for (const auto &Header : SplitIgnoreHeaders) {

PiotrZSL wrote:
> many check uses ; as separator, and uses parseStringList function to do that 
> from OptionsUtils.
Thanks for the tip, I can use the OptionsUtils infrastructure indeed.



Comment at: clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp:19
+#include "bar.h"
+#include 
+#include "bar.h"

PiotrZSL wrote:
> make sure that those tests does not depend on actual system headers (check 
> what headers are included here).
they don't, adding a declaration to the custom "vector.h" and then using it in 
the main file makes `vector` disappear from the list of unused includes.
On top of that, even if the test did somehow depend on the actual system 
headers, this wouldn't change anything in the test result, since the `vector` 
header would remain unused.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148793/new/

https://reviews.llvm.org/D148793

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


[PATCH] D148700: [clang] Add support for “regular” keyword attributes

2023-05-31 Thread Nico Weber via Phabricator via cfe-commits
thakis added subscribers: sammccall, thakis.
thakis added inline comments.



Comment at: clang-tools-extra/pseudo/lib/grammar/CMakeLists.txt:5
-# Dependencies should be minimal to avoid long dep paths in the build graph.
-# It does use clangBasic headers (tok::TokenKind), but linking is not needed.
-# We have no transitive dependencies on tablegen files.

Did whoever wrote this comment sign up its removal? Looks like it was 
@sammccall in 
https://github.com/llvm/llvm-project/commit/dc63ad8878de6d0b5dc1268691f48035e9234763


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148700/new/

https://reviews.llvm.org/D148700

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


[PATCH] D150953: [Clang][SVE2.1] Add clang support for prototypes using svcount_t

2023-05-31 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added inline comments.



Comment at: clang/include/clang/Basic/arm_sve.td:56
 // P: boolean
+// Qa: svcount
 // U: unsigned

The typespec modifier in this file can remain `Q` rather than `Qa`. Can you 
change it back?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150953/new/

https://reviews.llvm.org/D150953

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


[PATCH] D150953: [Clang][SVE2.1] Add clang support for prototypes using svcount_t

2023-05-31 Thread hassnaaHamdi via Phabricator via cfe-commits
hassnaa-arm added inline comments.



Comment at: clang/include/clang/Basic/arm_sve.td:56
 // P: boolean
+// Qa: svcount
 // U: unsigned

sdesmalen wrote:
> The typespec modifier in this file can remain `Q` rather than `Qa`. Can you 
> change it back?
what if there is a new type that is target-specific ?
At that case we will have to find a new character.
But if we now use Qa, we can use Qb for the new type.
Is that correct ?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150953/new/

https://reviews.llvm.org/D150953

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


[PATCH] D148700: [clang] Add support for “regular” keyword attributes

2023-05-31 Thread Richard Sandiford via Phabricator via cfe-commits
rsandifo-arm added inline comments.



Comment at: clang-tools-extra/pseudo/lib/grammar/CMakeLists.txt:5
-# Dependencies should be minimal to avoid long dep paths in the build graph.
-# It does use clangBasic headers (tok::TokenKind), but linking is not needed.
-# We have no transitive dependencies on tablegen files.

thakis wrote:
> Did whoever wrote this comment sign up its removal? Looks like it was 
> @sammccall in 
> https://github.com/llvm/llvm-project/commit/dc63ad8878de6d0b5dc1268691f48035e9234763
No, sorry, I should have checked.

The type referenced in the comment (`tok::TokenKind`) is the one that is now 
being partially generated by tablegen.  Given that, there didn't seem any way 
of avoiding the dependency.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148700/new/

https://reviews.llvm.org/D148700

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


[clang] ce97312 - Implement BufferOverlap check for sprint/snprintf

2023-05-31 Thread Arnaud Bienner via cfe-commits
Author: Arnaud Bienner
Date: 2023-05-31T14:43:16+02:00
New Revision: ce97312d109b21acb97d3ea243e214f20bd87cfc

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

LOG: Implement BufferOverlap check for sprint/snprintf

Differential Revision: https://reviews.llvm.org/D150430

Added: 
clang/test/Analysis/buffer-overlap.c

Modified: 
clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 12b948a65261f..01a35505a90a2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -12,6 +12,7 @@
 
//===--===//
 
 #include "InterCheckerAPI.h"
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
@@ -175,6 +176,8 @@ class CStringChecker : public Checker< eval::Call,
std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Regular)},
   {{CDF_MaybeBuiltin, {"bzero"}, 2}, &CStringChecker::evalBzero},
   {{CDF_MaybeBuiltin, {"explicit_bzero"}, 2}, &CStringChecker::evalBzero},
+  {{CDF_MaybeBuiltin, {"sprintf"}, 2}, &CStringChecker::evalSprintf},
+  {{CDF_MaybeBuiltin, {"snprintf"}, 2}, &CStringChecker::evalSnprintf},
   };
 
   // These require a bit of special handling.
@@ -228,6 +231,11 @@ class CStringChecker : public Checker< eval::Call,
   void evalMemset(CheckerContext &C, const CallExpr *CE) const;
   void evalBzero(CheckerContext &C, const CallExpr *CE) const;
 
+  void evalSprintf(CheckerContext &C, const CallExpr *CE) const;
+  void evalSnprintf(CheckerContext &C, const CallExpr *CE) const;
+  void evalSprintfCommon(CheckerContext &C, const CallExpr *CE, bool IsBounded,
+ bool IsBuiltin) const;
+
   // Utility methods
   std::pair
   static assumeZero(CheckerContext &C,
@@ -2352,6 +2360,51 @@ void CStringChecker::evalBzero(CheckerContext &C, const 
CallExpr *CE) const {
   C.addTransition(State);
 }
 
+void CStringChecker::evalSprintf(CheckerContext &C, const CallExpr *CE) const {
+  CurrentFunctionDescription = "'sprintf'";
+  bool IsBI = CE->getBuiltinCallee() == Builtin::BI__builtin___sprintf_chk;
+  evalSprintfCommon(C, CE, /* IsBounded */ false, IsBI);
+}
+
+void CStringChecker::evalSnprintf(CheckerContext &C, const CallExpr *CE) const 
{
+  CurrentFunctionDescription = "'snprintf'";
+  bool IsBI = CE->getBuiltinCallee() == Builtin::BI__builtin___snprintf_chk;
+  evalSprintfCommon(C, CE, /* IsBounded */ true, IsBI);
+}
+
+void CStringChecker::evalSprintfCommon(CheckerContext &C, const CallExpr *CE,
+   bool IsBounded, bool IsBuiltin) const {
+  ProgramStateRef State = C.getState();
+  DestinationArgExpr Dest = {CE->getArg(0), 0};
+
+  const auto NumParams = CE->getCalleeDecl()->getAsFunction()->getNumParams();
+  assert(CE->getNumArgs() >= NumParams);
+
+  const auto AllArguments =
+  llvm::make_range(CE->getArgs(), CE->getArgs() + CE->getNumArgs());
+  const auto VariadicArguments = drop_begin(enumerate(AllArguments), 
NumParams);
+
+  for (const auto &[ArgIdx, ArgExpr] : VariadicArguments) {
+// We consider only string buffers
+if (const QualType type = ArgExpr->getType();
+!type->isAnyPointerType() ||
+!type->getPointeeType()->isAnyCharacterType())
+  continue;
+SourceArgExpr Source = {ArgExpr, unsigned(ArgIdx)};
+
+// Ensure the buffers do not overlap.
+SizeArgExpr SrcExprAsSizeDummy = {Source.Expression, Source.ArgumentIndex};
+State = CheckOverlap(
+C, State,
+(IsBounded ? SizeArgExpr{CE->getArg(1), 1} : SrcExprAsSizeDummy), Dest,
+Source);
+if (!State)
+  return;
+  }
+
+  C.addTransition(State);
+}
+
 
//===--===//
 // The driver method, and other Checker callbacks.
 
//===--===//

diff  --git a/clang/test/Analysis/buffer-overlap.c 
b/clang/test/Analysis/buffer-overlap.c
new file mode 100644
index 0..8414a764541e2
--- /dev/null
+++ b/clang/test/Analysis/buffer-overlap.c
@@ -0,0 +1,98 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=alpha.unix.cstring.BufferOverlap
+//
+// RUN: %clang_analyze_cc1 -verify %s -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=alpha.unix.cstring.BufferOverlap
+//
+// RUN: %clang_analyze_cc1 -verify %s -DVARIANT \
+// RUN:   -analyzer-checker=alpha.unix.cstring.BufferOverlap
+//
+// RUN: %clang_analyze_cc

[PATCH] D150430: Implement BufferOverlap check for sprint/snprintf

2023-05-31 Thread Arnaud Bienner via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGce97312d109b: Implement BufferOverlap check for 
sprint/snprintf (authored by ArnaudBienner).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150430/new/

https://reviews.llvm.org/D150430

Files:
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/test/Analysis/buffer-overlap.c

Index: clang/test/Analysis/buffer-overlap.c
===
--- /dev/null
+++ clang/test/Analysis/buffer-overlap.c
@@ -0,0 +1,98 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=alpha.unix.cstring.BufferOverlap
+//
+// RUN: %clang_analyze_cc1 -verify %s -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=alpha.unix.cstring.BufferOverlap
+//
+// RUN: %clang_analyze_cc1 -verify %s -DVARIANT \
+// RUN:   -analyzer-checker=alpha.unix.cstring.BufferOverlap
+//
+// RUN: %clang_analyze_cc1 -verify %s -DVARIANT -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=alpha.unix.cstring.BufferOverlap
+
+// This provides us with four possible sprintf() definitions.
+
+#ifdef USE_BUILTINS
+#define BUILTIN(f) __builtin_##f
+#else /* USE_BUILTINS */
+#define BUILTIN(f) f
+#endif /* USE_BUILTINS */
+
+typedef typeof(sizeof(int)) size_t;
+
+#ifdef VARIANT
+
+#define __sprintf_chk BUILTIN(__sprintf_chk)
+#define __snprintf_chk BUILTIN(__snprintf_chk)
+int __sprintf_chk (char * __restrict str, int flag, size_t os,
+const char * __restrict fmt, ...);
+int __snprintf_chk (char * __restrict str, size_t len, int flag, size_t os,
+const char * __restrict fmt, ...);
+
+#define sprintf(str, ...) __sprintf_chk(str, 0, __builtin_object_size(str, 0), __VA_ARGS__)
+#define snprintf(str, len, ...) __snprintf_chk(str, len, 0, __builtin_object_size(str, 0), __VA_ARGS__)
+
+#else /* VARIANT */
+
+#define sprintf BUILTIN(sprintf)
+int sprintf(char *restrict buffer, const char *restrict format, ... );
+int snprintf(char *restrict buffer, size_t bufsz,
+ const char *restrict format, ... );
+#endif /* VARIANT */
+
+void test_sprintf1() {
+  char a[4] = {0};
+  sprintf(a, "%d/%s", 1, a); // expected-warning{{Arguments must not be overlapping buffers}}
+}
+
+void test_sprintf2() {
+  char a[4] = {0};
+  sprintf(a, "%s", a); // expected-warning{{Arguments must not be overlapping buffers}}
+}
+
+void test_sprintf3() {
+  char a[4] = {0};
+  sprintf(a, "%s/%s", a, a); // expected-warning{{Arguments must not be overlapping buffers}}
+}
+
+void test_sprintf4() {
+  char a[4] = {0};
+  sprintf(a, "%d", 42); // no-warning
+}
+
+void test_sprintf5() {
+  char a[4] = {0};
+  char b[4] = {0};
+  sprintf(a, "%s", b); // no-warning
+}
+
+void test_snprintf1() {
+  char a[4] = {0};
+  snprintf(a, sizeof(a), "%d/%s", 1, a); // expected-warning{{Arguments must not be overlapping buffers}}
+}
+
+void test_snprintf2() {
+  char a[4] = {0};
+  snprintf(a+1, sizeof(a)-1, "%d/%s", 1, a); // expected-warning{{Arguments must not be overlapping buffers}}
+}
+
+void test_snprintf3() {
+  char a[4] = {0};
+  snprintf(a, sizeof(a), "%s", a); // expected-warning{{Arguments must not be overlapping buffers}}
+}
+
+void test_snprintf4() {
+  char a[4] = {0};
+  snprintf(a, sizeof(a), "%s/%s", a, a); // expected-warning{{Arguments must not be overlapping buffers}}
+}
+
+void test_snprintf5() {
+  char a[4] = {0};
+  snprintf(a, sizeof(a), "%d", 42); // no-warning
+}
+
+void test_snprintf6() {
+  char a[4] = {0};
+  char b[4] = {0};
+  snprintf(a, sizeof(a), "%s", b); // no-warning
+}
Index: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -12,6 +12,7 @@
 //===--===//
 
 #include "InterCheckerAPI.h"
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
@@ -175,6 +176,8 @@
std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Regular)},
   {{CDF_MaybeBuiltin, {"bzero"}, 2}, &CStringChecker::evalBzero},
   {{CDF_MaybeBuiltin, {"explicit_bzero"}, 2}, &CStringChecker::evalBzero},
+  {{CDF_MaybeBuiltin, {"sprintf"}, 2}, &CStringChecker::evalSprintf},
+  {{CDF_MaybeBuiltin, {"snprintf"}, 2}, &CStringChecker::evalSnprintf},
   };
 
   // These require a bit of special handling.
@@ -228,6 +231,11 @@
   void evalMemset(CheckerContext &C, const CallExpr *CE) const;
   void evalBzero(CheckerContext &C, const CallExpr *CE) const;
 
+  void evalSprintf(CheckerContext &C, const CallExpr *CE) const;
+  void evalSnprintf(CheckerContext &C, const CallExpr *CE) const;
+  void evalSprintfCommon(CheckerContext &C, const CallExpr *CE, bool IsBounded,
+ 

[PATCH] D150430: Implement BufferOverlap check for sprint/snprintf

2023-05-31 Thread Arnaud Bienner via Phabricator via cfe-commits
ArnaudBienner added a comment.

Thanks @steakhal for the proposal :) but I pushed it myself: 
https://github.com/llvm/llvm-project/commit/ce97312d109b21acb97d3ea243e214f20bd87cfc

I used to have svn access, and Chris kindly give me write access to the git 
repository.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150430/new/

https://reviews.llvm.org/D150430

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


[PATCH] D146418: Support for OpenMP 5.0 sec 2.12.7 - Declare Target initializer expressions

2023-05-31 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D146418/new/

https://reviews.llvm.org/D146418

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


[PATCH] D151625: [clang] Add `clang::equality_operator_compares_members_lexicographically`

2023-05-31 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D151625#4382227 , @philnik wrote:

> In D151625#4380735 , @erichkeane 
> wrote:
>
>> I'm a little dense today perhaps, but I don't get the use case for this?  
>> Can you ELI-EWG?  Is this an attribute we expect our users to use?  The name 
>> is horrifyingly long for users to use, but perhaps that is a good thing.
>
> This is useful for libraries which have ADL requirements. Something like
>
>   template 
>   struct Holder {
> T v;
>   };
>   
>   struct Incomplete;
>   
>   template 
>   class TupleImpl {
> T v;
>   
> bool operator==(const TupleImpl&) const = default;
>   };
>   
>   template 
>   class Tuple : public TupleImpl {
> bool operator==(const Tuple&) const = default; // ADL call here
>   };
>   
>   void func() {
> Tuple*> f; // Instantiation fails because Incomplete 
> isn't defined
>   }
>
> has to work for `std::tuple` etc. to make them 
> `__is_trivially_equality_comparable`, but the defaulted `operator==` will 
> always try ADL (at least that's my understanding). To not make ADL calls, 
> this attribute can be used instead, which basically say "trust me, my 
> operator== does what the defaulted one would do".
>
> Not sure what you mean by "Can you ELI-EWG?".
> I agree that the name isn't great, but I couldn't come up with anything 
> better that is still descriptive, and this attribute will probably only be 
> used by very few libraries anyways (maybe just libc++, since this is pure 
> QoI). As I said in the attribute description, the defaulted operator should 
> be used if possible (which is probably the case in 99.9% of use cases).
>
> (Note to self: maybe add the example as a test)

ELI-EWG: "Explain-like-I'm Evolution Working Group" :)  Its a touch of a joke, 
there is a common reddit 'ELI5' (Explain like I'm 5), so I'm equating the C++ 
EWG to needing 5-year-old-esque explanations.

I can see the value to that I guess?  I don't have a good idea on the name, but 
perhaps folks from @clang-language-wg might have an idea?  Either way, I want 
to give it a little time for folks to comment.

That said, it DOES seem that the pre-commit-CI failures are related, so those 
need fixing as well.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151625/new/

https://reviews.llvm.org/D151625

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


[PATCH] D150430: Implement BufferOverlap check for sprint/snprintf

2023-05-31 Thread Arnaud Bienner via Phabricator via cfe-commits
ArnaudBienner added a comment.

@steakhal should the release notes page be updated to add this?

I think this could be beneficial for the users to be aware of that change.

If yes, who is responsible for doing that? Developers? (me) or someone else is 
taking care of reviewing the list of changes since latest releases?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150430/new/

https://reviews.llvm.org/D150430

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


[PATCH] D151683: [clang] Enable C++11-style attributes in all language modes

2023-05-31 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D151683#4382408 , @philnik wrote:

> In D151683#4380877 , @erichkeane 
> wrote:
>
>> What is the justification for this?
>
> What exactly are you asking for? Why I'd like to back port it? This would 
> make quite a bit of code in libc++ simpler and avoids pit-falls where an 
> attribute works in some place in some version but not in another.
>
>> Do other compilers do this?
>
> ICC and NVC++ support this: https://godbolt.org/z/TeMnGdGsY
>
>> Was there an RFC?
>
> No. I guess, since you are asking I should write one for this? Only for the 
> removal of `-fdouble-square-bracket-attributes`, or also for back porting 
> this?

The RFC I would expect for "allow C/C++ style attributes as an extension in 
previous modes".  This is a pretty significant feature to allow as an 
extension, particularly since our two main alternative compilers (G++/MSVC) 
don't have this as an extension. I'd be curious how the other C compilers do 
this as well.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151683/new/

https://reviews.llvm.org/D151683

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


[clang] e5399f1 - [Headers][doc] Add shuffle-like intrinsic descriptions to avx2intrin.h

2023-05-31 Thread Paul Robinson via cfe-commits
Author: Paul Robinson
Date: 2023-05-31T06:33:18-07:00
New Revision: e5399f1d7cabfca90030ca03f52818e892aa389f

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

LOG: [Headers][doc] Add shuffle-like intrinsic descriptions to avx2intrin.h

Differential Revision: https://reviews.llvm.org/D151749

Added: 


Modified: 
clang/lib/Headers/avx2intrin.h

Removed: 




diff  --git a/clang/lib/Headers/avx2intrin.h b/clang/lib/Headers/avx2intrin.h
index be4d30a98195e..409401f46ba9b 100644
--- a/clang/lib/Headers/avx2intrin.h
+++ b/clang/lib/Headers/avx2intrin.h
@@ -41,24 +41,126 @@ _mm256_abs_epi32(__m256i __a)
 return (__m256i)__builtin_elementwise_abs((__v8si)__a);
 }
 
+/// Converts the elements of two 256-bit vectors of [16 x i16] to 8-bit
+///integers using signed saturation, and returns the 256-bit result.
+///
+/// \code{.operation}
+/// FOR i := 0 TO 7
+///   j := i*16
+///   k := i*8
+///   result[7+k:k] := SATURATE8(__a[15+j:j])
+///   result[71+k:64+k] := SATURATE8(__b[15+j:j])
+///   result[135+k:128+k] := SATURATE8(__a[143+j:128+j])
+///   result[199+k:192+k] := SATURATE8(__b[143+j:128+j])
+/// ENDFOR
+/// \endcode
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the \c VPACKSSWB instruction.
+///
+/// \param __a
+///A 256-bit vector of [16 x i16] used to generate result[63:0] and
+///result[191:128].
+/// \param __b
+///A 256-bit vector of [16 x i16] used to generate result[127:64] and
+///result[255:192].
+/// \returns A 256-bit integer vector containing the result.
 static __inline__ __m256i __DEFAULT_FN_ATTRS256
 _mm256_packs_epi16(__m256i __a, __m256i __b)
 {
   return (__m256i)__builtin_ia32_packsswb256((__v16hi)__a, (__v16hi)__b);
 }
 
+/// Converts the elements of two 256-bit vectors of [8 x i32] to 16-bit
+///integers using signed saturation, and returns the resulting 256-bit
+///vector of [16 x i16].
+///
+/// \code{.operation}
+/// FOR i := 0 TO 3
+///   j := i*32
+///   k := i*16
+///   result[15+k:k] := SATURATE16(__a[31+j:j])
+///   result[79+k:64+k] := SATURATE16(__b[31+j:j])
+///   result[143+k:128+k] := SATURATE16(__a[159+j:128+j])
+///   result[207+k:192+k] := SATURATE16(__b[159+j:128+j])
+/// ENDFOR
+/// \endcode
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the \c VPACKSSDW instruction.
+///
+/// \param __a
+///A 256-bit vector of [8 x i32] used to generate result[63:0] and
+///result[191:128].
+/// \param __b
+///A 256-bit vector of [8 x i32] used to generate result[127:64] and
+///result[255:192].
+/// \returns A 256-bit vector of [16 x i16] containing the result.
 static __inline__ __m256i __DEFAULT_FN_ATTRS256
 _mm256_packs_epi32(__m256i __a, __m256i __b)
 {
   return (__m256i)__builtin_ia32_packssdw256((__v8si)__a, (__v8si)__b);
 }
 
+/// Converts elements from two 256-bit vectors of [16 x i16] to 8-bit integers
+///using unsigned saturation, and returns the 256-bit result.
+///
+/// \code{.operation}
+/// FOR i := 0 TO 7
+///   j := i*16
+///   k := i*8
+///   result[7+k:k] := SATURATE8U(__a[15+j:j])
+///   result[71+k:64+k] := SATURATE8U(__b[15+j:j])
+///   result[135+k:128+k] := SATURATE8U(__a[143+j:128+j])
+///   result[199+k:192+k] := SATURATE8U(__b[143+j:128+j])
+/// ENDFOR
+/// \endcode
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the \c VPACKUSWB instruction.
+///
+/// \param __a
+///A 256-bit vector of [16 x i16] used to generate result[63:0] and
+///result[191:128].
+/// \param __b
+///A 256-bit vector of [16 x i16] used to generate result[127:64] and
+///result[255:192].
+/// \returns A 256-bit integer vector containing the result.
 static __inline__ __m256i __DEFAULT_FN_ATTRS256
 _mm256_packus_epi16(__m256i __a, __m256i __b)
 {
   return (__m256i)__builtin_ia32_packuswb256((__v16hi)__a, (__v16hi)__b);
 }
 
+/// Converts elements from two 256-bit vectors of [8 x i32] to 16-bit integers
+///using unsigned saturation, and returns the resulting 256-bit vector of
+///[16 x i16].
+///
+/// \code{.operation}
+/// FOR i := 0 TO 3
+///   j := i*32
+///   k := i*16
+///   result[15+k:k] := SATURATE16U(__V1[31+j:j])
+///   result[79+k:64+k] := SATURATE16U(__V2[31+j:j])
+///   result[143+k:128+k] := SATURATE16U(__V1[159+j:128+j])
+///   result[207+k:192+k] := SATURATE16U(__V2[159+j:128+j])
+/// ENDFOR
+/// \endcode
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the \c VPACKUSDW instruction.
+///
+/// \param __V1
+///A 256-bit vector of [8 x i32] used to generate result[63:0] and
+///result[191:128].
+/// \param __V2
+///A 256-bit vector of [8 x i32] used to generate result[127:64] and
+///result[255:192].
+/// \returns A 256-bit vector of [16 x i16] containing the result.
 static __inline__ __m256i _

[PATCH] D151749: [Headers][doc] Add "shuffle-like" intrinsic descriptions to avx2intrin.h

2023-05-31 Thread Paul Robinson via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe5399f1d7cab: [Headers][doc] Add shuffle-like intrinsic 
descriptions to avx2intrin.h (authored by probinson).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D151749?vs=526782&id=527015#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151749/new/

https://reviews.llvm.org/D151749

Files:
  clang/lib/Headers/avx2intrin.h

Index: clang/lib/Headers/avx2intrin.h
===
--- clang/lib/Headers/avx2intrin.h
+++ clang/lib/Headers/avx2intrin.h
@@ -41,24 +41,126 @@
 return (__m256i)__builtin_elementwise_abs((__v8si)__a);
 }
 
+/// Converts the elements of two 256-bit vectors of [16 x i16] to 8-bit
+///integers using signed saturation, and returns the 256-bit result.
+///
+/// \code{.operation}
+/// FOR i := 0 TO 7
+///   j := i*16
+///   k := i*8
+///   result[7+k:k] := SATURATE8(__a[15+j:j])
+///   result[71+k:64+k] := SATURATE8(__b[15+j:j])
+///   result[135+k:128+k] := SATURATE8(__a[143+j:128+j])
+///   result[199+k:192+k] := SATURATE8(__b[143+j:128+j])
+/// ENDFOR
+/// \endcode
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the \c VPACKSSWB instruction.
+///
+/// \param __a
+///A 256-bit vector of [16 x i16] used to generate result[63:0] and
+///result[191:128].
+/// \param __b
+///A 256-bit vector of [16 x i16] used to generate result[127:64] and
+///result[255:192].
+/// \returns A 256-bit integer vector containing the result.
 static __inline__ __m256i __DEFAULT_FN_ATTRS256
 _mm256_packs_epi16(__m256i __a, __m256i __b)
 {
   return (__m256i)__builtin_ia32_packsswb256((__v16hi)__a, (__v16hi)__b);
 }
 
+/// Converts the elements of two 256-bit vectors of [8 x i32] to 16-bit
+///integers using signed saturation, and returns the resulting 256-bit
+///vector of [16 x i16].
+///
+/// \code{.operation}
+/// FOR i := 0 TO 3
+///   j := i*32
+///   k := i*16
+///   result[15+k:k] := SATURATE16(__a[31+j:j])
+///   result[79+k:64+k] := SATURATE16(__b[31+j:j])
+///   result[143+k:128+k] := SATURATE16(__a[159+j:128+j])
+///   result[207+k:192+k] := SATURATE16(__b[159+j:128+j])
+/// ENDFOR
+/// \endcode
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the \c VPACKSSDW instruction.
+///
+/// \param __a
+///A 256-bit vector of [8 x i32] used to generate result[63:0] and
+///result[191:128].
+/// \param __b
+///A 256-bit vector of [8 x i32] used to generate result[127:64] and
+///result[255:192].
+/// \returns A 256-bit vector of [16 x i16] containing the result.
 static __inline__ __m256i __DEFAULT_FN_ATTRS256
 _mm256_packs_epi32(__m256i __a, __m256i __b)
 {
   return (__m256i)__builtin_ia32_packssdw256((__v8si)__a, (__v8si)__b);
 }
 
+/// Converts elements from two 256-bit vectors of [16 x i16] to 8-bit integers
+///using unsigned saturation, and returns the 256-bit result.
+///
+/// \code{.operation}
+/// FOR i := 0 TO 7
+///   j := i*16
+///   k := i*8
+///   result[7+k:k] := SATURATE8U(__a[15+j:j])
+///   result[71+k:64+k] := SATURATE8U(__b[15+j:j])
+///   result[135+k:128+k] := SATURATE8U(__a[143+j:128+j])
+///   result[199+k:192+k] := SATURATE8U(__b[143+j:128+j])
+/// ENDFOR
+/// \endcode
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the \c VPACKUSWB instruction.
+///
+/// \param __a
+///A 256-bit vector of [16 x i16] used to generate result[63:0] and
+///result[191:128].
+/// \param __b
+///A 256-bit vector of [16 x i16] used to generate result[127:64] and
+///result[255:192].
+/// \returns A 256-bit integer vector containing the result.
 static __inline__ __m256i __DEFAULT_FN_ATTRS256
 _mm256_packus_epi16(__m256i __a, __m256i __b)
 {
   return (__m256i)__builtin_ia32_packuswb256((__v16hi)__a, (__v16hi)__b);
 }
 
+/// Converts elements from two 256-bit vectors of [8 x i32] to 16-bit integers
+///using unsigned saturation, and returns the resulting 256-bit vector of
+///[16 x i16].
+///
+/// \code{.operation}
+/// FOR i := 0 TO 3
+///   j := i*32
+///   k := i*16
+///   result[15+k:k] := SATURATE16U(__V1[31+j:j])
+///   result[79+k:64+k] := SATURATE16U(__V2[31+j:j])
+///   result[143+k:128+k] := SATURATE16U(__V1[159+j:128+j])
+///   result[207+k:192+k] := SATURATE16U(__V2[159+j:128+j])
+/// ENDFOR
+/// \endcode
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the \c VPACKUSDW instruction.
+///
+/// \param __V1
+///A 256-bit vector of [8 x i32] used to generate result[63:0] and
+///result[191:128].
+/// \param __V2
+///A 256-bit vector of [8 x i32] used to generate result[127:64] and
+///result[255:192].
+/// \returns A 256-bit vector of [16 x i16] containing the result.
 static __inline__ __m256i __DEFAULT_FN_ATTRS256
 _mm256_packus_epi32(__m256i __V1, __m256i __V2)
 {
@@ -215,6 

[PATCH] D151537: [NFC] Update cpu_specific test to use a newer CPU

2023-05-31 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D151537#4382811 , @LuoYuanke wrote:

> In D151537#4380763 , @erichkeane 
> wrote:
>
>> I don't really see the justification here?  Why do this change?  If the 
>> intent is to just test a newer architecture, we can add tests for that, not 
>> change existing ones.
>
> KNL is deprecated and it is better to remove KNL related code in clang/llvm.

IS it deprecated in Clang?  I see an RFC proposing it, but I don't see 
acceptance of that yet.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151537/new/

https://reviews.llvm.org/D151537

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


[clang] 5437056 - [Headers][doc] Fix typo in avx2intrin.h doc

2023-05-31 Thread Paul Robinson via cfe-commits
Author: Paul Robinson
Date: 2023-05-31T06:43:38-07:00
New Revision: 543705641adb1d3533be141947264ca1b7b04479

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

LOG: [Headers][doc] Fix typo in avx2intrin.h doc

Added: 


Modified: 
clang/lib/Headers/avx2intrin.h

Removed: 




diff  --git a/clang/lib/Headers/avx2intrin.h b/clang/lib/Headers/avx2intrin.h
index 409401f46ba9..5346a0209928 100644
--- a/clang/lib/Headers/avx2intrin.h
+++ b/clang/lib/Headers/avx2intrin.h
@@ -1088,7 +1088,7 @@ _mm256_sad_epu8(__m256i __a, __m256i __b)
   return __builtin_ia32_psadbw256((__v32qi)__a, (__v32qi)__b);
 }
 
-/// Shuffles 8-bit integers in the 256-bit integer vector \a __a acccording
+/// Shuffles 8-bit integers in the 256-bit integer vector \a __a according
 ///to control information in the 256-bit integer vector \a __b, and
 ///returns the 256-bit result. In effect there are two separate 128-bit
 ///shuffles in the lower and upper halves.
@@ -1128,7 +1128,7 @@ _mm256_shuffle_epi8(__m256i __a, __m256i __b)
 }
 
 /// Shuffles 32-bit integers from the 256-bit vector of [8 x i32] in \a a
-///acccording to control information in the integer literal \a imm, and
+///according to control information in the integer literal \a imm, and
 ///returns the 256-bit result. In effect there are two parallel 128-bit
 ///shuffles in the lower and upper halves.
 ///
@@ -1161,7 +1161,7 @@ _mm256_shuffle_epi8(__m256i __a, __m256i __b)
   ((__m256i)__builtin_ia32_pshufd256((__v8si)(__m256i)(a), (int)(imm)))
 
 /// Shuffles 16-bit integers from the 256-bit vector of [16 x i16] in \a a
-///acccording to control information in the integer literal \a imm, and
+///according to control information in the integer literal \a imm, and
 ///returns the 256-bit result. The upper 64 bits of each 128-bit half
 ///are shuffled in parallel; the lower 64 bits of each 128-bit half are
 ///copied from \a a unchanged.
@@ -1197,7 +1197,7 @@ _mm256_shuffle_epi8(__m256i __a, __m256i __b)
   ((__m256i)__builtin_ia32_pshufhw256((__v16hi)(__m256i)(a), (int)(imm)))
 
 /// Shuffles 16-bit integers from the 256-bit vector of [16 x i16] \a a
-///acccording to control information in the integer literal \a imm, and
+///according to control information in the integer literal \a imm, and
 ///returns the 256-bit [16 x i16] result. The lower 64 bits of each
 ///128-bit half are shuffled; the upper 64 bits of each 128-bit half are
 ///copied from \a a unchanged.



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


[PATCH] D150953: [Clang][SVE2.1] Add clang support for prototypes using svcount_t

2023-05-31 Thread Caroline via Phabricator via cfe-commits
CarolineConcatto updated this revision to Diff 527021.
CarolineConcatto added a comment.

- Remove Qa from arm_sve.td and its dependencies


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150953/new/

https://reviews.llvm.org/D150953

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/arm_sve.td
  clang/lib/AST/ASTContext.cpp
  clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_ptrue.c
  clang/utils/TableGen/SveEmitter.cpp

Index: clang/utils/TableGen/SveEmitter.cpp
===
--- clang/utils/TableGen/SveEmitter.cpp
+++ clang/utils/TableGen/SveEmitter.cpp
@@ -66,7 +66,8 @@
 class SVEType {
   TypeSpec TS;
   bool Float, Signed, Immediate, Void, Constant, Pointer, BFloat;
-  bool DefaultType, IsScalable, Predicate, PredicatePattern, PrefetchOp;
+  bool DefaultType, IsScalable, Predicate, PredicatePattern, PrefetchOp,
+  Svcount;
   unsigned Bitwidth, ElementBitwidth, NumVectors;
 
 public:
@@ -76,7 +77,8 @@
   : TS(TS), Float(false), Signed(true), Immediate(false), Void(false),
 Constant(false), Pointer(false), BFloat(false), DefaultType(false),
 IsScalable(true), Predicate(false), PredicatePattern(false),
-PrefetchOp(false), Bitwidth(128), ElementBitwidth(~0U), NumVectors(1) {
+PrefetchOp(false), Svcount(false), Bitwidth(128), ElementBitwidth(~0U),
+NumVectors(1) {
 if (!TS.empty())
   applyTypespec();
 applyModifier(CharMod);
@@ -95,13 +97,16 @@
   bool isFloat() const { return Float && !BFloat; }
   bool isBFloat() const { return BFloat && !Float; }
   bool isFloatingPoint() const { return Float || BFloat; }
-  bool isInteger() const { return !isFloatingPoint() && !Predicate; }
+  bool isInteger() const {
+return !isFloatingPoint() && !Predicate && !Svcount;
+  }
   bool isScalarPredicate() const {
 return !isFloatingPoint() && Predicate && NumVectors == 0;
   }
   bool isPredicateVector() const { return Predicate; }
   bool isPredicatePattern() const { return PredicatePattern; }
   bool isPrefetchOp() const { return PrefetchOp; }
+  bool isSvcount() const { return Svcount; }
   bool isConstant() const { return Constant; }
   unsigned getElementSizeInBits() const { return ElementBitwidth; }
   unsigned getNumVectors() const { return NumVectors; }
@@ -203,6 +208,9 @@
   /// ClassS, so will add type suffixes such as _u32/_s32.
   std::string getMangledName() const { return mangleName(ClassS); }
 
+  /// As above, but mangles the LLVM name instead.
+  std::string getMangledLLVMName() const { return mangleLLVMName(); }
+
   /// Returns true if the intrinsic is overloaded, in that it should also generate
   /// a short form without the type-specifiers, e.g. 'svld1(..)' instead of
   /// 'svld1_u32(..)'.
@@ -233,6 +241,7 @@
 private:
   std::string getMergeSuffix() const { return MergeSuffix; }
   std::string mangleName(ClassKind LocalCK) const;
+  std::string mangleLLVMName() const;
   std::string replaceTemplatedArgs(std::string Name, TypeSpec TS,
std::string Proto) const;
 };
@@ -366,6 +375,9 @@
   if (isScalarPredicate())
 return "b";
 
+  if (isSvcount())
+return "Qa";
+
   if (isVoidPointer())
 S += "v";
   else if (!isFloatingPoint())
@@ -429,13 +441,15 @@
   if (Void)
 S += "void";
   else {
-if (isScalableVector())
+if (isScalableVector() || isSvcount())
   S += "sv";
 if (!Signed && !isFloatingPoint())
   S += "u";
 
 if (Float)
   S += "float";
+else if (isSvcount())
+  S += "count";
 else if (isScalarPredicate() || isPredicateVector())
   S += "bool";
 else if (isBFloat())
@@ -443,7 +457,7 @@
 else
   S += "int";
 
-if (!isScalarPredicate() && !isPredicateVector())
+if (!isScalarPredicate() && !isPredicateVector() && !isSvcount())
   S += utostr(ElementBitwidth);
 if (!isScalableVector() && isVector())
   S += "x" + utostr(getNumElements());
@@ -463,6 +477,9 @@
 void SVEType::applyTypespec() {
   for (char I : TS) {
 switch (I) {
+case 'Q':
+  Svcount = true;
+  break;
 case 'P':
   Predicate = true;
   break;
@@ -554,6 +571,7 @@
 Float = false;
 BFloat = false;
 Predicate = true;
+Svcount = false;
 Bitwidth = 16;
 ElementBitwidth = 1;
 break;
@@ -593,18 +611,21 @@
 break;
   case 'u':
 Predicate = false;
+Svcount = false;
 Signed = false;
 Float = false;
 BFloat = false;
 break;
   case 'x':
 Predicate = false;
+Svcount = false;
 Signed = true;
 Float = false;
 BFloat = false;
 break;
   case 'i':
 Predicate = false;
+Svcount = false;
 Float = false;
 BFloat = false;
 ElementBitwidth = Bitwidth = 64;
@@ -614,6 +635,7 @@
 break;
   case 'I':
 Predicate = false;
+Svcount = false;
 Float = false;
 BFloat = false;
 ElementBitwid

[PATCH] D150953: [Clang][SVE2.1] Add clang support for prototypes using svcount_t

2023-05-31 Thread Caroline via Phabricator via cfe-commits
CarolineConcatto marked 2 inline comments as done.
CarolineConcatto added inline comments.



Comment at: clang/include/clang/Basic/arm_sve.td:56
 // P: boolean
+// Qa: svcount
 // U: unsigned

hassnaa-arm wrote:
> sdesmalen wrote:
> > The typespec modifier in this file can remain `Q` rather than `Qa`. Can you 
> > change it back?
> what if there is a new type that is target-specific ?
> At that case we will have to find a new character.
> But if we now use Qa, we can use Qb for the new type.
> Is that correct ?
This is now removed. I thought that should reflect what is in Builtins.def, but 
it does not.
Because Q is being defined in sve target we do not the 'a' in 'Qa'


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150953/new/

https://reviews.llvm.org/D150953

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


[PATCH] D148793: [clang-tidy] Implement an include-cleaner check.

2023-05-31 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:186
 
+- New :doc:`misc-include-cleaner
+  ` check.

Please keep alphabetical order (by check name) in this section.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:189
+
+  Checks for unused and missing includes. Generates findings only for
+  the main file of a translation unit.

One sentence is enough.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148793/new/

https://reviews.llvm.org/D148793

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


[PATCH] D151121: [Clang][UBSan] Fix the crash caused by __builtin_assume_aligned with -no-opaque-pointers enabled

2023-05-31 Thread Yurong via Phabricator via cfe-commits
yronglin added a comment.

ping~


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151121/new/

https://reviews.llvm.org/D151121

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


[PATCH] D151741: [Lex] Only warn on defining or undefining language-defined builtins

2023-05-31 Thread John Brawn via Phabricator via cfe-commits
john.brawn updated this revision to Diff 527024.
john.brawn added a comment.

Add more testing.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151741/new/

https://reviews.llvm.org/D151741

Files:
  clang/lib/Lex/PPDirectives.cpp
  clang/test/Preprocessor/macro-reserved.c


Index: clang/test/Preprocessor/macro-reserved.c
===
--- clang/test/Preprocessor/macro-reserved.c
+++ clang/test/Preprocessor/macro-reserved.c
@@ -7,6 +7,7 @@
 #define _HAVE_X 0
 #define X__Y
 #define __STDC__ 1 // expected-warning {{redefining builtin macro}}
+#define __clang__ 1
 
 #undef for
 #undef final
@@ -15,6 +16,12 @@
 #undef _HAVE_X
 #undef X__Y
 #undef __STDC_HOSTED__ // expected-warning {{undefining builtin macro}}
+#undef __INT32_TYPE__
+#undef __UINT32_TYPE__
+#undef __UINTPTR_TYPE__
+#undef __i386__
+#undef __UINT64_TYPE__
+#undef __INT64_TYPE__
 
 // allowlisted definitions
 #define while while
Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -150,6 +150,30 @@
 MacroName);
 }
 
+static bool isLanguageDefinedBuiltin(const SourceManager &SourceMgr,
+ const MacroInfo *MI,
+ const StringRef MacroName) {
+  // If this is a macro with special handling (like __LINE__) then it's 
language
+  // defined.
+  if (MI->isBuiltinMacro())
+return true;
+  // Builtin macros are defined in the builtin file
+  if (!SourceMgr.isWrittenInBuiltinFile(MI->getDefinitionLoc()))
+return false;
+  // C defines macros starting with __STDC, and C++ defines macros starting 
with
+  // __STDCPP
+  if (MacroName.startswith("__STDC"))
+return true;
+  // C++ defines the __cplusplus macro
+  if (MacroName == "__cplusplus")
+return true;
+  // C++ defines various feature-test macros starting with __cpp
+  if (MacroName.startswith("__cpp"))
+return true;
+  // Anything else isn't language-defined
+  return false;
+}
+
 static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
   const LangOptions &Lang = PP.getLangOpts();
   StringRef Text = II->getName();
@@ -3107,9 +3131,7 @@
 
   // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
   // C++ [cpp.predefined]p4, but allow it as an extension.
-  if (OtherMI->isBuiltinMacro() ||
-  (SourceMgr.isWrittenInBuiltinFile(OtherMI->getDefinitionLoc()) &&
-   !isFeatureTestMacro(MacroNameTok.getIdentifierInfo()->getName(
+  if (isLanguageDefinedBuiltin(SourceMgr, OtherMI, II->getName()))
 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
   // Macros must be identical.  This means all tokens and whitespace
   // separation must be the same.  C99 6.10.3p2.
@@ -3190,11 +3212,8 @@
   Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
 
 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4 and
-// C++ [cpp.predefined]p4, but allow it as an extension. Don't warn if this
-// is an Objective-C builtin macro though.
-if ((MI->isBuiltinMacro() ||
- SourceMgr.isWrittenInBuiltinFile(MI->getDefinitionLoc())) &&
-!(getLangOpts().ObjC && isObjCProtectedMacro(II)))
+// C++ [cpp.predefined]p4, but allow it as an extension.
+if (isLanguageDefinedBuiltin(SourceMgr, MI, II->getName()))
   Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
 
 if (MI->isWarnIfUnused())


Index: clang/test/Preprocessor/macro-reserved.c
===
--- clang/test/Preprocessor/macro-reserved.c
+++ clang/test/Preprocessor/macro-reserved.c
@@ -7,6 +7,7 @@
 #define _HAVE_X 0
 #define X__Y
 #define __STDC__ 1 // expected-warning {{redefining builtin macro}}
+#define __clang__ 1
 
 #undef for
 #undef final
@@ -15,6 +16,12 @@
 #undef _HAVE_X
 #undef X__Y
 #undef __STDC_HOSTED__ // expected-warning {{undefining builtin macro}}
+#undef __INT32_TYPE__
+#undef __UINT32_TYPE__
+#undef __UINTPTR_TYPE__
+#undef __i386__
+#undef __UINT64_TYPE__
+#undef __INT64_TYPE__
 
 // allowlisted definitions
 #define while while
Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -150,6 +150,30 @@
 MacroName);
 }
 
+static bool isLanguageDefinedBuiltin(const SourceManager &SourceMgr,
+ const MacroInfo *MI,
+ const StringRef MacroName) {
+  // If this is a macro with special handling (like __LINE__) then it's language
+  // defined.
+  if (MI->isBuiltinMacro())
+return true;
+  // Builtin macros are defined in the builtin file
+  if (!SourceMgr.isWrittenInBuiltinFile(MI->getDefinitionLoc()))
+return false;
+  //

[PATCH] D151325: [analyzer] Differentiate lifetime extended temporaries

2023-05-31 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource updated this revision to Diff 527027.
tomasz-kaminski-sonarsource added a comment.

Added function to query stack frame for temporary object.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151325/new/

https://reviews.llvm.org/D151325

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/Regions.def
  clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/test/Analysis/lifetime-extended-regions.cpp
  clang/test/Analysis/stack-addr-ps.cpp
  clang/test/Analysis/use-after-move.cpp

Index: clang/test/Analysis/use-after-move.cpp
===
--- clang/test/Analysis/use-after-move.cpp
+++ clang/test/Analysis/use-after-move.cpp
@@ -613,6 +613,14 @@
   }
 }
 
+void lifeTimeExtendTest() {
+  A&& a = A{};
+  A b = std::move(a); // peaceful-note {{Object is moved}}
+
+  a.foo(); // peaceful-warning {{Method called on moved-from object}}
+   // peaceful-note@-1 {{Method called on moved-from object}}
+}
+
 void interFunTest1(A &a) {
   a.bar(); // peaceful-warning {{Method called on moved-from object 'a'}}
// peaceful-note@-1 {{Method called on moved-from object 'a'}}
Index: clang/test/Analysis/stack-addr-ps.cpp
===
--- clang/test/Analysis/stack-addr-ps.cpp
+++ clang/test/Analysis/stack-addr-ps.cpp
@@ -30,13 +30,13 @@
 
 const int &get_reference2() {
   const int &x = get_value(); // expected-note {{binding reference variable 'x' here}}
-  return x; // expected-warning{{Address of stack memory associated with temporary object of type 'int' returned}} expected-warning {{returning reference to local temporary}}
+  return x; // expected-warning{{Address of stack memory associated with temporary object of type 'int' lifetime extended by local variable 'x' returned to caller}} expected-warning {{returning reference to local temporary}} 
 }
 
 const int &get_reference3() {
   const int &x1 = get_value(); // expected-note {{binding reference variable 'x1' here}}
   const int &x2 = x1; // expected-note {{binding reference variable 'x2' here}}
-  return x2; // expected-warning{{Address of stack memory associated with temporary object of type 'int' returned}} expected-warning {{returning reference to local temporary}}
+  return x2; // expected-warning{{Address of stack memory associated with temporary object of type 'int' lifetime extended by local variable 'x1' returned to caller}} expected-warning {{returning reference to local temporary}}
 }
 
 int global_var;
@@ -60,7 +60,7 @@
 const int *f4() {
   const int &x1 = get_value(); // expected-note {{binding reference variable 'x1' here}}
   const int &x2 = x1; // expected-note {{binding reference variable 'x2' here}}
-  return &x2; // expected-warning{{Address of stack memory associated with temporary object of type 'int' returned}} expected-warning {{returning address of local temporary}}
+  return &x2; // expected-warning{{Address of stack memory associated with temporary object of type 'int' lifetime extended by local variable 'x1' returned to caller}} expected-warning {{returning address of local temporary}}
 }
 
 struct S {
Index: clang/test/Analysis/lifetime-extended-regions.cpp
===
--- /dev/null
+++ clang/test/Analysis/lifetime-extended-regions.cpp
@@ -0,0 +1,170 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection\
+// RUN:-Wno-dangling -Wno-c++1z-extensions\
+// RUN:-verify=expected,cpp14\
+// RUN:-x c++ -std=c++14 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection\
+// RUN:-analyzer-config elide-constructors=false\
+// RUN:-Wno-dangling -Wno-c++1z-extensions\
+// RUN:-verify=expected,cpp14\
+// RUN:-x c++ -std=c++14 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection\
+// RUN:-Wno-dangling -verify=expected,cpp17\
+// RUN:-x c++ -std=c++17 %s
+
+template
+void clang_analyzer_dump(T&&) {}
+
+template
+T create() { return T{}; }
+
+template
+T const& select(bool cond, T const& t, T const& u) { return cond ? t : u; }
+
+struct Composite {
+  int x;
+  int y;
+};
+
+struct Derived : Composite {
+  int z;
+};
+
+template
+struct Array {
+  T array[20];
+
+  T&& fr

[PATCH] D149444: [ARM] Allow codegen for Armv6m eXecute-Only (XO) sections

2023-05-31 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/arm-execute-only.c:1
-// RUN: not %clang -c -target thumbv6m-eabi -mexecute-only %s 2>&1 | \
+// RUN: %clang -c -target thumbv6m-eabi -mexecute-only %s 2>&1 | \
+// RUN:   FileCheck -allow-empty --check-prefix CHECK-THIS %s

test/Driver tests should test just the Driver part, not sema/codegen, so we 
generally use `-###` to skip compilation.

`-target ` has been deprecated since 3.x. Use `--target=`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D149444/new/

https://reviews.llvm.org/D149444

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


[PATCH] D149444: [ARM] Allow codegen for Armv6m eXecute-Only (XO) sections

2023-05-31 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: llvm/lib/Target/ARM/ARMSubtarget.cpp:195
+if (!hasV6MOps())
+  llvm_unreachable("Cannot generate execute-only code for this target");
   }

If this code path is actually reachable, a proper error reporting will be 
better. At the least `report_fatal_error` can be used. Don't use 
`llvm_unreachable` for known-reachable code paths.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D149444/new/

https://reviews.llvm.org/D149444

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


[PATCH] D151741: [Lex] Only warn on defining or undefining language-defined builtins

2023-05-31 Thread John Brawn via Phabricator via cfe-commits
john.brawn marked an inline comment as done.
john.brawn added inline comments.



Comment at: clang/lib/Lex/PPDirectives.cpp:163-172
+  // C defines macros starting with __STDC, and C++ defines macros starting 
with
+  // __STDCPP
+  if (MacroName.startswith("__STDC"))
+return true;
+  // C++ defines the __cplusplus macro
+  if (MacroName == "__cplusplus")
+return true;

nickdesaulniers wrote:
> Should these depend on LangOpt?
I don't think so. If we're e.g. not compiling C++ then __cplusplus won't be 
defined so it doesn't matter if we check for it.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151741/new/

https://reviews.llvm.org/D151741

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


[PATCH] D150985: [clang] Allow fp in atomic fetch max/min builtins

2023-05-31 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 527034.
yaxunl added a comment.

rebase


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150985/new/

https://reviews.llvm.org/D150985

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGenCUDA/amdgpu-atomic-ops.cu
  clang/test/Sema/atomic-ops.c
  clang/test/SemaOpenCL/atomic-ops.cl

Index: clang/test/SemaOpenCL/atomic-ops.cl
===
--- clang/test/SemaOpenCL/atomic-ops.cl
+++ clang/test/SemaOpenCL/atomic-ops.cl
@@ -61,8 +61,10 @@
 
   __opencl_atomic_fetch_min(i, 1, memory_order_seq_cst, memory_scope_work_group);
   __opencl_atomic_fetch_max(i, 1, memory_order_seq_cst, memory_scope_work_group);
-  __opencl_atomic_fetch_min(f, 1, memory_order_seq_cst, memory_scope_work_group); // expected-error {{address argument to atomic operation must be a pointer to atomic integer ('__generic atomic_float *' (aka '__generic _Atomic(float) *') invalid)}}
-  __opencl_atomic_fetch_max(f, 1, memory_order_seq_cst, memory_scope_work_group); // expected-error {{address argument to atomic operation must be a pointer to atomic integer ('__generic atomic_float *' (aka '__generic _Atomic(float) *') invalid)}}
+  __opencl_atomic_fetch_min(f, 1, memory_order_seq_cst, memory_scope_work_group);
+  __opencl_atomic_fetch_max(f, 1, memory_order_seq_cst, memory_scope_work_group);
+  __opencl_atomic_fetch_min(d, 1, memory_order_seq_cst, memory_scope_work_group);
+  __opencl_atomic_fetch_max(d, 1, memory_order_seq_cst, memory_scope_work_group);
 
   bool cmpexch_1 = __opencl_atomic_compare_exchange_strong(i, I, 1, memory_order_seq_cst, memory_order_seq_cst, memory_scope_work_group);
   bool cmpexch_2 = __opencl_atomic_compare_exchange_strong(p, P, 1, memory_order_seq_cst, memory_order_seq_cst, memory_scope_work_group);
Index: clang/test/Sema/atomic-ops.c
===
--- clang/test/Sema/atomic-ops.c
+++ clang/test/Sema/atomic-ops.c
@@ -199,14 +199,24 @@
   __c11_atomic_fetch_add(f, 1.0f, memory_order_seq_cst);
   __c11_atomic_fetch_add(d, 1.0, memory_order_seq_cst);
   __c11_atomic_fetch_add(ld, 1.0, memory_order_seq_cst); // fp80-error {{must be a pointer to atomic integer, pointer or supported floating point type}}
+  __c11_atomic_fetch_min(i, 1, memory_order_seq_cst);
+  __c11_atomic_fetch_min(p, 1, memory_order_seq_cst); // expected-error {{must be a pointer to atomic integer or supported floating point type}}
+  __c11_atomic_fetch_min(f, 1.0f, memory_order_seq_cst);
+  __c11_atomic_fetch_min(d, 1.0, memory_order_seq_cst);
+  __c11_atomic_fetch_min(ld, 1.0, memory_order_seq_cst); // fp80-error {{must be a pointer to atomic integer or supported floating point type}}
+  __c11_atomic_fetch_max(i, 1, memory_order_seq_cst);
+  __c11_atomic_fetch_max(p, 1, memory_order_seq_cst); // expected-error {{must be a pointer to atomic integer or supported floating point type}}
+  __c11_atomic_fetch_max(f, 1.0f, memory_order_seq_cst);
+  __c11_atomic_fetch_max(d, 1.0, memory_order_seq_cst);
+  __c11_atomic_fetch_max(ld, 1.0, memory_order_seq_cst); // fp80-error {{must be a pointer to atomic integer or supported floating point type}}
 
   __atomic_fetch_add(i, 3, memory_order_seq_cst); // expected-error {{pointer to integer, pointer or supported floating point type}}
   __atomic_fetch_sub(I, 3, memory_order_seq_cst);
   __atomic_fetch_sub(P, 3, memory_order_seq_cst);
   __atomic_fetch_sub(D, 3, memory_order_seq_cst);
   __atomic_fetch_sub(s1, 3, memory_order_seq_cst); // expected-error {{must be a pointer to integer, pointer or supported floating point type}}
-  __atomic_fetch_min(D, 3, memory_order_seq_cst); // expected-error {{must be a pointer to integer}}
-  __atomic_fetch_max(P, 3, memory_order_seq_cst); // expected-error {{must be a pointer to integer}}
+  __atomic_fetch_min(D, 3, memory_order_seq_cst);
+  __atomic_fetch_max(P, 3, memory_order_seq_cst); // expected-error {{must be a pointer to integer or supported floating point type}}
   __atomic_fetch_max(p, 3);   // expected-error {{too few arguments to function call, expected 3, have 2}}
 
   __c11_atomic_fetch_and(i, 1, memory_order_seq_cst);
Index: clang/test/CodeGenCUDA/amdgpu-atomic-ops.cu
===
--- clang/test/CodeGenCUDA/amdgpu-atomic-ops.cu
+++ clang/test/CodeGenCUDA/amdgpu-atomic-ops.cu
@@ -1,29 +1,98 @@
-// RUN: %clang_cc1 %s -emit-llvm -o - -triple=amdgcn-amd-amdhsa \
+// RUN: %clang_cc1 -x hip %s -emit-llvm -o - -triple=amdgcn-amd-amdhsa \
 // RUN:   -fcuda-is-device -target-cpu gfx906 -fnative-half-type \
 // RUN:   -fnative-half-arguments-and-returns | FileCheck %s
 
+// RUN: %clang_cc1 -x hip %s -O3 -S -o - -triple=amdgcn-amd-amdhsa \
+// RUN:   -fcuda-is-device -target-cpu gfx1100 -fnative-half-type \
+// RUN:   -fnative-half-arguments-and-returns | Fi

[PATCH] D150430: Implement BufferOverlap check for sprint/snprintf

2023-05-31 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

TBH we don't really have processes there. And its a bit of a mess, regarding 
CSA.  Usually we forgot to update the release notes, and at best we aggregate 
the changes just prior a release for the release notes. But we haven't done it 
for the last two releases for sure.

I was thinking of asking you, but given this context we wouldn't gain much. We 
would still need to go through the diffs anyway. So, let not touch the notes 
now.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150430/new/

https://reviews.llvm.org/D150430

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


[PATCH] D148490: [AIX] use system assembler for assembly files

2023-05-31 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/target-as.s:1
 // Make sure the -march is passed down to cc1as.
 // RUN: %clang -target i386-unknown-freebsd -### -c -integrated-as %s \

aix-as.c will be more appropriate.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148490/new/

https://reviews.llvm.org/D148490

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


[PATCH] D151088: [flang][hlfir] Separate -emit-fir and -emit-hlfir for flang-new

2023-05-31 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:651
+// Lower using HLFIR then run the FIR to HLFIR pipeline
+void CodeGenAction::lowerHLFIRToFIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");

tblah wrote:
> awarzynski wrote:
> > I wouldn't really consider this hook as a separate action. Instead, I'd use 
> > it here: 
> > https://github.com/llvm/llvm-project/blob/6130c9df99a7a7eb9c6adc118a48f8f2acc534ab/flang/lib/Frontend/FrontendActions.cpp#L917-L920.
> >  As in, it basically "tweaks" `EmitMLIR` (which I would rename as 
> > `EmitFIR`).
> This is very different to `EmitMLIR`.
> 
> `EmitMLIR` will print the MLIR produced by lowering (HLFIR or FIR depending 
> upon the `-flang-experimental-hlfir` flag).
> 
> This action will run lowering, always generating HLFIR. Then it will run the 
> HLFIR pass pipeline to lower the HLFIR into FIR, and output that FIR (which 
> will be very different to FIR generated directly from lowering without going 
> through HLFIR).
So, at the moment:
* `EmitMLIR` will generate either FIR of HLFIR,
* `lowerHLFIRToFIR` will also generate FIR via HFLIR.

When `-flang-experimental-hlfir` is used, both actions do the same thing 
(**what**) - generate FIR. The difference becomes in **how** this is achieved.  
However, actions represent "what", not "how" and hence my suggestion. In fact,  
this would be totally valid:
```
  /// (with `-flang-experimental-hlfir`) Lower to FIR and print
  EmitMLIR,

  /// Lower to FIR and print, go via HLFIR
  EmitHLFIRToFIR,
```
With `EmitFIR` and `EmitHLFIR` (instead of `EmitMLIR` and `EmitHLFIRToFIR`), 
you'd preserve all the functionality and also make sure that there's never 
overlap between actions, right? Additionally, you'd still have 
`-flang-experimental-hlfir` that would tweak `EmitFIR`).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151088/new/

https://reviews.llvm.org/D151088

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


[PATCH] D151709: [Clang][SVE2.1] Add builtins for svrevd

2023-05-31 Thread Dinar Temirbulatov via Phabricator via cfe-commits
dtemirbulatov accepted this revision.
dtemirbulatov added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151709/new/

https://reviews.llvm.org/D151709

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


[PATCH] D151608: [Sema] Remove unused function getFloat128Identifier

2023-05-31 Thread Nico Weber via Phabricator via cfe-commits
thakis accepted this revision.
thakis added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D151608/new/

https://reviews.llvm.org/D151608

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


  1   2   3   >