[PATCH] D137269: [Clang][AArch64][Darwin] Enable GlobalISel by default for Darwin ARM64 platforms.

2022-11-10 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

In D137269#3916911 , @fhahn wrote:

> It looks like GISel crashes when building `llvm-test-suite` with -O3 on 
> ARM64. If it isn't trivial to fix we should probably revert the patch to 
> bring things back to green.
>
> Reproducer:
>
>   ; llc  -global-isel -O3
>   target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128"
>   target triple = "arm64-apple-macosx"
>   
>   define void @widget(ptr %arg, i1 %arg1) {
>   bb:
> br i1 %arg1, label %bb2, label %bb3
>   
>   bb2:  ; preds = %bb
> %tmp = icmp slt i32 0, 0
> br i1 %tmp, label %bb3, label %bb9
>   
>   bb3:  ; preds = %bb2, %bb
> %tmp4 = phi i32 [ 1, %bb ], [ 0, %bb2 ]
> %tmp5 = zext i32 %tmp4 to i64
> br label %bb6
>   
>   bb6:  ; preds = %bb6, %bb3
> %tmp7 = getelementptr i32, ptr %arg, i64 %tmp5
> %tmp8 = getelementptr i32, ptr %tmp7, i64 4
> store <4 x i32> zeroinitializer, ptr %tmp8, align 4
> br label %bb6
>   
>   bb9:  ; preds = %bb2
> ret void
>   }
>
> https://llvm.godbolt.org/z/d5oTWxvaG

There are a few minor issues here. There are a handle of g_ptr_add combines 
which are creating offsets with the non-canonical size, and then others that 
don't consider that the size could be different


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137269

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


[PATCH] D137706: [clang][Interp] Implement IntegralToPointer casts

2022-11-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 474459.

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

https://reviews.llvm.org/D137706

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/Pointer.cpp
  clang/lib/AST/Interp/Pointer.h
  clang/test/Sema/const-eval-64.c

Index: clang/test/Sema/const-eval-64.c
===
--- clang/test/Sema/const-eval-64.c
+++ clang/test/Sema/const-eval-64.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -triple x86_64-linux %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple x86_64-linux -fexperimental-new-constant-interpreter %s
 
 #define EVAL_EXPR(testno, expr) int test##testno = sizeof(struct{char qq[expr];});
 
Index: clang/lib/AST/Interp/Pointer.h
===
--- clang/lib/AST/Interp/Pointer.h
+++ clang/lib/AST/Interp/Pointer.h
@@ -67,6 +67,7 @@
   Pointer() {}
   Pointer(Block *B);
   Pointer(Block *B, unsigned BaseAndOffset);
+  Pointer(unsigned Offset);
   Pointer(const Pointer &P);
   Pointer(Pointer &&P);
   ~Pointer();
@@ -79,6 +80,8 @@
 
   /// Offsets a pointer inside an array.
   Pointer atIndex(unsigned Idx) const {
+if (!Pointee)
+  return Pointer(nullptr, 0, Offset + Idx);
 if (Base == RootPtrMark)
   return Pointer(Pointee, RootPtrMark, getDeclDesc()->getSize());
 unsigned Off = Idx * elemSize();
@@ -160,14 +163,17 @@
   }
 
   /// Checks if the pointer is null.
-  bool isZero() const { return Pointee == nullptr; }
+  bool isZero() const { return Pointee == nullptr && Offset == 0; }
   /// Checks if the pointer is live.
   bool isLive() const { return Pointee && !Pointee->IsDead; }
   /// Checks if the item is a field in an object.
   bool isField() const { return Base != 0 && Base != RootPtrMark; }
 
   /// Accessor for information about the declaration site.
-  Descriptor *getDeclDesc() const { return Pointee->Desc; }
+  Descriptor *getDeclDesc() const {
+assert(Pointee);
+return Pointee->Desc;
+  }
   SourceLocation getDeclLoc() const { return getDeclDesc()->getLocation(); }
 
   /// Returns a pointer to the object of which this pointer is a field.
@@ -232,12 +238,12 @@
   }
 
   /// Checks if the innermost field is an array.
-  bool inArray() const { return getFieldDesc()->IsArray; }
+  bool inArray() const { return Pointee ? getFieldDesc()->IsArray : false; }
   /// Checks if the structure is a primitive array.
   bool inPrimitiveArray() const { return getFieldDesc()->isPrimitiveArray(); }
   /// Checks if the structure is an array of unknown size.
   bool isUnknownSizeArray() const {
-return getFieldDesc()->isUnknownSizeArray();
+return Pointee ? getFieldDesc()->isUnknownSizeArray() : false;
   }
   /// Checks if the pointer points to an array.
   bool isArrayElement() const { return Base != Offset; }
@@ -288,12 +294,20 @@
   }
 
   /// Returns the number of elements.
-  unsigned getNumElems() const { return getSize() / elemSize(); }
+  unsigned getNumElems() const {
+if (Pointee)
+  return getSize() / elemSize();
+
+return std::numeric_limits::max();
+  }
 
   Block *block() const { return Pointee; }
 
   /// Returns the index into an array.
   int64_t getIndex() const {
+if (!Pointee)
+  return 0;
+
 if (isElementPastEnd())
   return 1;
 if (auto ElemSize = elemSize())
@@ -307,7 +321,7 @@
   }
 
   /// Checks if the pointer is an out-of-bounds element pointer.
-  bool isElementPastEnd() const { return Offset == PastEndMark; }
+  bool isElementPastEnd() const { return Pointee && Offset == PastEndMark; }
 
   /// Dereferences the pointer, if it's live.
   template  T &deref() const {
Index: clang/lib/AST/Interp/Pointer.cpp
===
--- clang/lib/AST/Interp/Pointer.cpp
+++ clang/lib/AST/Interp/Pointer.cpp
@@ -19,6 +19,8 @@
 Pointer::Pointer(Block *Pointee, unsigned BaseAndOffset)
 : Pointer(Pointee, BaseAndOffset, BaseAndOffset) {}
 
+Pointer::Pointer(unsigned Offset) : Pointer(nullptr, Offset, Offset) {}
+
 Pointer::Pointer(const Pointer &P) : Pointer(P.Pointee, P.Base, P.Offset) {}
 
 Pointer::Pointer(Pointer &&P)
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -522,6 +522,11 @@
   let HasGroup = 1;
 }
 
+def CastIntegralPointer : Opcode {
+  let Types = [AluTypeClass];
+  let HasGroup = 1;
+}
+
 //===--===//
 // Comparison opcodes.
 //===--===//
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -1249,6 +1249,13 @@

[PATCH] D137693: [NFC] [C++20] [Modules] [clangd] Add test for code completion for C++20 Named Modules

2022-11-10 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 474462.
ChuanqiXu added a comment.

Set the path to clang correctly.


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

https://reviews.llvm.org/D137693

Files:
  clang-tools-extra/clangd/test/CMakeLists.txt
  clang-tools-extra/clangd/test/completion-modules.test
  clang-tools-extra/clangd/test/completion-modules2.test
  clang-tools-extra/clangd/test/completion-modules3.test
  clang-tools-extra/clangd/test/completion-modules4.test

Index: clang-tools-extra/clangd/test/completion-modules4.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/completion-modules4.test
@@ -0,0 +1,77 @@
+# Tests that the importee can't find the entities in the global module fragment.
+# RUN: rm -fr %t
+# RUN: mkdir -p %t
+# RUN: split-file %s %t
+#
+# RUN: sed -e "s|DIR|%/t|g" %t/compile_commands.json.tmpl > %t/compile_commands.json.tmp
+# RUN: sed -e "s|CLANG_CC|%clang|g" %t/compile_commands.json.tmp > %t/compile_commands.json
+# RUN: sed -e "s|DIR|%/t|g" %t/definition.jsonrpc.tmpl > %t/definition.jsonrpc
+# RUN: %clang -std=c++20 %t/A.cppm --precompile -o %t/A.pcm
+# RUN: clangd -lit-test < %t/definition.jsonrpc  | FileCheck %t/definition.jsonrpc
+
+#--- foo.h
+void printA() {}
+
+#--- A.cppm
+module;
+#include "foo.h"
+export module A;
+
+
+#--- Use.cpp
+import A;
+void foo() {
+print
+}
+
+#--- compile_commands.json.tmpl
+[
+{
+  "directory": "DIR",
+  "command": "clang++  -fprebuilt-module-path=DIR -std=c++20 -o DIR/main.cpp.o -c DIR/Use.cpp",
+  "file": "DIR/Use.cpp"
+}
+]
+
+#--- definition.jsonrpc.tmpl
+{
+  "jsonrpc": "2.0",
+  "id": 0,
+  "method": "initialize",
+  "params": {
+"processId": 123,
+"rootPath": "clangd",
+"capabilities": {
+  "textDocument": {
+"completion": {
+  "completionItem": {
+"snippetSupport": true
+  }
+}
+  }
+},
+"trace": "off"
+  }
+}
+---
+{
+  "jsonrpc": "2.0",
+  "method": "textDocument/didOpen",
+  "params": {
+"textDocument": {
+  "uri": "file://DIR/Use.cpp",
+  "languageId": "cpp",
+  "version": 1,
+  "text": "import A;\nvoid foo() {\nprint\n}\n"
+}
+  }
+}
+
+# CHECK-NOT: "filterText": "printA"
+
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/completion","params":{"textDocument":{"uri":"file://DIR/Use.cpp"},"context":{"triggerKind":1},"position":{"line":2,"character":6}}}
+---
+{"jsonrpc":"2.0","id":2,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: clang-tools-extra/clangd/test/completion-modules3.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/completion-modules3.test
@@ -0,0 +1,98 @@
+# Tests that the importee can find the exported entities.
+# RUN: rm -fr %t
+# RUN: mkdir -p %t
+# RUN: split-file %s %t
+#
+# RUN: sed -e "s|DIR|%/t|g" %t/compile_commands.json.tmpl > %t/compile_commands.json.tmp
+# RUN: sed -e "s|CLANG_CC|%clang|g" %t/compile_commands.json.tmp > %t/compile_commands.json
+# RUN: sed -e "s|DIR|%/t|g" %t/definition.jsonrpc.tmpl > %t/definition.jsonrpc
+# RUN: %clang -std=c++20 %t/A.cppm --precompile -o %t/A.pcm
+# RUN: clangd -lit-test < %t/definition.jsonrpc  | FileCheck -strict-whitespace %t/definition.jsonrpc
+
+#--- A.cppm
+export module A;
+void printA() {}
+
+#--- Use.cpp
+export module A:part;
+import A;
+void foo() {
+print
+}
+
+#--- compile_commands.json.tmpl
+[
+{
+  "directory": "DIR",
+  "command": "clang++  -fprebuilt-module-path=DIR -std=c++20 -o DIR/main.cpp.o -c DIR/Use.cpp",
+  "file": "DIR/Use.cpp"
+}
+]
+
+#--- definition.jsonrpc.tmpl
+{
+  "jsonrpc": "2.0",
+  "id": 0,
+  "method": "initialize",
+  "params": {
+"processId": 123,
+"rootPath": "clangd",
+"capabilities": {
+  "textDocument": {
+"completion": {
+  "completionItem": {
+"snippetSupport": true
+  }
+}
+  }
+},
+"trace": "off"
+  }
+}
+---
+{
+  "jsonrpc": "2.0",
+  "method": "textDocument/didOpen",
+  "params": {
+"textDocument": {
+  "uri": "file://DIR/Use.cpp",
+  "languageId": "cpp",
+  "version": 1,
+  "text": "export module A:part;\nimport A;\nvoid foo() {\nprint\n}\n"
+}
+  }
+}
+
+# CHECK:  "id": 1,
+# CHECK-NEXT:  "jsonrpc": "2.0",
+# CHECK-NEXT:  "result": {
+# CHECK-NEXT:"isIncomplete": false,
+# CHECK-NEXT:"items": [
+# CHECK-NEXT:  {
+# CHECK-NEXT:"detail": "void",
+# CHECK-NEXT:"filterText": "printA",
+# CHECK-NEXT:"insertText": "printA()",
+# CHECK-NEXT:"insertTextFormat": 2,
+# CHECK-NEXT:"kind": 3,
+# CHECK-NEXT:"label": " printA()",
+# CHECK-NEXT:"score":
+# CHECK-NEXT:"sortText": "409fc4f5printA",
+# CHECK-NEXT:"textEdit": {
+# CHECK-NEXT:  "newText": "printA()",
+# CHECK-NEXT:  "range": {
+# CHECK-NEXT:

[PATCH] D129156: Add -fpass-plugin option to Flang

2022-11-10 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Please be aware of https://reviews.llvm.org/D137673 - you may need to rebase if 
it lands before this patch.

Please just go ahead and merge, but please keep `WIN32` in the final version of 
"flang/test/CMakeLists.txt" (see my comment inline).

LGTM




Comment at: flang/test/CMakeLists.txt:65
 )
+if (NOT WIN32)
+  list(APPEND FLANG_TEST_DEPENDS Bye)

awarzynski wrote:
> IIUC, `Bye` is only needed when plugins are enabled.
IIUC, `WIN32` is still required. Sorry for not being clearer earlier.


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

https://reviews.llvm.org/D129156

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


[clang] 04fb3e3 - [C++20] [Modules] Document the behavior about reserved module names

2022-11-10 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-11-10T16:43:50+08:00
New Revision: 04fb3e3de7329a11b75c77fc418e3e5f5ddcac77

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

LOG: [C++20] [Modules] Document the behavior about reserved module names

We would diagnose about the reserved names in b8ceb9f4e4bd. And the
patch documents about the related behaviors.

Added: 


Modified: 
clang/docs/StandardCPlusPlusModules.rst

Removed: 




diff  --git a/clang/docs/StandardCPlusPlusModules.rst 
b/clang/docs/StandardCPlusPlusModules.rst
index 021edbc3dfdf..c9790703e2ee 100644
--- a/clang/docs/StandardCPlusPlusModules.rst
+++ b/clang/docs/StandardCPlusPlusModules.rst
@@ -270,6 +270,40 @@ we can't compile them by the original command lines. But 
we are still able to do
   $ ./Hello.out
   Hello World!
 
+Module name requirement
+~~~
+
+[module.unit]p1 says:
+
+> All module-names either beginning with an identifier consisting of std 
followed by zero
+  or more digits or containing a reserved identifier ([lex.name]) are reserved 
and shall not
+  be specified in a module-declaration; no diagnostic is required. If any 
identifier in a reserved
+  module-name is a reserved identifier, the module name is reserved for use by 
C++ implementations;
+  otherwise it is reserved for future standardization.
+
+So all of the following name is not valid by default:
+
+.. code-block:: text
+
+std
+std1
+std.foo
+__test
+// and so on ...
+
+If you still want to use the reserved module names for any reason, currently 
you can add a special line marker
+in the front of the module declaration like:
+
+.. code-block:: c++
+
+  # __LINE_NUMBER__ __FILE__ 1 3
+  export moudle std;
+
+Here the `__LINE_NUMBER__` is the actual line number of the corresponding 
line. The `__FILE__` means the filename
+of the translation unit. The `1` means the following is a new file. And `3` 
means this is a system header/file so
+the certain warnings should be suppressed. You could find more details at:
+https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp_9.html.
+
 How to specify the dependent BMIs
 ~
 



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


[PATCH] D137650: [clangd] Implement hover for string literals

2022-11-10 Thread v1nh1shungry via Phabricator via cfe-commits
v1nh1shungry updated this revision to Diff 474466.
v1nh1shungry added a comment.

Modify the name in the hover info


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137650

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1300,7 +1300,6 @@
   "auto x = ^42.0i;",
   "auto x = ^42;",
   "auto x = ^nullptr;",
-  "auto x = ^\"asdf\";",
   };
 
   for (const auto &Test : Tests) {
@@ -1326,6 +1325,12 @@
  HI.Type = "char";
  HI.Value = "65 (0x41)";
}},
+  {"auto s = ^[[\"Hello, world!\"]]; // string literal",
+   [](HoverInfo &HI) {
+ HI.Name = "string-literal";
+ HI.Size = 14;
+ HI.Type = "const char[14]";
+   }},
   {
   R"cpp(// Local variable
 int main() {
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -777,6 +777,17 @@
   return HI;
 }
 
+HoverInfo getStringLiteralContents(const StringLiteral *SL,
+   const PrintingPolicy &PP) {
+  HoverInfo HI;
+
+  HI.Name = "string-literal";
+  HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth();
+  HI.Type = SL->getType().getAsString(PP).c_str();
+
+  return HI;
+}
+
 bool isLiteral(const Expr *E) {
   // Unfortunately there's no common base Literal classes inherits from
   // (apart from Expr), therefore these exclusions.
@@ -785,7 +796,7 @@
  llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
- llvm::isa(E) || llvm::isa(E);
+ llvm::isa(E);
 }
 
 llvm::StringLiteral getNameForExpr(const Expr *E) {
@@ -810,6 +821,9 @@
 return llvm::None;
 
   HoverInfo HI;
+  // Print the type and the size for string literals
+  if (const StringLiteral *SL = dyn_cast(E))
+return getStringLiteralContents(SL, PP);
   // For `this` expr we currently generate hover with pointee type.
   if (const CXXThisExpr *CTE = dyn_cast(E))
 return getThisExprHoverContents(CTE, AST.getASTContext(), PP);


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1300,7 +1300,6 @@
   "auto x = ^42.0i;",
   "auto x = ^42;",
   "auto x = ^nullptr;",
-  "auto x = ^\"asdf\";",
   };
 
   for (const auto &Test : Tests) {
@@ -1326,6 +1325,12 @@
  HI.Type = "char";
  HI.Value = "65 (0x41)";
}},
+  {"auto s = ^[[\"Hello, world!\"]]; // string literal",
+   [](HoverInfo &HI) {
+ HI.Name = "string-literal";
+ HI.Size = 14;
+ HI.Type = "const char[14]";
+   }},
   {
   R"cpp(// Local variable
 int main() {
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -777,6 +777,17 @@
   return HI;
 }
 
+HoverInfo getStringLiteralContents(const StringLiteral *SL,
+   const PrintingPolicy &PP) {
+  HoverInfo HI;
+
+  HI.Name = "string-literal";
+  HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth();
+  HI.Type = SL->getType().getAsString(PP).c_str();
+
+  return HI;
+}
+
 bool isLiteral(const Expr *E) {
   // Unfortunately there's no common base Literal classes inherits from
   // (apart from Expr), therefore these exclusions.
@@ -785,7 +796,7 @@
  llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
- llvm::isa(E) || llvm::isa(E);
+ llvm::isa(E);
 }
 
 llvm::StringLiteral getNameForExpr(const Expr *E) {
@@ -810,6 +821,9 @@
 return llvm::None;
 
   HoverInfo HI;
+  // Print the type and the size for string literals
+  if (const StringLiteral *SL = dyn_cast(E))
+return getStringLiteralContents(SL, PP);
   // For `this` expr we currently generate hover with pointee type.
   if (const CXXThisExpr *CTE = dyn_cast(E))
 return getThisExprHoverContents(CTE, AST.getASTContext(), PP);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137650: [clangd] Implement hover for string literals

2022-11-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, lgtm!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137650

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


[clang] 135a927 - [Clang][LoongArch] Handle -march/-m{single,double,soft}-float/-mfpu options

2022-11-10 Thread via cfe-commits

Author: Weining Lu
Date: 2022-11-10T17:27:28+08:00
New Revision: 135a9272a4c99b7f960086d0bf9d7e7da4c0396d

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

LOG: [Clang][LoongArch] Handle -march/-m{single,double,soft}-float/-mfpu options

This patch adds options -march, -msingle-float, -mdouble-float,
-msoft-float and -mfpu for LoongArch.

Clang options `msingle_float` and `mdouble_float` are moved from
`m_mips_Features_Group` to `m_Group` because now more than targets use
them.

Reference:
https://github.com/loongson/LoongArch-Documentation/blob/main/docs/LoongArch-toolchain-conventions-EN.adoc

TODO: add -mtune.

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

Added: 
clang/test/Driver/loongarch-march-error.c
clang/test/Driver/loongarch-march.c
clang/test/Driver/loongarch-mdouble-float.c
clang/test/Driver/loongarch-mfpu-error.c
clang/test/Driver/loongarch-mfpu.c
clang/test/Driver/loongarch-msingle-float.c
clang/test/Driver/loongarch-msoft-float.c
llvm/include/llvm/Support/LoongArchTargetParser.def
llvm/include/llvm/Support/LoongArchTargetParser.h
llvm/lib/Support/LoongArchTargetParser.cpp

Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
clang/lib/Driver/ToolChains/Arch/LoongArch.h
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Linux.cpp
clang/test/Driver/loongarch-default-features.c
llvm/lib/Support/CMakeLists.txt

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 12c246b32cfd4..1b24d9c70a0b6 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -691,4 +691,7 @@ def warn_drv_sarif_format_unstable : Warning<
 
 def err_drv_riscv_unsupported_with_linker_relaxation : Error<
   "%0 is unsupported with RISC-V linker relaxation (-mrelax)">;
+
+def err_drv_loongarch_invalid_mfpu_EQ : Error<
+  "invalid argument '%0' to -mfpu=; must be one of: 64, 32, 0, none">;
 }

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c096c58440045..debe038196c06 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3910,8 +3910,8 @@ def mdsp : Flag<["-"], "mdsp">, 
Group;
 def mno_dsp : Flag<["-"], "mno-dsp">, Group;
 def mdspr2 : Flag<["-"], "mdspr2">, Group;
 def mno_dspr2 : Flag<["-"], "mno-dspr2">, Group;
-def msingle_float : Flag<["-"], "msingle-float">, Group;
-def mdouble_float : Flag<["-"], "mdouble-float">, Group;
+def msingle_float : Flag<["-"], "msingle-float">, Group;
+def mdouble_float : Flag<["-"], "mdouble-float">, Group;
 def mmadd4 : Flag<["-"], "mmadd4">, Group,
   HelpText<"Enable the generation of 4-operand madd.s, madd.d and related 
instructions.">;
 def mno_madd4 : Flag<["-"], "mno-madd4">, Group,

diff  --git a/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp 
b/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
index d364a2e8f7a8e..576677a5f38e1 100644
--- a/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
@@ -7,33 +7,109 @@
 
//===--===//
 
 #include "LoongArch.h"
+#include "clang/Basic/DiagnosticDriver.h"
+#include "clang/Driver/Driver.h"
+#include "clang/Driver/DriverDiagnostic.h"
+#include "clang/Driver/Options.h"
+#include "llvm/Support/LoongArchTargetParser.h"
 
+using namespace clang::driver;
 using namespace clang::driver::tools;
 using namespace clang;
 using namespace llvm::opt;
 
-StringRef loongarch::getLoongArchABI(const ArgList &Args,
+StringRef loongarch::getLoongArchABI(const Driver &D, const ArgList &Args,
  const llvm::Triple &Triple) {
   assert((Triple.getArch() == llvm::Triple::loongarch32 ||
   Triple.getArch() == llvm::Triple::loongarch64) &&
  "Unexpected triple");
+  bool IsLA32 = Triple.getArch() == llvm::Triple::loongarch32;
+
+  // Check -m*-float firstly since they have highest priority.
+  if (const Arg *A = Args.getLastArg(options::OPT_mdouble_float,
+ options::OPT_msingle_float,
+ options::OPT_msoft_float)) {
+if (A->getOption().matches(options::OPT_mdouble_float))
+  return IsLA32 ? "ilp32d" : "lp64d";
+if (A->getOption().matches(options::OPT_msingle_float))
+  return IsLA32 ? "ilp32f" : "lp64f";
+if (A->getOption().matches(options::OPT_msoft_float))
+  return IsLA32 ? "ilp32s" : "lp64s";
+  }
 
   // If `-mabi=` is specified, use it.
   if (const Arg *A 

[clang] 60e5cfe - [Clang][LoongArch] Define more LoongArch specific built-in macros

2022-11-10 Thread via cfe-commits

Author: Weining Lu
Date: 2022-11-10T17:27:29+08:00
New Revision: 60e5cfe2a4eba3bf0a642aeeb53a3f37dfed5fdb

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

LOG: [Clang][LoongArch] Define more LoongArch specific built-in macros

Define below macros according to LoongArch toolchain conventions [1].

* `__loongarch_grlen`
* `__loongarch_frlen`
* `__loongarch_lp64`
* `__loongarch_hard_float`
* `__loongarch_soft_float`
* `__loongarch_single_float`
* `__loongarch_double_float`

Note:
1. `__loongarch__` has been defined in earlier patch.
2. `__loongarch_arch` is not defined because I don't know how `TargetInfo` can 
get the arch name specified by `-march`.
3. `__loongarch_tune` will be defined in future.

[1]: 
https://loongson.github.io/LoongArch-Documentation/LoongArch-toolchain-conventions-EN.html

Depends on D136146

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

Added: 


Modified: 
clang/lib/Basic/Targets/LoongArch.cpp
clang/lib/Basic/Targets/LoongArch.h
clang/test/Preprocessor/init-loongarch.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/LoongArch.cpp 
b/clang/lib/Basic/Targets/LoongArch.cpp
index 12d53a9aff43b..ca7f6e519bd5a 100644
--- a/clang/lib/Basic/Targets/LoongArch.cpp
+++ b/clang/lib/Basic/Targets/LoongArch.cpp
@@ -131,10 +131,50 @@ LoongArchTargetInfo::convertConstraint(const char 
*&Constraint) const {
 void LoongArchTargetInfo::getTargetDefines(const LangOptions &Opts,
MacroBuilder &Builder) const {
   Builder.defineMacro("__loongarch__");
-  // TODO: Define more macros.
+  unsigned GRLen = getRegisterWidth();
+  Builder.defineMacro("__loongarch_grlen", Twine(GRLen));
+  if (GRLen == 64)
+Builder.defineMacro("__loongarch64");
+
+  if (HasFeatureD)
+Builder.defineMacro("__loongarch_frlen", "64");
+  else if (HasFeatureF)
+Builder.defineMacro("__loongarch_frlen", "32");
+  else
+Builder.defineMacro("__loongarch_frlen", "0");
+
+  // TODO: define __loongarch_arch and __loongarch_tune.
+
+  StringRef ABI = getABI();
+  if (ABI == "lp64d" || ABI == "lp64f" || ABI == "lp64s")
+Builder.defineMacro("__loongarch_lp64");
+
+  if (ABI == "lp64d" || ABI == "ilp32d") {
+Builder.defineMacro("__loongarch_hard_float");
+Builder.defineMacro("__loongarch_double_float");
+  } else if (ABI == "lp64f" || ABI == "ilp32f") {
+Builder.defineMacro("__loongarch_hard_float");
+Builder.defineMacro("__loongarch_single_float");
+  } else if (ABI == "lp64s" || ABI == "ilp32s") {
+Builder.defineMacro("__loongarch_soft_float");
+  }
 }
 
 ArrayRef LoongArchTargetInfo::getTargetBuiltins() const {
   // TODO: To be implemented in future.
   return {};
 }
+
+bool LoongArchTargetInfo::handleTargetFeatures(
+std::vector &Features, DiagnosticsEngine &Diags) {
+  for (const auto &Feature : Features) {
+if (Feature == "+d" || Feature == "+f") {
+  // "d" implies "f".
+  HasFeatureF = true;
+  if (Feature == "+d") {
+HasFeatureD = true;
+  }
+}
+  }
+  return true;
+}

diff  --git a/clang/lib/Basic/Targets/LoongArch.h 
b/clang/lib/Basic/Targets/LoongArch.h
index 09d3290362f65..69bcec18659d5 100644
--- a/clang/lib/Basic/Targets/LoongArch.h
+++ b/clang/lib/Basic/Targets/LoongArch.h
@@ -24,10 +24,14 @@ namespace targets {
 class LLVM_LIBRARY_VISIBILITY LoongArchTargetInfo : public TargetInfo {
 protected:
   std::string ABI;
+  bool HasFeatureD;
+  bool HasFeatureF;
 
 public:
   LoongArchTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
   : TargetInfo(Triple) {
+HasFeatureD = false;
+HasFeatureF = false;
 LongDoubleWidth = 128;
 LongDoubleAlign = 128;
 LongDoubleFormat = &llvm::APFloat::IEEEquad();
@@ -58,6 +62,9 @@ class LLVM_LIBRARY_VISIBILITY LoongArchTargetInfo : public 
TargetInfo {
   std::string convertConstraint(const char *&Constraint) const override;
 
   bool hasBitIntType() const override { return true; }
+
+  bool handleTargetFeatures(std::vector &Features,
+DiagnosticsEngine &Diags) override;
 };
 
 class LLVM_LIBRARY_VISIBILITY LoongArch32TargetInfo

diff  --git a/clang/test/Preprocessor/init-loongarch.c 
b/clang/test/Preprocessor/init-loongarch.c
index c26cc4f741582..b7b84d42d4ec7 100644
--- a/clang/test/Preprocessor/init-loongarch.c
+++ b/clang/test/Preprocessor/init-loongarch.c
@@ -322,6 +322,7 @@
 // LA32-LINUX: #define __gnu_linux__ 1
 // LA32-LINUX: #define __linux 1
 // LA32-LINUX: #define __linux__ 1
+// LA32-NOT: #define __loongarch64 1
 // LA32: #define __loongarch__ 1
 // LA32-LINUX: #define __unix 1
 // LA32-LINUX: #define __unix__ 1
@@ -634,8 +635,149 @@
 // LA64-LINUX: #define __gnu_linux__ 1
 // LA64-LINUX: #define __linux 1
 // LA64-LINUX: #define __linux__ 1
+// LA64: #de

[clang] 85f08c4 - [Clang][LoongArch] Implement __builtin_loongarch_dbar builtin

2022-11-10 Thread via cfe-commits

Author: gonglingqin
Date: 2022-11-10T17:27:44+08:00
New Revision: 85f08c4197aea68b2444e6874524b5f8b4067cfd

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

LOG: [Clang][LoongArch] Implement __builtin_loongarch_dbar builtin

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

Added: 
clang/include/clang/Basic/BuiltinsLoongArch.def
clang/lib/Headers/larchintrin.h
clang/test/CodeGen/LoongArch/intrinsic.c
llvm/test/CodeGen/LoongArch/intrinsic-error.ll
llvm/test/CodeGen/LoongArch/intrinsic.ll

Modified: 
clang/include/clang/Basic/TargetBuiltins.h
clang/include/clang/module.modulemap
clang/lib/Basic/Targets/LoongArch.cpp
clang/lib/Basic/Targets/LoongArch.h
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Headers/CMakeLists.txt
llvm/include/llvm/IR/IntrinsicsLoongArch.td
llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
llvm/lib/Target/LoongArch/LoongArchISelLowering.h
llvm/lib/Target/LoongArch/LoongArchInstrInfo.td

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsLoongArch.def 
b/clang/include/clang/Basic/BuiltinsLoongArch.def
new file mode 100644
index 0..109592ca4324d
--- /dev/null
+++ b/clang/include/clang/Basic/BuiltinsLoongArch.def
@@ -0,0 +1,23 @@
+//==- BuiltinsLoongArch.def - LoongArch Builtin function database -- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file defines the LoongArch-specific builtin function database.  Users 
of
+// this file must define the BUILTIN macro to make use of this information.
+//
+//===--===//
+
+#if defined(BUILTIN) && !defined(TARGET_BUILTIN)
+#   define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE) BUILTIN(ID, TYPE, ATTRS)
+#endif
+
+// TODO: Support more builtins.
+// TODO: Added feature constraints.
+TARGET_BUILTIN(__builtin_loongarch_dbar, "vIUi", "nc", "")
+
+#undef BUILTIN
+#undef TARGET_BUILTIN

diff  --git a/clang/include/clang/Basic/TargetBuiltins.h 
b/clang/include/clang/Basic/TargetBuiltins.h
index 48f343a206cfc..2f94e839768cd 100644
--- a/clang/include/clang/Basic/TargetBuiltins.h
+++ b/clang/include/clang/Basic/TargetBuiltins.h
@@ -151,6 +151,16 @@ namespace clang {
   };
   } // namespace RISCV
 
+  /// LoongArch builtins
+  namespace LoongArch {
+  enum {
+LastTIBuiltin = clang::Builtin::FirstTSBuiltin - 1,
+#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
+#include "clang/Basic/BuiltinsLoongArch.def"
+LastTSBuiltin
+  };
+  } // namespace LoongArch
+
   /// Flags to identify the types for overloaded Neon builtins.
   ///
   /// These must be kept in sync with the flags in 
utils/TableGen/NeonEmitter.h.

diff  --git a/clang/include/clang/module.modulemap 
b/clang/include/clang/module.modulemap
index ef055b599c0ae..227beafabcb08 100644
--- a/clang/include/clang/module.modulemap
+++ b/clang/include/clang/module.modulemap
@@ -42,6 +42,7 @@ module Clang_Basic {
   textual header "Basic/BuiltinsHexagon.def"
   textual header "Basic/BuiltinsHexagonDep.def"
   textual header "Basic/BuiltinsHexagonMapCustomDep.def"
+  textual header "Basic/BuiltinsLoongArch.def"
   textual header "Basic/BuiltinsMips.def"
   textual header "Basic/BuiltinsNEON.def"
   textual header "Basic/BuiltinsNVPTX.def"

diff  --git a/clang/lib/Basic/Targets/LoongArch.cpp 
b/clang/lib/Basic/Targets/LoongArch.cpp
index ca7f6e519bd5a..f79afe5eb7c49 100644
--- a/clang/lib/Basic/Targets/LoongArch.cpp
+++ b/clang/lib/Basic/Targets/LoongArch.cpp
@@ -160,9 +160,17 @@ void LoongArchTargetInfo::getTargetDefines(const 
LangOptions &Opts,
   }
 }
 
+const Builtin::Info LoongArchTargetInfo::BuiltinInfo[] = {
+#define BUILTIN(ID, TYPE, ATTRS)   
\
+  {#ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr},
+#define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE)   
\
+  {#ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, FEATURE},
+#include "clang/Basic/BuiltinsLoongArch.def"
+};
+
 ArrayRef LoongArchTargetInfo::getTargetBuiltins() const {
-  // TODO: To be implemented in future.
-  return {};
+  return llvm::makeArrayRef(BuiltinInfo, clang::LoongArch::LastTSBuiltin -
+ Builtin::FirstTSBuiltin);
 }
 
 bool LoongArchTargetInfo::handleTargetFeatures(

diff  --git a/clang/lib/Basic/Targets/LoongArch.h 
b/clang/lib/Basic/Targets/LoongArch.h
index 69bcec18659d5..4128dfd8aa7de 100644
--- a/clang/lib/Basic/Targets/LoongArch.h
+++ b/clang/lib/B

[PATCH] D136146: [Clang][LoongArch] Handle -march/-m{single,double,soft}-float/-mfpu options

2022-11-10 Thread Gong LingQin 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 rG135a9272a4c9: [Clang][LoongArch] Handle 
-march/-m{single,double,soft}-float/-mfpu options (authored by SixWeining, 
committed by gonglingqin).

Changed prior to commit:
  https://reviews.llvm.org/D136146?vs=474414&id=474471#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136146

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
  clang/lib/Driver/ToolChains/Arch/LoongArch.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/Driver/loongarch-default-features.c
  clang/test/Driver/loongarch-march-error.c
  clang/test/Driver/loongarch-march.c
  clang/test/Driver/loongarch-mdouble-float.c
  clang/test/Driver/loongarch-mfpu-error.c
  clang/test/Driver/loongarch-mfpu.c
  clang/test/Driver/loongarch-msingle-float.c
  clang/test/Driver/loongarch-msoft-float.c
  llvm/include/llvm/Support/LoongArchTargetParser.def
  llvm/include/llvm/Support/LoongArchTargetParser.h
  llvm/lib/Support/CMakeLists.txt
  llvm/lib/Support/LoongArchTargetParser.cpp

Index: llvm/lib/Support/LoongArchTargetParser.cpp
===
--- /dev/null
+++ llvm/lib/Support/LoongArchTargetParser.cpp
@@ -0,0 +1,53 @@
+//==-- LoongArch64TargetParser - Parser for LoongArch64 features --*- C++ -*-=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements a target parser to recognise LoongArch hardware features
+// such as CPU/ARCH and extension names.
+//
+//===--===//
+
+#include "llvm/Support/LoongArchTargetParser.h"
+#include "llvm/ADT/StringSwitch.h"
+
+using namespace llvm;
+using namespace llvm::LoongArch;
+
+const FeatureInfo AllFeatures[] = {
+#define LOONGARCH_FEATURE(NAME, KIND) {NAME, KIND},
+#include "llvm/Support/LoongArchTargetParser.def"
+};
+
+const ArchInfo AllArchs[] = {
+#define LOONGARCH_ARCH(NAME, KIND, FEATURES)   \
+  {NAME, LoongArch::ArchKind::KIND, FEATURES},
+#include "llvm/Support/LoongArchTargetParser.def"
+};
+
+LoongArch::ArchKind LoongArch::parseArch(StringRef Arch) {
+  for (const auto A : AllArchs) {
+if (A.Name == Arch)
+  return A.Kind;
+  }
+
+  return LoongArch::ArchKind::AK_INVALID;
+}
+
+bool LoongArch::getArchFeatures(StringRef Arch,
+std::vector &Features) {
+  for (const auto A : AllArchs) {
+if (A.Name == Arch) {
+  for (const auto F : AllFeatures) {
+if ((A.Features & F.Kind) == F.Kind && F.Kind != FK_INVALID) {
+  Features.push_back(F.Name);
+}
+  }
+  return true;
+}
+  }
+  return false;
+}
Index: llvm/lib/Support/CMakeLists.txt
===
--- llvm/lib/Support/CMakeLists.txt
+++ llvm/lib/Support/CMakeLists.txt
@@ -187,6 +187,7 @@
   LineIterator.cpp
   Locale.cpp
   LockFileManager.cpp
+  LoongArchTargetParser.cpp
   LowLevelType.cpp
   ManagedStatic.cpp
   MathExtras.cpp
Index: llvm/include/llvm/Support/LoongArchTargetParser.h
===
--- /dev/null
+++ llvm/include/llvm/Support/LoongArchTargetParser.h
@@ -0,0 +1,74 @@
+//==-- LoongArch64TargetParser - Parser for LoongArch64 features --*- C++ -*-=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements a target parser to recognise LoongArch hardware features
+// such as CPU/ARCH and extension names.
+//
+//===--===//
+
+#ifndef LLVM_SUPPORT_LOONGARCHTARGETPARSER_H
+#define LLVM_SUPPORT_LOONGARCHTARGETPARSER_H
+
+#include "llvm/ADT/Triple.h"
+#include 
+
+namespace llvm {
+class StringRef;
+
+namespace LoongArch {
+
+enum FeatureKind : uint32_t {
+  FK_INVALID = 0,
+  FK_NONE = 1,
+
+  // 64-bit ISA is available.
+  FK_64BIT = 1 << 1,
+
+  // Single-precision floating-point instructions are available.
+  FK_FP32 = 1 << 2,
+
+  // Double-precision floating-point instructions are available.
+  FK_FP64 = 1 << 3,
+
+  // Loongson SIMD Extension is available.
+  FK_LSX = 1 << 4,
+
+  // Loongson Advanced SIMD Extension is available.
+  FK_LASX = 1 

[PATCH] D136906: [Clang][LoongArch] Implement __builtin_loongarch_dbar builtin

2022-11-10 Thread Gong LingQin 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 rG85f08c4197ae: [Clang][LoongArch] Implement 
__builtin_loongarch_dbar builtin (authored by gonglingqin).

Changed prior to commit:
  https://reviews.llvm.org/D136906?vs=473909&id=474473#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136906

Files:
  clang/include/clang/Basic/BuiltinsLoongArch.def
  clang/include/clang/Basic/TargetBuiltins.h
  clang/include/clang/module.modulemap
  clang/lib/Basic/Targets/LoongArch.cpp
  clang/lib/Basic/Targets/LoongArch.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Headers/larchintrin.h
  clang/test/CodeGen/LoongArch/intrinsic.c
  llvm/include/llvm/IR/IntrinsicsLoongArch.td
  llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
  llvm/lib/Target/LoongArch/LoongArchISelLowering.h
  llvm/lib/Target/LoongArch/LoongArchInstrInfo.td
  llvm/test/CodeGen/LoongArch/intrinsic-error.ll
  llvm/test/CodeGen/LoongArch/intrinsic.ll

Index: llvm/test/CodeGen/LoongArch/intrinsic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/LoongArch/intrinsic.ll
@@ -0,0 +1,15 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc --mtriple=loongarch32 < %s | FileCheck %s
+; RUN: llc --mtriple=loongarch64 < %s | FileCheck %s
+
+declare void @llvm.loongarch.dbar(i32)
+
+define void @foo() nounwind {
+; CHECK-LABEL: foo:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:dbar 0
+; CHECK-NEXT:ret
+entry:
+  call void @llvm.loongarch.dbar(i32 0)
+  ret void
+}
Index: llvm/test/CodeGen/LoongArch/intrinsic-error.ll
===
--- /dev/null
+++ llvm/test/CodeGen/LoongArch/intrinsic-error.ll
@@ -0,0 +1,18 @@
+; RUN: not llc --mtriple=loongarch32 --disable-verify < %s 2>&1 | FileCheck %s
+; RUN: not llc --mtriple=loongarch64 --disable-verify < %s 2>&1 | FileCheck %s
+
+define void @dbar_not_constant(i32 %x) nounwind {
+; CHECK: argument to '__builtin_loongarch_dbar' must be a constant integer
+entry:
+  call void @llvm.loongarch.dbar(i32 %x)
+  ret void
+}
+
+define void @dbar_imm_out_of_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_dbar' out of range
+entry:
+  call void @llvm.loongarch.dbar(i32 32769)
+  ret void
+}
+
+declare void @llvm.loongarch.dbar(i32)
Index: llvm/lib/Target/LoongArch/LoongArchInstrInfo.td
===
--- llvm/lib/Target/LoongArch/LoongArchInstrInfo.td
+++ llvm/lib/Target/LoongArch/LoongArchInstrInfo.td
@@ -35,6 +35,8 @@
   SDTCisInt<0>, SDTCisSameAs<0, 1>, SDTCisInt<2>, SDTCisSameAs<2, 3>
 ]>;
 
+def SDT_LoongArchDBAR : SDTypeProfile<0, 1, [SDTCisVT<0, GRLenVT>]>;
+
 // TODO: Add LoongArch specific DAG Nodes
 // Target-independent nodes, but with target-specific formats.
 def callseq_start : SDNode<"ISD::CALLSEQ_START", SDT_CallSeqStart,
@@ -63,6 +65,8 @@
 def loongarch_bitrev_w : SDNode<"LoongArchISD::BITREV_W", SDTUnaryOp>;
 def loongarch_clzw : SDNode<"LoongArchISD::CLZ_W", SDTIntBitCountUnaryOp>;
 def loongarch_ctzw : SDNode<"LoongArchISD::CTZ_W", SDTIntBitCountUnaryOp>;
+def loongarch_dbar : SDNode<"LoongArchISD::DBAR", SDT_LoongArchDBAR,
+ [SDNPHasChain, SDNPSideEffect]>;
 
 //===--===//
 // Operand and SDNode transformation definitions.
@@ -130,7 +134,8 @@
   let ParserMatchClass = UImmAsmOperand<14>;
 }
 
-def uimm15 : Operand {
+def uimm15 : Operand,
+ ImmLeaf (Imm);}]> {
   let ParserMatchClass = UImmAsmOperand<15>;
 }
 
@@ -1304,6 +1309,16 @@
   (PseudoAtomicLoadXor32 GPR:$incr, GPR:$addr)>;
 } // Predicates = [IsLA32]
 
+/// Intrinsics
+
+let Predicates = [IsLA32] in {
+def : Pat<(int_loongarch_dbar uimm15:$imm15), (DBAR uimm15:$imm15)>;
+} // Predicates = [IsLA32]
+
+let Predicates = [IsLA64] in {
+def : Pat<(loongarch_dbar uimm15:$imm15), (DBAR uimm15:$imm15)>;
+} // Predicates = [IsLA64]
+
 /// Other pseudo-instructions
 
 // Pessimistically assume the stack pointer will be clobbered
Index: llvm/lib/Target/LoongArch/LoongArchISelLowering.h
===
--- llvm/lib/Target/LoongArch/LoongArchISelLowering.h
+++ llvm/lib/Target/LoongArch/LoongArchISelLowering.h
@@ -56,6 +56,9 @@
   REVB_2W,
   BITREV_4B,
   BITREV_W,
+
+  // Intrinsic operations
+  DBAR,
 };
 } // end namespace LoongArchISD
 
@@ -174,6 +177,7 @@
   SDValue lowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) const;
   SDValue lowerVASTART(SDValue Op, SelectionDAG &DAG) const;
   SDValue lowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const;
+  SDValue lowerINTRINSIC_VOID(SDValue Op, SelectionDAG &DAG) const

[PATCH] D136413: [Clang][LoongArch] Define more LoongArch specific built-in macros

2022-11-10 Thread Gong LingQin via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG60e5cfe2a4eb: [Clang][LoongArch] Define more LoongArch 
specific built-in macros (authored by SixWeining, committed by gonglingqin).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136413

Files:
  clang/lib/Basic/Targets/LoongArch.cpp
  clang/lib/Basic/Targets/LoongArch.h
  clang/test/Preprocessor/init-loongarch.c

Index: clang/test/Preprocessor/init-loongarch.c
===
--- clang/test/Preprocessor/init-loongarch.c
+++ clang/test/Preprocessor/init-loongarch.c
@@ -322,6 +322,7 @@
 // LA32-LINUX: #define __gnu_linux__ 1
 // LA32-LINUX: #define __linux 1
 // LA32-LINUX: #define __linux__ 1
+// LA32-NOT: #define __loongarch64 1
 // LA32: #define __loongarch__ 1
 // LA32-LINUX: #define __unix 1
 // LA32-LINUX: #define __unix__ 1
@@ -634,8 +635,149 @@
 // LA64-LINUX: #define __gnu_linux__ 1
 // LA64-LINUX: #define __linux 1
 // LA64-LINUX: #define __linux__ 1
+// LA64: #define __loongarch64 1
 // LA64: #define __loongarch__ 1
 // LA64-LINUX: #define __unix 1
 // LA64-LINUX: #define __unix__ 1
 // LA64-LINUX: #define linux 1
 // LA64-LINUX: #define unix 1
+
+
+/// Check various macros prefixed with "__loongarch_" in different cases.
+/// "__loongarch__"" is not listed here as it has been checked above.
+
+// RUN: %clang --target=loongarch32 -mfpu=64 -mabi=ilp32d -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU64-ILP32D %s
+// RUN: %clang --target=loongarch32 -mdouble-float -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU64-ILP32D %s
+// LA32-FPU64-ILP32D: __loongarch_double_float 1
+// LA32-FPU64-ILP32D-NEXT: __loongarch_frlen 64
+// LA32-FPU64-ILP32D-NEXT: __loongarch_grlen 32
+// LA32-FPU64-ILP32D-NEXT: __loongarch_hard_float 1
+// LA32-FPU64-ILP32D-NOT: __loongarch_lp64
+// LA32-FPU64-ILP32D-NOT: __loongarch_single_float
+// LA32-FPU64-ILP32D-NOT: __loongarch_soft_float
+
+// RUN: %clang --target=loongarch32 -mfpu=64 -mabi=ilp32f -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU64-ILP32F %s
+// LA32-FPU64-ILP32F-NOT: __loongarch_double_float
+// LA32-FPU64-ILP32F: __loongarch_frlen 64
+// LA32-FPU64-ILP32F-NEXT: __loongarch_grlen 32
+// LA32-FPU64-ILP32F-NEXT: __loongarch_hard_float 1
+// LA32-FPU64-ILP32F-NOT: __loongarch_lp64
+// LA32-FPU64-ILP32F-NEXT: __loongarch_single_float 1
+// LA32-FPU64-ILP32F-NOT: __loongarch_soft_float
+
+// RUN: %clang --target=loongarch32 -mfpu=64 -mabi=ilp32s -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU64-ILP32S %s
+// LA32-FPU64-ILP32S-NOT: __loongarch_double_float
+// LA32-FPU64-ILP32S: __loongarch_frlen 64
+// LA32-FPU64-ILP32S-NEXT: __loongarch_grlen 32
+// LA32-FPU64-ILP32S-NOT: __loongarch_hard_float
+// LA32-FPU64-ILP32S-NOT: __loongarch_lp64
+// LA32-FPU64-ILP32S-NOT: __loongarch_single_float
+// LA32-FPU64-ILP32S-NEXT: __loongarch_soft_float 1
+
+// RUN: %clang --target=loongarch32 -mfpu=32 -mabi=ilp32f -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU32-ILP32F %s
+// RUN: %clang --target=loongarch32 -msingle-float -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU32-ILP32F %s
+// LA32-FPU32-ILP32F-NOT: __loongarch_double_float
+// LA32-FPU32-ILP32F: __loongarch_frlen 32
+// LA32-FPU32-ILP32F-NEXT: __loongarch_grlen 32
+// LA32-FPU32-ILP32F-NEXT: __loongarch_hard_float 1
+// LA32-FPU32-ILP32F-NOT: __loongarch_lp64
+// LA32-FPU32-ILP32F-NEXT: __loongarch_single_float 1
+// LA32-FPU32-ILP32F-NOT: __loongarch_soft_float
+
+// RUN: %clang --target=loongarch32 -mfpu=32 -mabi=ilp32s -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU32-ILP32S %s
+// LA32-FPU32-ILP32S-NOT: __loongarch_double_float
+// LA32-FPU32-ILP32S: __loongarch_frlen 32
+// LA32-FPU32-ILP32S-NEXT: __loongarch_grlen 32
+// LA32-FPU32-ILP32S-NOT: __loongarch_hard_float
+// LA32-FPU32-ILP32S-NOT: __loongarch_lp64
+// LA32-FPU32-ILP32S-NOT: __loongarch_single_float
+// LA32-FPU32-ILP32S-NEXT: __loongarch_soft_float 1
+
+// RUN: %clang --target=loongarch32 -mfpu=0 -mabi=ilp32s -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU0-ILP32S %s
+// RUN: %clang --target=loongarch32 -mfpu=none -mabi=ilp32s -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU0-ILP32S %s
+// RUN: %clang --target=loongarch32 -msoft-float -x c -E -dM %s -o - \
+// RUN:   | grep __loongarch_ | FileCheck --check-prefix=LA32-FPU0-ILP32S %s
+// LA32-FPU0-ILP32S-NOT: __loongarch_double_float
+// LA32-FPU0-ILP32S: __loongarch_frlen 0
+// LA32-FPU0-ILP32S-NEXT: __loongarch_grlen 32
+// LA32-FPU0-ILP32S-NOT: __loongarch_hard_float
+// LA32-FPU0-ILP32S-NOT: __loongarch_lp

[PATCH] D137770: [docs] Introduce clangd part in StandardCPlusPlusModules

2022-11-10 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: sammccall, nridge.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
ChuanqiXu requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Introduce clangd part in to the document to tell end users about the status 
quo. It is pretty important since nowadays it is painful to write codes without 
the help form the code intelligence.

And my feeling in the recent days is that: the current status is obviously very 
far from good but it is not useless completely.  As long as we can get a 
`compile_commands.json`, the clangd can start to work in some degree. And it 
should be easy for the build systems to generate the `compile_commands.json`. 
So I think it is meaningful to document the status quo.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137770

Files:
  clang/docs/StandardCPlusPlusModules.rst


Index: clang/docs/StandardCPlusPlusModules.rst
===
--- clang/docs/StandardCPlusPlusModules.rst
+++ clang/docs/StandardCPlusPlusModules.rst
@@ -821,6 +821,63 @@
 there are some differences between header units and Clang modules and that 
ignoring those
 differences now would likely become a problem in the future.
 
+Interoperability with tool chains
+=
+
+The modules change the traditional header based C++ project structures 
drastically.
+So the interoperability of many tool chains is broken. Here we track the 
status quo
+and the interoperability with clang for different tools.
+
+clangd
+==
+
+The clangd is a language server that can work with many editors via a plugin.
+The clangd can show diagnostics of errors and warnings in-place, suggest fixes,
+show extra hints about code problems and suggest code completion.
+
+Since clangd will invoke clang to parse the files according to flags from the
+`compilation database 
`_,
+so as long as the clang can compile the files by these flags in the 
compilation database,
+the clangd should be able to handle the files in some level.
+
+So given clang can compile some modules codes now,
+the clangd can work for modules in some degree. The following is an simple 
example to show
+how to use clangd for modules:
+
+.. code-block:: c++
+
+  // A.cppm
+  export module A;
+  export void printA() {}
+
+  // Use.cpp
+  import A;
+  void foo() {
+  }
+
+  // compile_commands.json
+  [
+{
+  "directory": "DIR",
+  "command": "clang++  -fprebuilt-module-path=DIR -std=c++20 -o 
DIR/main.cpp.o -c DIR/Use.cpp",
+  "file": "DIR/Use.cpp"
+}
+  ]
+
+Now the important part is that we need to compile module A to BMI first:
+
+.. code-block:: console
+  
+  clang++  -fprebuilt-module-path=DIR -std=c++20 -o DIR/main.cpp.o -c 
DIR/Use.cpp
+
+Then in ``Use.cpp``, when we type `pr`, we can find the suggestion to `printA`.
+And if we require to find the definition for `printA`, we can go to the 
definition corretly.
+
+However, since modules bring completely new relationship to the C++ projects 
and
+clangd doesn't do special corresponding changes. It is natural that the 
interactions
+are not friendly, there are a lot of defects and even crashes. We can track 
the newest status
+in https://github.com/clangd/clangd/issues/1293.
+
 Possible Questions
 ==
 


Index: clang/docs/StandardCPlusPlusModules.rst
===
--- clang/docs/StandardCPlusPlusModules.rst
+++ clang/docs/StandardCPlusPlusModules.rst
@@ -821,6 +821,63 @@
 there are some differences between header units and Clang modules and that ignoring those
 differences now would likely become a problem in the future.
 
+Interoperability with tool chains
+=
+
+The modules change the traditional header based C++ project structures drastically.
+So the interoperability of many tool chains is broken. Here we track the status quo
+and the interoperability with clang for different tools.
+
+clangd
+==
+
+The clangd is a language server that can work with many editors via a plugin.
+The clangd can show diagnostics of errors and warnings in-place, suggest fixes,
+show extra hints about code problems and suggest code completion.
+
+Since clangd will invoke clang to parse the files according to flags from the
+`compilation database `_,
+so as long as the clang can compile the files by these flags in the compilation database,
+the clangd should be able to handle the files in some level.
+
+So given clang can compile some modules codes now,
+the clangd can work for modules in some degree. The following is an simple example to show
+how to use clangd for modules:
+
+.. code-block:: c++
+
+  // A.cppm
+  export module A;
+  export void printA() {

[PATCH] D137154: Adding nvvm_reflect clang builtin

2022-11-10 Thread Alexey Bader via Phabricator via cfe-commits
bader added a comment.

Is binary size a concern here? NVIDIA, AMD and Intel GPUs are already have ~ 20 
different architectures each, so I want my app/library to run on any GPU from 
these vendors (which is quite reasonable expectation), I'll need to 
have/distribute ~ 60 different binaries. libdevice, libm, libc are quite small, 
but other apps (e.g. ML frameworks) might be quite large, so that distributed 
binary size is important to consider.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137154

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


[PATCH] D137693: [NFC] [C++20] [Modules] [clangd] Add test for code completion for C++20 Named Modules

2022-11-10 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

The failed tests in windows says:

> Failed to find compilation database for 
> \\C:\ws\w9\llvm-project\premerge-checks\build\tools\clang\tools\extra\clangd\test\Output\completion-modules.test.tmp\Use.cpp


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

https://reviews.llvm.org/D137693

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


[PATCH] D137755: [clang-format] Treats &/&& as reference when followed by ',' or ')'.

2022-11-10 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Its always good if you have a github issue to add that to the summary (just to 
tie stuff together), if you don't feel free to go over there an log a bug.




Comment at: clang/lib/Format/TokenAnnotator.cpp:2355
+NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_noexcept, 
tok::comma,
+   tok::r_paren) ||
 NextToken->canBePointerOrReferenceQualifier() ||

nowadays we add a TokenAnnotator test (they are very easy to write), this lets 
us ensure its getting annotated correctly. (which is really the bug here), 

but your tests below are great too!.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137755

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


[PATCH] D137755: [clang-format] Treats &/&& as reference when followed by ',' or ')'.

2022-11-10 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

On first inspection this looks ok, but lets wait for the others chime in, 
please add the annotator test too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137755

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


[PATCH] D137770: [docs] Introduce clangd part in StandardCPlusPlusModules

2022-11-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

The status quo for modules on clangd is all flavors are completely unsupported: 
https://github.com/clangd/clangd/issues/1293.
I don't think we should encourage people to set up workflows that are known not 
to work properly and will probably break in future.

It's true that some parts work by coincidence (if you embed clang, you get all 
the features by default), but it's broken both in principle and in practice.

- most users don't have a version-locked clang and clangd, so relying on 
loading clang-produced BMI files from disk is the wrong design
- modules that get loaded somewhere inside clang never get indexed, which 
affects most features (e.g. code completion))
- various clangd features (include insertion, code completion ranking, unused 
include detection, many others) rely on the assumption that we have recorded 
the complete `#include` tree.
- in practice we know it's easy to get this to crash, and that users who follow 
instructions and get crashes expect support

To get to a better state someone needs to design and build support for modules 
in clangd. This is a major project. (Based on the discussions we've had so far, 
I *don't* expect the solution to look like "adopt clang's support" but rather 
require significant new infrastructure).

It's also one that doesn't currently have an owner. Unfortuntately (which has 
funded much of clangd's development) it's not likely to be a priority for 
$EMPLOYER unless/until we're using C++20 modules ourselves. (And we have less 
time to work on clangd at all, these days). We're open to someone else driving 
it (I know some folks from Meta were looking at this) as long as we head 
towards a design that's likely to be widely useful (e.g. no version lock, plan 
to work with common build systems).

This situation is not at all obvious to users, and I'm impressed you managed to 
figure out the bits that work! I think we should clarify the situation by 
making clangd emit an error when modules are enabled (we can disable this with 
a flag like `--experimental-modules` for people that want to work on modules 
support/test it once someone works on it).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137770

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


[PATCH] D134791: [clang] Unify Sema and CodeGen implementation of isFlexibleArrayMemberExpr

2022-11-10 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I wonder if we could come up with an overload or something for cases when we 
only have a `FieldDecl`.
For example, in the Clang Static Analyzer, we have something similar at 
MemRegion.cpp#L784-L811 
,
 and it would be great if we could also make use of this harmonized 
flexible-array-members detection.

Actually, @serge-sans-paille inserted a FIXME about this, and I believe it's 
correct.

  const AnalyzerOptions &Opts = SVB.getAnalyzerOptions();
  // FIXME: this option is probably redundant with -fstrict-flex-arrays=1.
  if (Opts.ShouldConsiderSingleElementArraysAsFlexibleArrayMembers && 
Size.isOne())
return true;

Unfortunately, in this context we don't have an `Expr`; we only have a 
`FieldDecl`, so I'm looking for some way to plug this 
`isFlexibleArrayMemberLike()` into this.
I'm thinking of like introducing another overload for it accepting `FieldDecl` 
instead of `Expr` along with the current one.

@serge-sans-paille what do you think about this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134791

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


[PATCH] D137650: [clangd] Implement hover for string literals

2022-11-10 Thread v1nh1shungry via Phabricator via cfe-commits
v1nh1shungry added a comment.

@kadircet Could you please help me commit it? Thanks a lot!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137650

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


[PATCH] D137319: [include-cleaner] Add export IWYU pragma support.

2022-11-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:69
+  // main-file #include with export pragma should never be removed.
+  if (Top.Exporter == SM.getMainFileID())
+Out->ShouldKeep.insert(

hokein wrote:
> kadircet wrote:
> > well, i've just noticed we're not actually doing anything specific to the 
> > include here (or for the `keep` equivalent) as we're just storing the line 
> > number we've seen the comment on.
> > so what about moving this logic (and the pragma keep one) into the 
> > `HandleComment` callback instead?
> right, but with the new implementation, we use the # line number to make sure 
> the #include is within the export range, this logic needs to be here, 
> otherwise the semantic of `ShouldKeep` will change to `track all lines that 
> have IWYU pragmas, even for lines without #include directive`.
> `track all lines that have IWYU pragmas, even for lines without #include 
> directive`

i am not sure what's so bad about this. i think it'll make the code less 
complicated, as inclusion directive doesn't need to care about mutating 
`ShouldKeep` anymore, and public api for the class doesn't actually care about 
include-directives for `shouldKeep` operation, it just operates on lines. so 
saying "yes" to preserving lines that have `// IWYU keep/export` but no 
associated inclusion directive, doesn't seem so confusing (i agree, it'd be 
better not to have, but i don't think is an important enough use case, i.e. 
people trying to make decisions for lines that don't have includes via 
include-cleaner is unlikely and possibly wrong enough that we shouldn't care).

up to you though, especially if you extract the export handling into a separate 
method, this shouldn't be too much of an issue.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:144
   int LastPragmaKeepInMainFileLine = -1;
+  struct State {
+// The file where we saw the export pragma.

hokein wrote:
> kadircet wrote:
> > maybe call this `ExportPragma` instead of `State`?
> ExportPragma seems more confusing than State, it doesn't express that we're 
> tracking the state of the export pragma. 
i think `State` doesn't emphasize the fact that it's about `export`s 
specifically, hence i was trying to suggest including `Export` in the name 
somehow.

moreover, i don't think we're tracking the state of the export pragma, we're 
literally recording occurrence of an export pragma, the state is rather tracked 
via `ExportStack` itself. hence i'd still suggest renaming this to 
`ExportPragma` and if you want change the `ExportStack` to `ExportState`, but i 
think `ExportStack` is fine as is.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:67
+
+if (!ExportStack.empty() && ExportStack.back().SeenAtFile == HashFID) {
+  auto Top = ExportStack.back();

do you mind extracting this into a method and re-flow in a early-exit friendly 
way, it's getting a little bit hard to follow. e.g:
```
void checkForExport(FileID IncludingFile, FileEntryRef IncludedFile) {
  if (ExportStack.etmpy()) return;
  auto &Top = ExportStack.top();
  if (Top.SeenAtFile != IncludingFile) return;
  ...
}
```



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:68
+if (!ExportStack.empty() && ExportStack.back().SeenAtFile == HashFID) {
+  auto Top = ExportStack.back();
+  if ((Top.Block && HashLine > Top.SeenAtLine) ||

nit: `auto &Top = ...` to prevent the copy



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:71
+  Top.SeenAtLine ==
+  HashLine) { // make sure the #include is within the export range.
+Out->IWYUExportBy[File->getUniqueID()].push_back(

can you move the comment to be above the `if` statement instead? nesting seems 
weird here. we can say `make sure current include is covered by the export 
pragma`.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:72
+  HashLine) { // make sure the #include is within the export range.
+Out->IWYUExportBy[File->getUniqueID()].push_back(
+save(SM.getFileEntryForID(Top.SeenAtFile)->tryGetRealPathName()));

unfortunately `File` is `Optional`.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:73
+Out->IWYUExportBy[File->getUniqueID()].push_back(
+save(SM.getFileEntryForID(Top.SeenAtFile)->tryGetRealPathName()));
+// main-file #include with export pragma should never be removed.

nit: i'd actually make `FullPath` part of `State` and use it directly from 
there, rather than possibly calling `tryGetRealPathName` and `save` multiple 
times here.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:105
+

[PATCH] D137693: [NFC] [C++20] [Modules] [clangd] Add test for code completion for C++20 Named Modules

2022-11-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

I think at this point we specifically don't want to commit to preserving 
particular modules behavior, this is more or less what the unsupported state 
means (https://github.com/clangd/clangd/issues/1293).

In particular the pattern where modules are built externally by clang, clang 
must be version-locked to clangd, and module content is never indexed, doesn't 
seem to be a good foundation for most users, so having the freedom to tear it 
down later seems better than encouraging people to rely on it.




Comment at: clang-tools-extra/clangd/test/CMakeLists.txt:2
 set(CLANGD_TEST_DEPS
+  clang
   clangd

A dependency on clang here probably isn't acceptable:
 - it's a *large* increase in what needs to be built for `check-clangd`, which 
we try quite hard to keep small
 - the conceptual reason is that clangd is consuming modules built by 
(version-locked) clang, for various reasons  this shouldn't be required (not 
least: users likely don't have a version-locked clang installed)



Comment at: clang-tools-extra/clangd/test/completion-modules.test:1
+# Tests that the importee can find the exported entities.
+# RUN: rm -fr %t

We generally find lit tests too hard to maintain for this sort of thing.

In particular:
- lots of noise added to each test
- failures are too hard to parse
- too much redundant setup work duplicated in each testcase
- substituting filenames tends to run into escaping issues with windows and 
backslashes, etc
- test scope ends up being too large
- use of real filesystem doesn't verify the implementation is VFS-clean

It's usually OK to have a single smoke test if needed, but generally these are 
written as unittests.


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

https://reviews.llvm.org/D137693

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


[PATCH] D137650: [clangd] Implement hover for string literals

2022-11-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

sure i am happy to land, @tom-anders do you have anything else to add ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137650

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


[PATCH] D137762: [clang-format] avoid breaking )( with BlockIndent

2022-11-10 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Definitely needs tests




Comment at: clang/lib/Format/ContinuationIndenter.cpp:720
   (!Previous.Previous || !Previous.Previous->isOneOf(
- tok::kw_for, tok::kw_while, tok::kw_switch)) 
&&
+  tok::r_paren,  tok::kw_for, tok::kw_while, tok::kw_switch)) 
&&
   // Don't do this for simple (no expressions) one-argument function calls

this would likely have been added for a reason, did this not break any tests?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137762

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


[PATCH] D137650: [clangd] Implement hover for string literals

2022-11-10 Thread Tom Praschan via Phabricator via cfe-commits
tom-anders added a comment.

In D137650#3919089 , @kadircet wrote:

> sure i am happy to land, @tom-anders do you have anything else to add ?

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137650

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


[PATCH] D127762: [Clang][AArch64] Add ACLE attributes for SME.

2022-11-10 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added a comment.

Gentle ping :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127762

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


[clang-tools-extra] 92297bd - [clangd] Implement hover for string literals

2022-11-10 Thread Kadir Cetinkaya via cfe-commits

Author: v1nh1shungry
Date: 2022-11-10T12:16:05+01:00
New Revision: 92297bde5ce13825dd6609e4eb99688e6019

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

LOG: [clangd] Implement hover for string literals

Show string-literals' type and size in a hover card

Issue related: https://github.com/clangd/clangd/issues/1016

Reviewed By: kadircet

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

Added: 


Modified: 
clang-tools-extra/clangd/Hover.cpp
clang-tools-extra/clangd/unittests/HoverTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 555cefd7d07fe..d3dc3966eca31 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -777,6 +777,17 @@ HoverInfo getDeducedTypeHoverContents(QualType QT, const 
syntax::Token &Tok,
   return HI;
 }
 
+HoverInfo getStringLiteralContents(const StringLiteral *SL,
+   const PrintingPolicy &PP) {
+  HoverInfo HI;
+
+  HI.Name = "string-literal";
+  HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth();
+  HI.Type = SL->getType().getAsString(PP).c_str();
+
+  return HI;
+}
+
 bool isLiteral(const Expr *E) {
   // Unfortunately there's no common base Literal classes inherits from
   // (apart from Expr), therefore these exclusions.
@@ -785,7 +796,7 @@ bool isLiteral(const Expr *E) {
  llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
- llvm::isa(E) || llvm::isa(E);
+ llvm::isa(E);
 }
 
 llvm::StringLiteral getNameForExpr(const Expr *E) {
@@ -810,6 +821,9 @@ llvm::Optional getHoverContents(const Expr *E, 
ParsedAST &AST,
 return llvm::None;
 
   HoverInfo HI;
+  // Print the type and the size for string literals
+  if (const StringLiteral *SL = dyn_cast(E))
+return getStringLiteralContents(SL, PP);
   // For `this` expr we currently generate hover with pointee type.
   if (const CXXThisExpr *CTE = dyn_cast(E))
 return getThisExprHoverContents(CTE, AST.getASTContext(), PP);

diff  --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 9f64defaf898f..4b1dbdfa31f5a 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1300,7 +1300,6 @@ TEST(Hover, NoHover) {
   "auto x = ^42.0i;",
   "auto x = ^42;",
   "auto x = ^nullptr;",
-  "auto x = ^\"asdf\";",
   };
 
   for (const auto &Test : Tests) {
@@ -1326,6 +1325,12 @@ TEST(Hover, All) {
  HI.Type = "char";
  HI.Value = "65 (0x41)";
}},
+  {"auto s = ^[[\"Hello, world!\"]]; // string literal",
+   [](HoverInfo &HI) {
+ HI.Name = "string-literal";
+ HI.Size = 14;
+ HI.Type = "const char[14]";
+   }},
   {
   R"cpp(// Local variable
 int main() {



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


[PATCH] D137650: [clangd] Implement hover for string literals

2022-11-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG92297bde5ce1: [clangd] Implement hover for string literals 
(authored by v1nh1shungry, committed by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137650

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1300,7 +1300,6 @@
   "auto x = ^42.0i;",
   "auto x = ^42;",
   "auto x = ^nullptr;",
-  "auto x = ^\"asdf\";",
   };
 
   for (const auto &Test : Tests) {
@@ -1326,6 +1325,12 @@
  HI.Type = "char";
  HI.Value = "65 (0x41)";
}},
+  {"auto s = ^[[\"Hello, world!\"]]; // string literal",
+   [](HoverInfo &HI) {
+ HI.Name = "string-literal";
+ HI.Size = 14;
+ HI.Type = "const char[14]";
+   }},
   {
   R"cpp(// Local variable
 int main() {
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -777,6 +777,17 @@
   return HI;
 }
 
+HoverInfo getStringLiteralContents(const StringLiteral *SL,
+   const PrintingPolicy &PP) {
+  HoverInfo HI;
+
+  HI.Name = "string-literal";
+  HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth();
+  HI.Type = SL->getType().getAsString(PP).c_str();
+
+  return HI;
+}
+
 bool isLiteral(const Expr *E) {
   // Unfortunately there's no common base Literal classes inherits from
   // (apart from Expr), therefore these exclusions.
@@ -785,7 +796,7 @@
  llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
- llvm::isa(E) || llvm::isa(E);
+ llvm::isa(E);
 }
 
 llvm::StringLiteral getNameForExpr(const Expr *E) {
@@ -810,6 +821,9 @@
 return llvm::None;
 
   HoverInfo HI;
+  // Print the type and the size for string literals
+  if (const StringLiteral *SL = dyn_cast(E))
+return getStringLiteralContents(SL, PP);
   // For `this` expr we currently generate hover with pointee type.
   if (const CXXThisExpr *CTE = dyn_cast(E))
 return getThisExprHoverContents(CTE, AST.getASTContext(), PP);


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1300,7 +1300,6 @@
   "auto x = ^42.0i;",
   "auto x = ^42;",
   "auto x = ^nullptr;",
-  "auto x = ^\"asdf\";",
   };
 
   for (const auto &Test : Tests) {
@@ -1326,6 +1325,12 @@
  HI.Type = "char";
  HI.Value = "65 (0x41)";
}},
+  {"auto s = ^[[\"Hello, world!\"]]; // string literal",
+   [](HoverInfo &HI) {
+ HI.Name = "string-literal";
+ HI.Size = 14;
+ HI.Type = "const char[14]";
+   }},
   {
   R"cpp(// Local variable
 int main() {
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -777,6 +777,17 @@
   return HI;
 }
 
+HoverInfo getStringLiteralContents(const StringLiteral *SL,
+   const PrintingPolicy &PP) {
+  HoverInfo HI;
+
+  HI.Name = "string-literal";
+  HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth();
+  HI.Type = SL->getType().getAsString(PP).c_str();
+
+  return HI;
+}
+
 bool isLiteral(const Expr *E) {
   // Unfortunately there's no common base Literal classes inherits from
   // (apart from Expr), therefore these exclusions.
@@ -785,7 +796,7 @@
  llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
  llvm::isa(E) || llvm::isa(E) ||
- llvm::isa(E) || llvm::isa(E);
+ llvm::isa(E);
 }
 
 llvm::StringLiteral getNameForExpr(const Expr *E) {
@@ -810,6 +821,9 @@
 return llvm::None;
 
   HoverInfo HI;
+  // Print the type and the size for string literals
+  if (const StringLiteral *SL = dyn_cast(E))
+return getStringLiteralContents(SL, PP);
   // For `this` expr we currently generate hover with pointee type.
   if (const CXXThisExpr *CTE = dyn_cast(E))
 return getThisExprHoverContents(CTE, AST.getASTContext(), PP);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137751: Produce a more informative diagnostics when Clang runs out of source locations

2022-11-10 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

Thanks for adding this diagnostic! I wonder whether we can include SLoc usage 
information into `-print-stats` output?




Comment at: clang/lib/Basic/SourceManager.cpp:2251
+  uint64_t CountedSize = 0;
+  for (int IDIndex = -(int)LoadedSLocEntryTable.size() - 1;
+   IDIndex < (int)LocalSLocEntryTable.size(); ++IDIndex) {

Could you add a comment about the meaning of negative IDIndex values?



Comment at: clang/test/Lexer/SourceLocationsOverflow.c:7
+// CHECK-NEXT: note: 214{{...}}B in local locations, 0B in locations 
loaded from AST files, for a total of 214{{...}}B (99% of available space)
+// CHECK-NEXT: 
/usr/local/google/home/richardsmith/llvm-mono-1/src/clang/test/Lexer/Inputs/inc2.h:1:1:
 note: file entered 214{{..}} times using 214{{...}}B of space
+// CHECK-NEXT: 
/*.

You probably didn't mean to match local paths on your machine. Same below.


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

https://reviews.llvm.org/D137751

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


[PATCH] D137319: [include-cleaner] Add export IWYU pragma support.

2022-11-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 474505.
hokein marked 8 inline comments as done.
hokein added a comment.

address remaining comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137319

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -10,6 +10,7 @@
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -30,6 +31,13 @@
   return false;
 }
 
+MATCHER_P(FileNamed, N, "") {
+  if (arg->tryGetRealPathName() == N)
+return true;
+  *result_listener << arg->tryGetRealPathName().str();
+  return false;
+}
+
 class RecordASTTest : public ::testing::Test {
 protected:
   TestInputs Inputs;
@@ -111,19 +119,43 @@
   }
 
   TestAST build() { return TestAST(Inputs); }
+
+  void createEmptyFiles(llvm::ArrayRef FileNames) {
+for (llvm::StringRef File : FileNames)
+  Inputs.ExtraFiles[File] = "";
+  }
 };
 
 TEST_F(PragmaIncludeTest, IWYUKeep) {
   Inputs.Code = R"cpp(// Line 1
 #include "keep1.h" // IWYU pragma: keep
 #include "keep2.h" /* IWYU pragma: keep */
+
+#include "export1.h" // IWYU pragma: export // line 5
+// IWYU pragma: begin_exports
+#include "export2.h" // Line 7
+#include "export3.h"
+// IWYU pragma: end_exports
+
+#include "normal.h" // Line 11
   )cpp";
-  Inputs.ExtraFiles["keep1.h"] = Inputs.ExtraFiles["keep2.h"] = "";
+  createEmptyFiles({"keep1.h", "keep2.h", "export1.h", "export2.h", "export3.h",
+"normal.h"});
 
   TestAST Processed = build();
   EXPECT_FALSE(PI.shouldKeep(1));
+  // Keep
   EXPECT_TRUE(PI.shouldKeep(2));
   EXPECT_TRUE(PI.shouldKeep(3));
+
+  // Exports
+  EXPECT_TRUE(PI.shouldKeep(5));
+  EXPECT_TRUE(PI.shouldKeep(7));
+  EXPECT_TRUE(PI.shouldKeep(8));
+  EXPECT_FALSE(PI.shouldKeep(6)); // no # directive
+  EXPECT_FALSE(PI.shouldKeep(9)); // no # directive
+
+  EXPECT_FALSE(PI.shouldKeep(11));
 }
 
 TEST_F(PragmaIncludeTest, IWYUPrivate) {
@@ -144,5 +176,73 @@
   EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
 }
 
+TEST_F(PragmaIncludeTest, IWYUExport) {
+  Inputs.Code = R"cpp(// Line 1
+#include "export1.h"
+#include "export2.h"
+  )cpp";
+  Inputs.ExtraFiles["export1.h"] = R"cpp(
+#include "private.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["export2.h"] = R"cpp(
+#include "export3.h"
+  )cpp";
+  Inputs.ExtraFiles["export3.h"] = R"cpp(
+#include "private.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["private.h"] = "";
+  TestAST Processed = build();
+  const auto &SM = Processed.sourceManager();
+  auto &FM = Processed.fileManager();
+
+  EXPECT_THAT(PI.getExporters(FM.getFile("private.h").get(), FM),
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("export3.h")));
+
+  EXPECT_TRUE(PI.getExporters(FM.getFile("export1.h").get(), FM).empty());
+  EXPECT_TRUE(PI.getExporters(FM.getFile("export2.h").get(), FM).empty());
+  EXPECT_TRUE(PI.getExporters(FM.getFile("export3.h").get(), FM).empty());
+  EXPECT_TRUE(
+  PI.getExporters(SM.getFileEntryForID(SM.getMainFileID()), FM).empty());
+}
+
+TEST_F(PragmaIncludeTest, IWYUExportBlock) {
+  Inputs.Code = R"cpp(// Line 1
+   #include "normal.h"
+  )cpp";
+  Inputs.ExtraFiles["normal.h"] = R"cpp(
+#include "foo.h"
+
+// IWYU pragma: begin_exports
+#include "export1.h"
+#include "private1.h"
+// IWYU pragma: end_exports
+  )cpp";
+  Inputs.ExtraFiles["export1.h"] = R"cpp(
+// IWYU pragma: begin_exports
+#include "private1.h"
+#include "private2.h"
+// IWYU pragma: end_exports
+
+#include "bar.h"
+#include "private3.h" // IWYU pragma: export
+  )cpp";
+  createEmptyFiles(
+  {"private1.h", "private2.h", "private3.h", "foo.h", "bar.h"});
+  TestAST Processed = build();
+  auto &FM = Processed.fileManager();
+
+  EXPECT_THAT(PI.getExporters(FM.getFile("private1.h").get(), FM),
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("normal.h")));
+  EXPECT_THAT(PI.getExporters(FM.getFile("private2.h").get(), FM),
+  testing::UnorderedElementsAre(FileNamed("export1.h")));
+  EXPECT_THAT(PI.getExporters(FM.getFile("private3.h").get(), FM),
+  testing::UnorderedElementsAre(FileNamed("export1.h")));
+
+  EXPECT_TRUE(PI.getEx

[PATCH] D136723: [include-cleaner] Record main-file macro occurences and includes

2022-11-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

In D136723#3915898 , @sammccall wrote:

> (and sorry, it seems I was sitting on a pile of comments I thought I'd sent, 
> LMK if I should follow up on them)

no looks good. the only meaty discussion was fileentry to multiple 
includes/files related ones, and i guess deferring them is fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136723

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


[PATCH] D137714: Do not merge traps in functions annotated optnone

2022-11-10 Thread Henrik G Olsson via Phabricator via cfe-commits
hnrklssn created this revision.
Herald added a project: All.
delcypher added a comment.
hnrklssn updated this revision to Diff 474504.
hnrklssn added reviewers: delcypher, rapidsna, fcloutier, t.p.northover, 
patrykstefanski.
hnrklssn published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

@hnrklssn Could you add a regression test?


hnrklssn added a comment.

Added regression test




Comment at: clang/lib/CodeGen/CodeGenModule.cpp:5321
 
+  SetLLVMFunctionAttributesForDefinition(D, Fn);
   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);

I'm a little worried about this ordering change here. Could this have some 
unintended consequences?



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:5321
 
+  SetLLVMFunctionAttributesForDefinition(D, Fn);
   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);

delcypher wrote:
> I'm a little worried about this ordering change here. Could this have some 
> unintended consequences?
Yeah I was also a bit worried about that when making the change, since the 
functions are both quite broad and I'm not familiar with them from before. 
However it doesn't break any test cases, so I'm not sure what the consequences 
would be exactly.

For reference, also moving the call to setNonAliasAttributes so that it is 
still before the call to SetLLVMFunctionAttributesForDefinition breaks a ton of 
test cases so I'm somewhat hopeful that we have good test coverage for this 
type of change.


This aligns the behaviour with that of disabling optimisations for the
translation unit entirely. Not merging the traps allows us to keep
separate debug information for each, improving the debugging experience
when finding the cause for a ubsan trap.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137714

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/ubsan-trap-debugloc.c


Index: clang/test/CodeGen/ubsan-trap-debugloc.c
===
--- clang/test/CodeGen/ubsan-trap-debugloc.c
+++ clang/test/CodeGen/ubsan-trap-debugloc.c
@@ -7,4 +7,16 @@
   a = a + 1;
 }
 
+void bar(volatile int a) __attribute__((optnone)) {
+  // CHECK: call void @llvm.ubsantrap(i8 0){{.*}} !dbg [[LOC2:![0-9]+]]
+  // CHECK: call void @llvm.ubsantrap(i8 0){{.*}} !dbg [[LOC3:![0-9]+]]
+  a = a + 1;
+  a = a + 1;
+}
+
+// With optimisations enabled the traps are merged and need to share a debug 
location
 // CHECK: [[LOC]] = !DILocation(line: 0
+
+// With optimisations disabled the traps are not merged and retain accurate 
debug locations
+// CHECK: [[LOC2]] = !DILocation(line: 13, column: 9
+// CHECK: [[LOC3]] = !DILocation(line: 14, column: 9
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -5318,10 +5318,10 @@
   // Set CodeGen attributes that represent floating point environment.
   setLLVMFunctionFEnvAttributes(D, Fn);
 
+  SetLLVMFunctionAttributesForDefinition(D, Fn);
   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
 
   setNonAliasAttributes(GD, Fn);
-  SetLLVMFunctionAttributesForDefinition(D, Fn);
 
   if (const ConstructorAttr *CA = D->getAttr())
 AddGlobalCtor(Fn, CA->getPriority());
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -3545,7 +3545,8 @@
 TrapBBs.resize(CheckHandlerID + 1);
   llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
 
-  if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
+  if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB ||
+  CurFn->hasFnAttribute(llvm::Attribute::OptimizeNone)) {
 TrapBB = createBasicBlock("trap");
 Builder.CreateCondBr(Checked, Cont, TrapBB);
 EmitBlock(TrapBB);


Index: clang/test/CodeGen/ubsan-trap-debugloc.c
===
--- clang/test/CodeGen/ubsan-trap-debugloc.c
+++ clang/test/CodeGen/ubsan-trap-debugloc.c
@@ -7,4 +7,16 @@
   a = a + 1;
 }
 
+void bar(volatile int a) __attribute__((optnone)) {
+  // CHECK: call void @llvm.ubsantrap(i8 0){{.*}} !dbg [[LOC2:![0-9]+]]
+  // CHECK: call void @llvm.ubsantrap(i8 0){{.*}} !dbg [[LOC3:![0-9]+]]
+  a = a + 1;
+  a = a + 1;
+}
+
+// With optimisations enabled the traps are merged and need to share a debug location
 // CHECK: [[LOC]] = !DILocation(line: 0
+
+// With optimisations disabled the traps are not merged and retain accurate debug locations
+// CHECK: [[LOC2]] = !DILocation(line: 13, column: 9
+// CHECK: [[LOC3]] = !DILocation(line: 14, column: 9
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule

[PATCH] D137319: [include-cleaner] Add export IWYU pragma support.

2022-11-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks for bearing with me, LG!




Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:72
 
+  void checkForExport(FileID FileSeenHash, int HashLine,
+  const FileEntry *IncludedHeader) {

`FileSeenHash` feels a little bit confusing (sounds like hash of an entity), 
why not directly call it as the `IncludingFile`? (similarly instead of 
`HashLine`, `IncludeLine` or `DirectiveLine` ?)



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:84
+Out->IWYUExportBy[IncludedHeader->getUniqueID()].push_back(
+save(SM.getFileEntryForID(Top.SeenAtFile)->tryGetRealPathName()));
+  // main-file #include with export pragma should never be removed.

i guess we should just use `Top.FullPath` here instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137319

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


[PATCH] D137583: [lldb] Fix simple template names and template params with scope qualifiers

2022-11-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D137583#3917735 , @dblaikie wrote:

> In D137583#3917706 , @aaron.ballman 
> wrote:
>
>>> ...we expect template params to be fully qualified when comparing them for 
>>> simple template names
>>
>> So lldb is not inspecting the AST, they're doing reflection (of a sort) on 
>> the pretty printed names? Or am I misunderstanding something?
>
> Not reflection as such - but building names for the user, but partly from the 
> AST - basically LLDB wants to be able to produce the same name that 
> CGDebugInfo produces - so, maybe it should produce it the same way as 
> CGDebugInfo, which isn't to use the pretty printer from scratch.

Ah thank you for the clarification, that makes more sense to me.

> @aeubanks would this work for lldb's use case? 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/CodeGen/CGDebugInfo.cpp#L5229
>  it'd be identical to the original debug info generation, and looks like it 
> doesn't require a printing policy change/feature. Sorry I didn't think of 
> that earlier. I guess since `Qualified` would be `false` for lldb's use case, 
> you could go down into the implementation and just call the unqualified side 
> directly: `NamedDecl::printName(OS, Policy);` should print it unqualified for 
> this name, but respect the qualified printing policy flag for any nested 
> names, parameters, etc.

I agree that it seems pretty sensible for the debugger to use the same 
mechanisms as debug info in terms of what names to display for users.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137583

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


[PATCH] D137578: Fix 'unsafe-math-optimizations' flag dependencies

2022-11-10 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam updated this revision to Diff 474515.
zahiraam edited the summary of this revision.
zahiraam added reviewers: andrew.w.kaylor, michele.scandale.
zahiraam set the repository for this revision to rG LLVM Github Monorepo.
zahiraam changed the visibility from "Custom Policy" to "All Users".
zahiraam added a project: clang.
zahiraam edited subscribers, added: cfe-commits; removed: andrew.w.kaylor, 
michele.scandale.
Herald added a subscriber: MaskRay.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137578

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGenOpenCL/relaxed-fpmath.cl
  clang/test/Driver/fp-contract.c

Index: clang/test/Driver/fp-contract.c
===
--- clang/test/Driver/fp-contract.c
+++ clang/test/Driver/fp-contract.c
@@ -1,6 +1,8 @@
 // Test that -ffp-contract is set to the right value when combined with
-// the options -ffast-math and -fno-fast-math.
+// the options -ffast-math, -fno-fast-math, funsafe-math-optimizations,
+// fno-unsafe-math-optimizations.
 
+// ffast-math, fno-fast-math
 // RUN: %clang -### -ffast-math -c %s 2>&1  \
 // RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
 // CHECK-FPC-FAST: "-ffp-contract=fast"
@@ -112,3 +114,123 @@
 // RUN: %clang -### -fno-fast-math -ffast-math -ffp-contract=off \
 // RUN: -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-OFF %s
 
+// funsafe-math-optimizations, fno-unsafe-math-optimizations
+// RUN: %clang -### -funsafe-math-optimizations -c %s 2>&1  \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=on -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=off -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=fast -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -ffp-contract=fast -funsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+// RUN: %clang -### -ffp-contract=on -funsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+// RUN: %clang -### -ffp-contract=off -funsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -ffp-contract=fast -fno-unsafe-math-optimizations -c \
+// RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-FAST %s
+// RUN: %clang -### -ffp-contract=on -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+// RUN: %clang -### -ffp-contract=off -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=fast \
+// RUN: -ffp-contract=on -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=on \
+// RUN: -ffp-contract=off -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=on \
+// RUN: -ffp-contract=fast -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=off \
+// RUN: -ffp-contract=on -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=off \
+// RUN: -ffp-contract=fast \
+// RUN: -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=on \
+// RUN: -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=off \
+// RUN: -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -funsafe-math-optimizations -ffp-contract=fast \
+// RUN: -fno-unsafe-math-optimizations -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -funsafe-math-optimizations -fno-unsafe-math-optimizations \
+// RUN: -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -fno-unsafe-math-optimizations -funsafe-math-optimizations \
+// RUN: -c %s 2>&1 | FileCheck --check-prefix=CHECK-FPC-FAST %s
+
+// RUN: %clang -### -fno-unsafe-math-optimizations -ffp-contract=on -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
+
+// RUN: %clang -### -fno-unsafe-math-optimizations -ffp-contract=off -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FPC-OFF %s
+
+// RUN: %clang -### -fno-uns

[PATCH] D137782: [clang-tidy]bugprone-fold-init-type

2022-11-10 Thread Clement Courbet via Phabricator via cfe-commits
courbet created this revision.
courbet added a reviewer: aaron.ballman.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
courbet requested review of this revision.
Herald added a project: clang-tools-extra.

Handle iterators that do not define a `value_type` type alias.

Get the value type from the return type of `Iter::operator*` instead.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137782

Files:
  clang-tools-extra/clang-tidy/bugprone/FoldInitTypeCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp
@@ -1,39 +1,67 @@
-// RUN: %check_clang_tidy %s bugprone-fold-init-type %t
+// RUN: %check_clang_tidy %s bugprone-fold-init-type -std=c++17 %t
 
 namespace std {
 template 
-T accumulate(InputIt first, InputIt last, T init);
+T accumulate(InputIt first, InputIt last, T init) {
+  // When `InputIt::operator*` returns a deduced `auto` type that refers to a
+  // dependent type, the return type is deduced only if `InputIt::operator*`
+  // is instantiated. In practice this happens somewhere in the implementation
+  // of `accumulate`. For tests, do it here.
+  (void)*first;
+}
 
 template 
-T reduce(InputIt first, InputIt last, T init);
+T reduce(InputIt first, InputIt last, T init) { (void)*first; }
 template 
 T reduce(ExecutionPolicy &&policy,
- InputIt first, InputIt last, T init);
+ InputIt first, InputIt last, T init) { (void)*first; }
 
 struct parallel_execution_policy {};
 constexpr parallel_execution_policy par{};
 
 template 
 T inner_product(InputIt1 first1, InputIt1 last1,
-InputIt2 first2, T value);
+InputIt2 first2, T value) { (void)*first1; (void)*first2; }
 
 template 
 T inner_product(ExecutionPolicy &&policy, InputIt1 first1, InputIt1 last1,
-InputIt2 first2, T value);
+InputIt2 first2, T value) { (void)*first1; (void)*first2; }
 
 } // namespace std
 
 struct FloatIterator {
-  typedef float value_type;
+  const float &operator*() const;
 };
+
+struct DerivedFloatIterator : public FloatIterator {
+};
+
+template  struct ByValueTemplateIterator {
+  ValueType operator*() const;
+};
+
+template  struct ByRefTemplateIterator {
+  ValueType &operator*();
+};
+
+template  struct ByRefTemplateIteratorWithAlias {
+  using reference = const ValueType&;
+  reference operator*();
+};
+
+template  struct AutoByValueTemplateIterator {
+  auto operator*() const { return ValueType{}; }
+};
+
+template  struct AutoByRefTemplateIterator {
+  decltype(auto) operator*() const { return value_; }
+  ValueType value_;
+};
+
 template 
-struct TypedefTemplateIterator { typedef ValueType value_type; };
-template 
-struct UsingTemplateIterator { using value_type = ValueType; };
-template 
-struct DependentTypedefTemplateIterator { typedef typename ValueType::value_type value_type; };
-template 
-struct DependentUsingTemplateIterator : public TypedefTemplateIterator { using typename TypedefTemplateIterator::value_type; };
+struct InheritingByConstRefTemplateIterator
+: public ByRefTemplateIterator {};
+
 using TypedeffedIterator = FloatIterator;
 
 // Positives.
@@ -51,39 +79,57 @@
 }
 
 int accumulatePositive3() {
+  DerivedFloatIterator it;
+  return std::accumulate(it, it, 0);
+  // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'float' into type 'int'
+}
+
+int accumulatePositive4() {
   double a[1] = {0.0};
   return std::accumulate(a, a + 1, 0.0f);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'double' into type 'float'
 }
 
-int accumulatePositive4() {
-  TypedefTemplateIterator it;
+int accumulatePositive5() {
+  ByValueTemplateIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
 }
 
-int accumulatePositive5() {
-  UsingTemplateIterator it;
+int accumulatePositive6() {
+  ByRefTemplateIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
 }
 
-int accumulatePositive6() {
-  DependentTypedefTemplateIterator> it;
+int accumulatePositive7() {
+  AutoByValueTemplateIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
 }
 
-int accumulatePositive7() {
+int accumulatePositive8() {
   TypedeffedIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'float' into type 'int'
 }
 
-int accumulatePositive8() {
-  DependentUsingTemplateIterator it;
+int accumulatePositive9() {
+  InheritingByCo

[PATCH] D137578: Fix 'unsafe-math-optimizations' flag dependencies

2022-11-10 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added inline comments.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:3957
 
-  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
-StringRef Val = A->getValue();
-if (Val == "fast")
+  if (auto *A = Args.getLastArg(OPT_ffp_contract, OPT_cl_fast_relaxed_math,
+OPT_cl_unsafe_math_optimizations)) {

michele.scandale wrote:
> If I look only at the CC1 behavior then I think this is probably the desired 
> behavior.
> 
> However from the compiler driver perspective it seems that `-ffp-contract` 
> and `-cl-*` math options don't really play well together -- in 
> `RenderFloatingPointOptions` the OpenCL related options are not considered, 
> and similarly in `RenderOpenCLOptions` the other floating point options are 
> not considered.
> 
> It's not clear to me if it is expected to mix OpenCL specific options with 
> other floating point related options -- given todays code it seems that is 
> not expected.
> For the time being it is probably better to simply keep the `ffp_contract` 
> handling as is today, and modify the code around line 3803 as follow
> ```
>   if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
> Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
> ```
> to handle `-cl-unsafe-math-optimizations` similarly to 
> `-cl-fast-relaxed-math` w.r.t. contraction behavior.
>>
It's not clear to me if it is expected to mix OpenCL specific options with 
other floating point related options -- given todays code it seems that is not 
expected.
>>
Yes, it looks like the FP options and CL options are orthogonal. Even so not 
sure how OpenCL people will react to the LIT test behavioral change 
(relaxed-fpmath.cl). Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137578

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


[PATCH] D137782: [clang-tidy]bugprone-fold-init-type

2022-11-10 Thread Clement Courbet via Phabricator via cfe-commits
courbet updated this revision to Diff 474520.
courbet added a comment.

fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137782

Files:
  clang-tools-extra/clang-tidy/bugprone/FoldInitTypeCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp
@@ -1,39 +1,67 @@
-// RUN: %check_clang_tidy %s bugprone-fold-init-type %t
+// RUN: %check_clang_tidy %s bugprone-fold-init-type -std=c++17 %t
 
 namespace std {
 template 
-T accumulate(InputIt first, InputIt last, T init);
+T accumulate(InputIt first, InputIt last, T init) {
+  // When `InputIt::operator*` returns a deduced `auto` type that refers to a
+  // dependent type, the return type is deduced only if `InputIt::operator*`
+  // is instantiated. In practice this happens somewhere in the implementation
+  // of `accumulate`. For tests, do it here.
+  (void)*first;
+}
 
 template 
-T reduce(InputIt first, InputIt last, T init);
+T reduce(InputIt first, InputIt last, T init) { (void)*first; }
 template 
 T reduce(ExecutionPolicy &&policy,
- InputIt first, InputIt last, T init);
+ InputIt first, InputIt last, T init) { (void)*first; }
 
 struct parallel_execution_policy {};
 constexpr parallel_execution_policy par{};
 
 template 
 T inner_product(InputIt1 first1, InputIt1 last1,
-InputIt2 first2, T value);
+InputIt2 first2, T value) { (void)*first1; (void)*first2; }
 
 template 
 T inner_product(ExecutionPolicy &&policy, InputIt1 first1, InputIt1 last1,
-InputIt2 first2, T value);
+InputIt2 first2, T value) { (void)*first1; (void)*first2; }
 
 } // namespace std
 
 struct FloatIterator {
-  typedef float value_type;
+  const float &operator*() const;
 };
+
+struct DerivedFloatIterator : public FloatIterator {
+};
+
+template  struct ByValueTemplateIterator {
+  ValueType operator*() const;
+};
+
+template  struct ByRefTemplateIterator {
+  ValueType &operator*();
+};
+
+template  struct ByRefTemplateIteratorWithAlias {
+  using reference = const ValueType&;
+  reference operator*();
+};
+
+template  struct AutoByValueTemplateIterator {
+  auto operator*() const { return ValueType{}; }
+};
+
+template  struct AutoByRefTemplateIterator {
+  decltype(auto) operator*() const { return value_; }
+  ValueType value_;
+};
+
 template 
-struct TypedefTemplateIterator { typedef ValueType value_type; };
-template 
-struct UsingTemplateIterator { using value_type = ValueType; };
-template 
-struct DependentTypedefTemplateIterator { typedef typename ValueType::value_type value_type; };
-template 
-struct DependentUsingTemplateIterator : public TypedefTemplateIterator { using typename TypedefTemplateIterator::value_type; };
+struct InheritingByConstRefTemplateIterator
+: public ByRefTemplateIterator {};
+
 using TypedeffedIterator = FloatIterator;
 
 // Positives.
@@ -51,39 +79,57 @@
 }
 
 int accumulatePositive3() {
+  DerivedFloatIterator it;
+  return std::accumulate(it, it, 0);
+  // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'float' into type 'int'
+}
+
+int accumulatePositive4() {
   double a[1] = {0.0};
   return std::accumulate(a, a + 1, 0.0f);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'double' into type 'float'
 }
 
-int accumulatePositive4() {
-  TypedefTemplateIterator it;
+int accumulatePositive5() {
+  ByValueTemplateIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
 }
 
-int accumulatePositive5() {
-  UsingTemplateIterator it;
+int accumulatePositive6() {
+  ByRefTemplateIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
 }
 
-int accumulatePositive6() {
-  DependentTypedefTemplateIterator> it;
+int accumulatePositive7() {
+  AutoByValueTemplateIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
 }
 
-int accumulatePositive7() {
+int accumulatePositive8() {
   TypedeffedIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'float' into type 'int'
 }
 
-int accumulatePositive8() {
-  DependentUsingTemplateIterator it;
+int accumulatePositive9() {
+  InheritingByConstRefTemplateIterator it;
   return std::accumulate(it, it, 0);
-  // FIXME: this one should trigger too.
+  // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
+}
+
+int accumulatePositive10() {
+  AutoByRefTemplateIterator

[PATCH] D137578: Fix 'unsafe-math-optimizations' flag dependencies

2022-11-10 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

In D137578#3918314 , 
@michele.scandale wrote:

> Looks good to me

@michele.scandale Now that I opened up the patch to all, it needs another stamp 
from you. Would you mind reviewing it again please? I will wait for a day 
before pushing it to give time to others to look at it.  Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137578

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


[PATCH] D137770: [docs] Introduce clangd part in StandardCPlusPlusModules

2022-11-10 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu planned changes to this revision.
ChuanqiXu added a comment.

@sammccall Thanks for you professional and valuable input. It is very helpful. 
From the perspective of clangd, it looks not good indeed that the user can't 
get a stable support for modules.

> This situation is not at all obvious to users, and I'm impressed you managed 
> to figure out the bits that work! I think we should clarify the situation by 
> making clangd emit an error when modules are enabled (we can disable this 
> with a flag like --experimental-modules for people that want to work on 
> modules support/test it once someone works on it).

Could I interpret your words as the following?

- We should and could emit an error in clangd if it detects we're using modules.
- We can add a flag `--experimental-modules` to skip such errors.

If yes, I think I know how to implement this. We can add a PPCallbacks, which 
implement the `moduleImport` callbacks so that we can know it is importing a 
module (or declare a module). This should be the proper way. And we can use 
(and document) the `experimental-modules` flag to get the facility today (and 
better in future). Or in another word, the tests in D137693 
 can't be passed. But if could be if we add 
the `experimental-modules` flag  to the clangd. Do I understand correctly?

---

The following off is the plan in the longer term. From my point of view, your 
word mentions 2 different concern:

- inner concern: we need new design in the clangd to make clangd understand 
modules really.
- outer concern: we need an protocal between clangd and the build system to 
allow the clangd to inform the build system to build modules. And we need the 
compiler (clang) to parse the module file from different versions.

From my point of view, both concerns are hard to address. While I don't know a 
lot about the implementation details about clangd, both of the two outer 
concern are not easy to address. (Although they are absolutely the correct 
direction, of course). I'm afraid that I can take it. But I'll try to look at 
the implementation of clangd more (I've tried to read it for a few days and it 
is not easy indeed) to have a strong feelings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137770

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


[PATCH] D137765: [NFC] Fixing a comment and some indentations

2022-11-10 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


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137765

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


[PATCH] D137693: [NFC] [C++20] [Modules] [clangd] Add test for code completion for C++20 Named Modules

2022-11-10 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu planned changes to this revision.
ChuanqiXu added a comment.

Thanks for the explanation. I got your point.


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

https://reviews.llvm.org/D137693

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


[libunwind] 4fde94f - [libunwind][NFC] Fix typo in libunwind debug string

2022-11-10 Thread via cfe-commits

Author: jinge90
Date: 2022-11-10T21:46:49+08:00
New Revision: 4fde94fb43297934428a685a90fd48ddf62457dc

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

LOG: [libunwind][NFC] Fix typo in libunwind debug string

Reviewed By: mstorsjo

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

Signed-off-by: jinge90 

Added: 


Modified: 
libunwind/src/UnwindLevel1.c

Removed: 




diff  --git a/libunwind/src/UnwindLevel1.c b/libunwind/src/UnwindLevel1.c
index f984a8bb6adec..7e9adf64246df 100644
--- a/libunwind/src/UnwindLevel1.c
+++ b/libunwind/src/UnwindLevel1.c
@@ -84,13 +84,13 @@ unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, 
_Unwind_Exception *except
 int stepResult = __unw_step(cursor);
 if (stepResult == 0) {
   _LIBUNWIND_TRACE_UNWINDING(
-  "unwind_phase1(ex_ojb=%p): __unw_step() reached "
+  "unwind_phase1(ex_obj=%p): __unw_step() reached "
   "bottom => _URC_END_OF_STACK",
   (void *)exception_object);
   return _URC_END_OF_STACK;
 } else if (stepResult < 0) {
   _LIBUNWIND_TRACE_UNWINDING(
-  "unwind_phase1(ex_ojb=%p): __unw_step failed => "
+  "unwind_phase1(ex_obj=%p): __unw_step failed => "
   "_URC_FATAL_PHASE1_ERROR",
   (void *)exception_object);
   return _URC_FATAL_PHASE1_ERROR;
@@ -101,7 +101,7 @@ unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, 
_Unwind_Exception *except
 unw_word_t sp;
 if (__unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
   _LIBUNWIND_TRACE_UNWINDING(
-  "unwind_phase1(ex_ojb=%p): __unw_get_proc_info "
+  "unwind_phase1(ex_obj=%p): __unw_get_proc_info "
   "failed => _URC_FATAL_PHASE1_ERROR",
   (void *)exception_object);
   return _URC_FATAL_PHASE1_ERROR;
@@ -120,7 +120,7 @@ unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, 
_Unwind_Exception *except
   unw_word_t pc;
   __unw_get_reg(cursor, UNW_REG_IP, &pc);
   _LIBUNWIND_TRACE_UNWINDING(
-  "unwind_phase1(ex_ojb=%p): pc=0x%" PRIxPTR ", start_ip=0x%" PRIxPTR
+  "unwind_phase1(ex_obj=%p): pc=0x%" PRIxPTR ", start_ip=0x%" PRIxPTR
   ", func=%s, lsda=0x%" PRIxPTR ", personality=0x%" PRIxPTR "",
   (void *)exception_object, pc, frameInfo.start_ip, functionName,
   frameInfo.lsda, frameInfo.handler);
@@ -133,7 +133,7 @@ unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, 
_Unwind_Exception *except
   _Unwind_Personality_Fn p =
   (_Unwind_Personality_Fn)(uintptr_t)(frameInfo.handler);
   _LIBUNWIND_TRACE_UNWINDING(
-  "unwind_phase1(ex_ojb=%p): calling personality function %p",
+  "unwind_phase1(ex_obj=%p): calling personality function %p",
   (void *)exception_object, (void *)(uintptr_t)p);
   _Unwind_Reason_Code personalityResult =
   (*p)(1, _UA_SEARCH_PHASE, exception_object->exception_class,
@@ -145,13 +145,13 @@ unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, 
_Unwind_Exception *except
 __unw_get_reg(cursor, UNW_REG_SP, &sp);
 exception_object->private_2 = (uintptr_t)sp;
 _LIBUNWIND_TRACE_UNWINDING(
-"unwind_phase1(ex_ojb=%p): _URC_HANDLER_FOUND",
+"unwind_phase1(ex_obj=%p): _URC_HANDLER_FOUND",
 (void *)exception_object);
 return _URC_NO_REASON;
 
   case _URC_CONTINUE_UNWIND:
 _LIBUNWIND_TRACE_UNWINDING(
-"unwind_phase1(ex_ojb=%p): _URC_CONTINUE_UNWIND",
+"unwind_phase1(ex_obj=%p): _URC_CONTINUE_UNWIND",
 (void *)exception_object);
 // continue unwinding
 break;
@@ -159,7 +159,7 @@ unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, 
_Unwind_Exception *except
   default:
 // something went wrong
 _LIBUNWIND_TRACE_UNWINDING(
-"unwind_phase1(ex_ojb=%p): _URC_FATAL_PHASE1_ERROR",
+"unwind_phase1(ex_obj=%p): _URC_FATAL_PHASE1_ERROR",
 (void *)exception_object);
 return _URC_FATAL_PHASE1_ERROR;
   }
@@ -173,7 +173,7 @@ static _Unwind_Reason_Code
 unwind_phase2(unw_context_t *uc, unw_cursor_t *cursor, _Unwind_Exception 
*exception_object) {
   __unw_init_local(cursor, uc);
 
-  _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p)",
+  _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_obj=%p)",
  (void *)exception_object);
 
   // uc is initialized by __unw_getcontext in the parent frame. The first stack
@@ -190,13 +190,13 @@ unwind_phase2(unw_context_t *uc, unw_cursor_t *cursor, 
_Unwind_Exception *except
 int stepResult = __unw_step_stage2(cursor);
 if (stepResult == 0) {
   _LIBUNWIND_TRACE_UNWINDING(
-  "unwind_phase2(ex_ojb=%p): __unw_step_stage2() reached "
+

[PATCH] D137320: [include-cleaner] Initial version for the "Location=>Header" step

2022-11-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, lgtm!




Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:58
+Results = {{FE}};
+// FIXME: compute a closure of exporter headers.
+for (const auto *Export : PI.getExporters(FE, SM.getFileManager()))

hokein wrote:
> kadircet wrote:
> > hokein wrote:
> > > kadircet wrote:
> > > > not sure i follow the fixme here, are you suggesting we should also 
> > > > compute transitive exporters?
> > > Yeah, rephrased the FIXME.
> > i see, i am not sure if that's desired though.
> > 
> > e.g. if we have `foo.h` exporting `bar.h` exporting `baz.h`, I don't think 
> > `baz.h` counts (or should count) as an alternative to `foo.h`. do we have 
> > information proving otherwise?
> The classical IWYU tool has this semantic, see the nested_export test in 
> https://github.com/include-what-you-use/include-what-you-use/commit/9945e543d894e90fab5ebd0b685cabd5aa8dd21f.
wow, that's surprising. but i guess is a valid point.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137320

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


[PATCH] D125860: [clang] Only use major version in resource dir

2022-11-10 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 rGe1b88c8a09be: [clang] Only use major version in resource dir 
(authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125860

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Version.inc.in
  clang/lib/Driver/Driver.cpp
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Tooling/CMakeLists.txt
  clang/runtime/CMakeLists.txt
  compiler-rt/cmake/base-config-ix.cmake
  lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
  lldb/unittests/Expression/ClangParserTest.cpp
  llvm/cmake/modules/LLVMExternalProjectUtils.cmake
  polly/lib/External/isl/interface/extract_interface.cc

Index: polly/lib/External/isl/interface/extract_interface.cc
===
--- polly/lib/External/isl/interface/extract_interface.cc
+++ polly/lib/External/isl/interface/extract_interface.cc
@@ -109,7 +109,7 @@
 	llvm::cl::value_desc("name"));
 
 static const char *ResourceDir =
-	CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
+CLANG_PREFIX "/lib/clang/" CLANG_VERSION_MAJOR_STRING;
 
 /* Does decl have an attribute of the following form?
  *
Index: llvm/cmake/modules/LLVMExternalProjectUtils.cmake
===
--- llvm/cmake/modules/LLVMExternalProjectUtils.cmake
+++ llvm/cmake/modules/LLVMExternalProjectUtils.cmake
@@ -255,9 +255,9 @@
 set(llvm_config_path ${LLVM_CONFIG_PATH})
 
 if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
-  string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION
+  string(REGEX MATCH "^[0-9]+" CLANG_VERSION_MAJOR
  ${PACKAGE_VERSION})
-  set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION}")
+  set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION_MAJOR}")
   set(flag_types ASM C CXX MODULE_LINKER SHARED_LINKER EXE_LINKER)
   foreach(type ${flag_types})
 set(${type}_flag -DCMAKE_${type}_FLAGS=-resource-dir=${resource_dir})
Index: lldb/unittests/Expression/ClangParserTest.cpp
===
--- lldb/unittests/Expression/ClangParserTest.cpp
+++ lldb/unittests/Expression/ClangParserTest.cpp
@@ -38,10 +38,11 @@
 #if !defined(_WIN32)
   std::string path_to_liblldb = "/foo/bar/lib/";
   std::string path_to_clang_dir =
-  "/foo/bar/" LLDB_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_STRING;
+  "/foo/bar/" LLDB_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_MAJOR_STRING;
 #else
   std::string path_to_liblldb = "C:\\foo\\bar\\lib";
-  std::string path_to_clang_dir = "C:\\foo\\bar\\lib\\clang\\" CLANG_VERSION_STRING;
+  std::string path_to_clang_dir =
+  "C:\\foo\\bar\\lib\\clang\\" CLANG_VERSION_MAJOR_STRING;
 #endif
   EXPECT_EQ(ComputeClangResourceDir(path_to_liblldb), path_to_clang_dir);
 
Index: lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
@@ -55,7 +55,7 @@
   static const llvm::StringRef kResourceDirSuffixes[] = {
   // LLVM.org's build of LLDB uses the clang resource directory placed
   // in $install_dir/lib{,64}/clang/$clang_version.
-  CLANG_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_STRING,
+  CLANG_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_MAJOR_STRING,
   // swift-lldb uses the clang resource directory copied from swift, which
   // by default is placed in $install_dir/lib{,64}/lldb/clang. LLDB places
   // it there, so we use LLDB_INSTALL_LIBDIR_BASENAME.
Index: compiler-rt/cmake/base-config-ix.cmake
===
--- compiler-rt/cmake/base-config-ix.cmake
+++ compiler-rt/cmake/base-config-ix.cmake
@@ -38,14 +38,14 @@
 
 if (LLVM_TREE_AVAILABLE)
   # Compute the Clang version from the LLVM version.
-  # FIXME: We should be able to reuse CLANG_VERSION variable calculated
+  # FIXME: We should be able to reuse CLANG_VERSION_MAJOR variable calculated
   #in Clang cmake files, instead of copying the rules here.
-  string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION
+  string(REGEX MATCH "^[0-9]+" CLANG_VERSION_MAJOR
  ${PACKAGE_VERSION})
   # Setup the paths where compiler-rt runtimes and headers should be stored.
-  set(COMPILER_RT_OUTPUT_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR}/clang/${CLANG_VERSION})
+  set(COMPILER_RT_OUTPUT_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR}/clang/${CLANG_VERSION_MAJOR})
   set(COMPILER_RT_EXEC_OUTPUT_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR})
-  set(COMPILER_RT_INSTALL_PATH lib${LLVM_LIBDIR_SUFFIX}/clang/${CLANG_VERSION})
+  set(COMPILER_RT_INSTALL_PATH lib${LLVM_LIBDIR_SUFFIX}/clang/${C

[PATCH] D129156: Add -fpass-plugin option to Flang

2022-11-10 Thread Tarun Prabhu via Phabricator via cfe-commits
tarunprabhu marked 2 inline comments as done.
tarunprabhu added a comment.

Yes, I am aware of the other patch which also adds 
`test/Driver/pass-plugin.f90`. I will keep an eye out for it.




Comment at: flang/test/CMakeLists.txt:65
 )
+if (NOT WIN32)
+  list(APPEND FLANG_TEST_DEPENDS Bye)

awarzynski wrote:
> awarzynski wrote:
> > IIUC, `Bye` is only needed when plugins are enabled.
> IIUC, `WIN32` is still required. Sorry for not being clearer earlier.
Ugh! Yes, of course. I looked at `llvm/CMakeLists.txt` and somehow concluded 
that `LLVM_ENABLE_PLUGINS` is disabled if WIN32, but it is in fact the _default 
value_ of `LLVM_ENABLE_PLUGINS` that is set to `false` in that case. 


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

https://reviews.llvm.org/D129156

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


[PATCH] D137319: [include-cleaner] Add export IWYU pragma support.

2022-11-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked 2 inline comments as done.
hokein added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:84
+Out->IWYUExportBy[IncludedHeader->getUniqueID()].push_back(
+save(SM.getFileEntryForID(Top.SeenAtFile)->tryGetRealPathName()));
+  // main-file #include with export pragma should never be removed.

kadircet wrote:
> i guess we should just use `Top.FullPath` here instead?
oops, I added the FullPath, but forgot to update the usage here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137319

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


[clang-tools-extra] f3e8a11 - [include-cleaner] Add export IWYU pragma support.

2022-11-10 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-11-10T15:39:30+01:00
New Revision: f3e8a117d2bc8d439434db5cb77b1c8a425a38c0

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

LOG: [include-cleaner] Add export IWYU pragma support.

- add support to PragmaIncludes to handle IWYU export/begin_exports/end_exports
  pragma;
- implement an API to retrieve the direct exporter headers;

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

Added: 


Modified: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
clang-tools-extra/include-cleaner/lib/Record.cpp
clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Removed: 




diff  --git 
a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h 
b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
index f3fdeeec4faa7..6a6e339a7f43f 100644
--- a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
+++ b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
@@ -19,6 +19,9 @@
 
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Allocator.h"
 #include "llvm/Support/FileSystem/UniqueID.h"
 #include "clang-include-cleaner/Types.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -35,6 +38,7 @@ class Decl;
 class FileEntry;
 class Preprocessor;
 class PPCallbacks;
+class FileManager;
 
 namespace include_cleaner {
 
@@ -61,6 +65,11 @@ class PragmaIncludes {
   /// Returns "" if there is none.
   llvm::StringRef getPublic(const FileEntry *File) const;
 
+  /// Returns all direct exporter headers for the given header file.
+  /// Returns empty if there is none.
+  llvm::SmallVector getExporters(const FileEntry *File,
+FileManager &FM) const;
+
 private:
   class RecordPragma;
   /// 1-based Line numbers for the #include directives of the main file that
@@ -73,10 +82,21 @@ class PragmaIncludes {
   // !!NOTE: instead of using a FileEntry* to identify the physical file, we
   // deliberately use the UniqueID to ensure the result is stable across
   // FileManagers (for clangd's preamble and main-file builds).
-  llvm::DenseMap
+  llvm::DenseMap
   IWYUPublic;
 
-  // FIXME: add other IWYU supports (export etc)
+  /// A reverse map from the underlying header to its exporter headers.
+  //
+  //  There's no way to get a FileEntry from a UniqueID, especially when it
+  //  hasn't been opened before. So store the full path and convert it to a
+  //  FileEntry by opening the file again through a FileManager.
+  llvm::DenseMap>
+  IWYUExportBy;
+
+  /// Owns the strings.
+  llvm::BumpPtrAllocator Arena;
+
   // FIXME: add support for clang use_instead pragma
   // FIXME: add selfcontained file.
 };

diff  --git a/clang-tools-extra/include-cleaner/lib/Record.cpp 
b/clang-tools-extra/include-cleaner/lib/Record.cpp
index 752f0e3d8b739..948b14c3338f5 100644
--- a/clang-tools-extra/include-cleaner/lib/Record.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -118,7 +118,7 @@ static llvm::Optional parseIWYUPragma(const char 
*Text) {
 class PragmaIncludes::RecordPragma : public PPCallbacks, public CommentHandler 
{
 public:
   RecordPragma(const CompilerInstance &CI, PragmaIncludes *Out)
-  : SM(CI.getSourceManager()), Out(Out) {}
+  : SM(CI.getSourceManager()), Out(Out), UniqueStrings(Arena) {}
 
   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
@@ -126,6 +126,16 @@ class PragmaIncludes::RecordPragma : public PPCallbacks, 
public CommentHandler {
 InMainFile = SM.isWrittenInMainFile(Loc);
   }
 
+  void EndOfMainFile() override {
+for (auto &It : Out->IWYUExportBy) {
+  llvm::sort(It.getSecond());
+  It.getSecond().erase(
+  std::unique(It.getSecond().begin(), It.getSecond().end()),
+  It.getSecond().end());
+}
+Out->Arena = std::move(Arena);
+  }
+
   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
   llvm::StringRef FileName, bool IsAngled,
   CharSourceRange /*FilenameRange*/,
@@ -134,14 +144,35 @@ class PragmaIncludes::RecordPragma : public PPCallbacks, 
public CommentHandler {
   llvm::StringRef /*RelativePath*/,
   const clang::Module * /*Imported*/,
   SrcMgr::CharacteristicKind FileKind) override {
-if (!InMainFile)
-  return;
-int HashLine =
-SM.getLineNumber(SM.getMainFileID(), SM.getFileOffset(HashLoc));
-if (LastPragmaKeepInMainFileLine == HashLine)
+FileID HashFID = SM.getFileID(HashLoc);
+int Hash

[PATCH] D137319: [include-cleaner] Add export IWYU pragma support.

2022-11-10 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
hokein marked an inline comment as done.
Closed by commit rGf3e8a117d2bc: [include-cleaner] Add export IWYU pragma 
support. (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D137319?vs=474505&id=474534#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137319

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -12,6 +12,7 @@
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
@@ -36,6 +37,13 @@
   return false;
 }
 
+MATCHER_P(FileNamed, N, "") {
+  if (arg->tryGetRealPathName() == N)
+return true;
+  *result_listener << arg->tryGetRealPathName().str();
+  return false;
+}
+
 class RecordASTTest : public ::testing::Test {
 protected:
   TestInputs Inputs;
@@ -257,22 +265,43 @@
   }
 
   TestAST build() { return TestAST(Inputs); }
+
+  void createEmptyFiles(llvm::ArrayRef FileNames) {
+for (llvm::StringRef File : FileNames)
+  Inputs.ExtraFiles[File] = "";
+  }
 };
 
 TEST_F(PragmaIncludeTest, IWYUKeep) {
   Inputs.Code = R"cpp(// Line 1
 #include "keep1.h" // IWYU pragma: keep
 #include "keep2.h" /* IWYU pragma: keep */
-#include "normal.h"
+
+#include "export1.h" // IWYU pragma: export // line 5
+// IWYU pragma: begin_exports
+#include "export2.h" // Line 7
+#include "export3.h"
+// IWYU pragma: end_exports
+
+#include "normal.h" // Line 11
   )cpp";
-  Inputs.ExtraFiles["keep1.h"] = Inputs.ExtraFiles["keep2.h"] =
-  Inputs.ExtraFiles["normal.h"] = "";
+  createEmptyFiles({"keep1.h", "keep2.h", "export1.h", "export2.h", "export3.h",
+"normal.h"});
 
   TestAST Processed = build();
   EXPECT_FALSE(PI.shouldKeep(1));
+  // Keep
   EXPECT_TRUE(PI.shouldKeep(2));
   EXPECT_TRUE(PI.shouldKeep(3));
-  EXPECT_FALSE(PI.shouldKeep(4));
+
+  // Exports
+  EXPECT_TRUE(PI.shouldKeep(5));
+  EXPECT_TRUE(PI.shouldKeep(7));
+  EXPECT_TRUE(PI.shouldKeep(8));
+  EXPECT_FALSE(PI.shouldKeep(6)); // no # directive
+  EXPECT_FALSE(PI.shouldKeep(9)); // no # directive
+
+  EXPECT_FALSE(PI.shouldKeep(11));
 }
 
 TEST_F(PragmaIncludeTest, IWYUPrivate) {
@@ -293,5 +322,73 @@
   EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
 }
 
+TEST_F(PragmaIncludeTest, IWYUExport) {
+  Inputs.Code = R"cpp(// Line 1
+#include "export1.h"
+#include "export2.h"
+  )cpp";
+  Inputs.ExtraFiles["export1.h"] = R"cpp(
+#include "private.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["export2.h"] = R"cpp(
+#include "export3.h"
+  )cpp";
+  Inputs.ExtraFiles["export3.h"] = R"cpp(
+#include "private.h" // IWYU pragma: export
+  )cpp";
+  Inputs.ExtraFiles["private.h"] = "";
+  TestAST Processed = build();
+  const auto &SM = Processed.sourceManager();
+  auto &FM = Processed.fileManager();
+
+  EXPECT_THAT(PI.getExporters(FM.getFile("private.h").get(), FM),
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+FileNamed("export3.h")));
+
+  EXPECT_TRUE(PI.getExporters(FM.getFile("export1.h").get(), FM).empty());
+  EXPECT_TRUE(PI.getExporters(FM.getFile("export2.h").get(), FM).empty());
+  EXPECT_TRUE(PI.getExporters(FM.getFile("export3.h").get(), FM).empty());
+  EXPECT_TRUE(
+  PI.getExporters(SM.getFileEntryForID(SM.getMainFileID()), FM).empty());
+}
+
+TEST_F(PragmaIncludeTest, IWYUExportBlock) {
+  Inputs.Code = R"cpp(// Line 1
+   #include "normal.h"
+  )cpp";
+  Inputs.ExtraFiles["normal.h"] = R"cpp(
+#include "foo.h"
+
+// IWYU pragma: begin_exports
+#include "export1.h"
+#include "private1.h"
+// IWYU pragma: end_exports
+  )cpp";
+  Inputs.ExtraFiles["export1.h"] = R"cpp(
+// IWYU pragma: begin_exports
+#include "private1.h"
+#include "private2.h"
+// IWYU pragma: end_exports
+
+#include "bar.h"
+#include "private3.h" // IWYU pragma: export
+  )cpp";
+  createEmptyFiles(
+  {"private1.h", "private2.h", "private3.h", "foo.h", "bar.h"});
+  TestAST Processed = build();
+  auto &FM = Processed.fileManager();
+
+  EXPECT_THAT(PI.getExporters(FM.getFile("private1.h").get(), FM),
+  testing::UnorderedElementsAre(FileNamed("export1.h"),
+   

[PATCH] D127762: [Clang][AArch64] Add ACLE attributes for SME.

2022-11-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a reviewer: erichkeane.
aaron.ballman added a comment.

Adding Erich as the new attributes code owner.




Comment at: clang/include/clang/Basic/Attr.td:2322
 
+def ArmStreamingCompatible : DeclOrTypeAttr, TargetSpecificAttr 
{
+  let Spellings = [Clang<"arm_streaming_compatible">];

sdesmalen wrote:
> aaron.ballman wrote:
> > sdesmalen wrote:
> > > aaron.ballman wrote:
> > > > sdesmalen wrote:
> > > > > aaron.ballman wrote:
> > > > > > `DeclOrTypeAttr` is only intended to be used for attributes which 
> > > > > > were historically a declaration attribute but are semantically type 
> > > > > > attributes (like calling conventions). It seems to me that each of 
> > > > > > these is purely a type attribute and we shouldn't allow them to be 
> > > > > > written in the declaration position. WDYT?
> > > > > In this case, I believe the attribute is valid on both the type and 
> > > > > the declaration, because the SME ACLE explicitly specifies that the 
> > > > > attributes can be applied to both declarations and types.
> > > > > 
> > > > > The 
> > > > > [[https://github.com/ARM-software/acle/pull/188/commits/ce878cf6c43fd824ffc634526e5dfec1ddc1839e#diff-516526d4a18101dc85300bc2033d0f86dc46c505b7510a7694baabea851aedfaR8283-R8294|specification]]
> > > > >  says:
> > > > > ```Some of the attributes described in this section apply to function 
> > > > > types.
> > > > > Their semantics are as follows:
> > > > > 
> > > > > *   If the attribute is attached to a function declaration or 
> > > > > definition,
> > > > > it applies to the type of the function.
> > > > > 
> > > > > *   If the attribute is attached to a function type, it applies to 
> > > > > that type.
> > > > > 
> > > > > *   If the attribute is attached to a pointer to a function type, it 
> > > > > applies
> > > > > to that function type.
> > > > > 
> > > > > *   Otherwise, the attribute is [ill-formed](#ill-formed).```
> > > > > In this case, I believe the attribute is valid on both the type and 
> > > > > the declaration, because the SME ACLE explicitly specifies that the 
> > > > > attributes can be applied to both declarations and types.
> > > > 
> > > > What are the chances that can change? Because there are problems here:
> > > > 
> > > > > If the attribute is attached to a function declaration or definition, 
> > > > > it applies to the type of the function.
> > > > 
> > > > This is egregiously opposed to the design of `[[]]` attributes in both 
> > > > C and C++. We came up with `DeclOrTypeAttr` for attributes that 
> > > > previously existed, but that is different than introducing new 
> > > > attributes. It's par for the course for `__attribute__` style 
> > > > attributes, so I don't worry so much there.
> > > > 
> > > > What's the rationale for this confusing of a design? (e.g., is there 
> > > > some reason you basically have to do that, like historically accepting 
> > > > the attributes in both positions?)
> > > The attribute must always apply to the type of the function, because we 
> > > can't have the streaming-property (or the properties on ZA) being lost 
> > > between function overrides or function pointer assignments. It's perhaps 
> > > similar to a calling convention, because the caller may have to set up 
> > > streaming- or ZA state before the call, and restore state after the call.
> > > 
> > > I'm not too familiar with the different spellings/syntaxes and their 
> > > implications, so I've now limited the attribute to `GNU` style attributes 
> > > (`__attribute__((..))`) and to being a `TypeAttr`, with the exception of 
> > > the `arm_locally_streaming` attribute, because that one can only be 
> > > applied to function definitions and is not part of the type.
> > > 
> > > I've also added some new tests to ensure the properties are correctly 
> > > propagated (using `decltype()`) and tests to ensure virtual function 
> > > overloads require the same attributes.
> > > 
> > > Is this a step in the right direction? :)
> > Switching to a GNU-only spelling sort of helps, but I still think this 
> > design is confused.
> > ```
> > *  If the attribute is attached to a function declaration or definition,
> > it applies to the type of the function.
> > ```
> > This seems like a misdesigned feature and I think it should be fixed in the 
> > specification. If it's an attribute that applies to the type of the 
> > function, you should not be allowed to specify it on the declaration; what 
> > is the benefit to allowing it in an unexpected position?
> > If it's an attribute that applies to the type of the function, you should 
> > not be allowed to specify it on the declaration
> Could you maybe give me an example here of what it looks like to apply the 
> attribute to the function *type* when it's not allowed on the *declaration*? 
> Does this all have to do with the //position// of the attribute in the 
> declaration statement? When writing a function declaration it define

[clang] c3821b8 - [flang] Add -fpass-plugin option to flang

2022-11-10 Thread Tarun Prabhu via cfe-commits

Author: Tarun Prabhu
Date: 2022-11-10T08:03:46-07:00
New Revision: c3821b8d2aacd1d7c0281db1b8db011e1158cf4d

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

LOG: [flang] Add -fpass-plugin option to flang

This patch adds the -fpass-plugin option to flang which dynamically loads LLVM
passes from the shared object passed as the argument to the flag. The behavior
of the option is designed to replicate that of the same option in clang and
thus has the same capabilities and limitations.

Features:

  Multiple instances of -fpass-plugin=path-to-file can be specified and each
  of the files will be loaded in that order.

  The flag can be passed to both flang-new and flang-new -fc1.

  The flag will be listed when the -help flag is passed to both flang-new and
  flang-new -fc1. It will also be listed when the --help-hidden flag is passed.

Limitations:

  Dynamically loaded plugins are not supported in clang on Windows and are not
  supported in flang either.

Addenda:

  Some minor stylistic changes are made in the files that were modified to
  enable this functionality. Those changes make the naming of functions more
  consistent, but do not change any functionality that is not directly
  related to enabling -fpass-plugin.

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

Added: 
flang/test/Driver/pass-plugin-not-found.f90
flang/test/Driver/pass-plugin.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
clang/lib/Driver/ToolChains/Flang.h
flang/docs/FlangDriver.md
flang/docs/ReleaseNotes.md
flang/include/flang/Frontend/CodeGenOptions.h
flang/lib/Frontend/CompilerInvocation.cpp
flang/lib/Frontend/FrontendActions.cpp
flang/test/CMakeLists.txt
flang/test/Driver/driver-help-hidden.f90
flang/test/Driver/driver-help.f90
flang/test/Driver/frontend-forwarding.f90

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index debe038196c06..a501306632afb 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2719,7 +2719,7 @@ def fplugin_arg : Joined<["-"], "fplugin-arg-">,
   MetaVarName<"-">,
   HelpText<"Pass  to plugin ">;
 def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
-  Group, Flags<[CC1Option]>, MetaVarName<"">,
+  Group, Flags<[CC1Option,FlangOption,FC1Option]>, 
MetaVarName<"">,
   HelpText<"Load pass plugin from a dynamic shared object file (only with new 
pass manager).">,
   MarshallingInfoStringVector>;
 defm preserve_as_comments : BoolFOption<"preserve-as-comments",

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index c9016238ee65e..588fabd560009 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -51,15 +51,15 @@ void Flang::addPreprocessingOptions(const ArgList &Args,
options::OPT_I, options::OPT_cpp, options::OPT_nocpp});
 }
 
-void Flang::forwardOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
+void Flang::addOtherOptions(const ArgList &Args, ArgStringList &CmdArgs) const 
{
   Args.AddAllArgs(CmdArgs,
   {options::OPT_module_dir, options::OPT_fdebug_module_writer,
options::OPT_fintrinsic_modules_path, options::OPT_pedantic,
options::OPT_std_EQ, options::OPT_W_Joined,
-   options::OPT_fconvert_EQ});
+   options::OPT_fconvert_EQ, options::OPT_fpass_plugin_EQ});
 }
 
-void Flang::AddPicOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
+void Flang::addPicOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
   // ParsePICArgs parses -fPIC/-fPIE and their variants and returns a tuple of
   // (RelocationModel, PICLevel, IsPIE).
   llvm::Reloc::Model RelocationModel;
@@ -238,13 +238,13 @@ void Flang::ConstructJob(Compilation &C, const JobAction 
&JA,
 CmdArgs.push_back("-fcolor-diagnostics");
 
   // -fPIC and related options.
-  AddPicOptions(Args, CmdArgs);
+  addPicOptions(Args, CmdArgs);
 
   // Floating point related options
   addFloatingPointOptions(D, Args, CmdArgs);
 
-  // Handle options which are simply forwarded to -fc1.
-  forwardOptions(Args, CmdArgs);
+  // Add other compile options
+  addOtherOptions(Args, CmdArgs);
 
   // Forward -Xflang arguments to -fc1
   Args.AddAllArgValues(CmdArgs, options::OPT_Xflang);

diff  --git a/clang/lib/Driver/ToolChains/Flang.h 
b/clang/lib/Driver/ToolChains/Flang.h
index 4d8e2e8ee5aa9..de72ac3601f96 100644
--- a/clang/lib/Driver/ToolChains/Flang.h
+++ b/clang/lib/Driver/ToolChains/Flang.h
@@ -45,15 +45,16 @@ class LLVM_LIBRARY_VISIBILITY Flang : public Tool {
   ///
   /// \param [in] Args The list of 

[PATCH] D137751: Produce a more informative diagnostics when Clang runs out of source locations

2022-11-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thank you for working on this, I think this will help folks who run out of 
source locations. Can you also add a release note and public docs for this 
extension?




Comment at: clang/include/clang/Basic/SourceManager.h:1695-1696
+  // Produce notes describing the current source location address space usage.
+  void noteSLocAddressSpaceUsage(DiagnosticsEngine &Diag,
+ unsigned MaxNotes = 50) const;
+

Not that I'm opposed, but how did you arrive at 50?



Comment at: clang/lib/Basic/SourceManager.cpp:675
   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
+  // TODO: Produce a proper diagnostic for this case.
   assert(NextLocalOffset + Length + 1 > NextLocalOffset &&

Are you planning to do this as part of this patch, or is this more of an 
aspirational FIXME for the future?



Comment at: clang/lib/Basic/SourceManager.cpp:2281-2282
+  SortedUsage.reserve(Usage.size());
+  for (auto It = Usage.begin(); It != Usage.end(); ++It)
+SortedUsage.push_back(It);
+  auto Cmp = [](UsageMap::iterator A, UsageMap::iterator B) {

llvm::copy?



Comment at: clang/lib/Lex/Pragma.cpp:1187
+  // specifically report information about.
+  uint64_t MaxNotes = (uint64_t)-1;
+  Token ArgToken;

`~0ULL`?



Comment at: clang/lib/Lex/Pragma.cpp:1190-1195
+  if (ArgToken.isNot(tok::eod)) {
+if (ArgToken.isNot(tok::numeric_constant) ||
+!PP.parseSimpleIntegerLiteral(ArgToken, MaxNotes)) {
+  PP.Diag(ArgToken, diag::warn_pragma_debug_unexpected_argument);
+}
+  }

These predicates can be combined into one `if` statement.



Comment at: clang/test/Misc/sloc-usage.cpp:1
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+

Should we do anything special about source locations from the command line, or 
do those not contribute source locations? (e.g., `-D` or `-U`, force include 
file, etc flags)

(Testing a forced include would be interesting regardless, just to ensure we 
catch those the same as we do an `#include`.)


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

https://reviews.llvm.org/D137751

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


[PATCH] D137787: [CodeGen] Relax assertion on generating destructor call

2022-11-10 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld created this revision.
Hahnfeld added reviewers: v.g.vassilev, mantognini, ChuanqiXu, Bigcheese.
Herald added a project: All.
Hahnfeld requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

If the `Decl` pointers are not identical, `declaresSameEntity` will check the 
canonical `Decls`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137787

Files:
  clang/lib/CodeGen/CGExprCXX.cpp


Index: clang/lib/CodeGen/CGExprCXX.cpp
===
--- clang/lib/CodeGen/CGExprCXX.cpp
+++ clang/lib/CodeGen/CGExprCXX.cpp
@@ -97,8 +97,9 @@
   const CXXMethodDecl *DtorDecl = cast(Dtor.getDecl());
 
   assert(!ThisTy.isNull());
-  assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
- "Pointer/Object mixup");
+  assert(
+  declaresSameEntity(ThisTy->getAsCXXRecordDecl(), DtorDecl->getParent()) 
&&
+  "Pointer/Object mixup");
 
   LangAS SrcAS = ThisTy.getAddressSpace();
   LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();


Index: clang/lib/CodeGen/CGExprCXX.cpp
===
--- clang/lib/CodeGen/CGExprCXX.cpp
+++ clang/lib/CodeGen/CGExprCXX.cpp
@@ -97,8 +97,9 @@
   const CXXMethodDecl *DtorDecl = cast(Dtor.getDecl());
 
   assert(!ThisTy.isNull());
-  assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
- "Pointer/Object mixup");
+  assert(
+  declaresSameEntity(ThisTy->getAsCXXRecordDecl(), DtorDecl->getParent()) &&
+  "Pointer/Object mixup");
 
   LangAS SrcAS = ThisTy.getAddressSpace();
   LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137782: [clang-tidy]bugprone-fold-init-type

2022-11-10 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp:205
 }
+

Excessive newline.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137782

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


[PATCH] D137697: Move the isSelfContained function from clangd to libtooling.

2022-11-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang/include/clang/Tooling/Inclusions/Header.h:1
+//===--- Header.h *- 
C++-*-===//
+//

rather than calling this `Header` can we call this `HeaderAnalysis`?



Comment at: clang/include/clang/Tooling/Inclusions/Header.h:21
+///
+/// A header is considered self-contained if either it has a proper header 
guard
+/// or it doesn't has dont-include-me-similar pattern.

let's mention being `#import`d as well



Comment at: clang/lib/Tooling/Inclusions/Header.cpp:64
+  // particular preprocessor state, usually set up by another header.
+  return !isDontIncludeMeHeader(SM.getBufferData(SM.translateFile(FE)));
+}

`translateFile` actually does a linear scan over all the slocentries, so i 
think it's better for this API to be based on FileID. (later on we can easily 
get fileentry from fileid in constant time)



Comment at: clang/unittests/Tooling/HeaderTest.cpp:21
+  Inputs.Code = R"cpp(
+  #include "headerguard.h"
+  #include "pragmaonce.h"

can you also add a test case for `#import` ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137697

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


[PATCH] D137787: [CodeGen] Relax assertion on generating destructor call

2022-11-10 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

This fixes the assertion for a downstream case in ROOT/Cling with the 
involvement of modules. If anyone has ideas how to test this, please let me 
know...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137787

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


[PATCH] D137340: [clang-tidy] Add misc-use-anonymous-namespace check

2022-11-10 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

@njames93 Friendly ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137340

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


[PATCH] D137782: [clang-tidy]bugprone-fold-init-type

2022-11-10 Thread Clement Courbet via Phabricator via cfe-commits
courbet updated this revision to Diff 474548.
courbet added a comment.

remove extra training newline


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137782

Files:
  clang-tools-extra/clang-tidy/bugprone/FoldInitTypeCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/fold-init-type.cpp
@@ -1,39 +1,67 @@
-// RUN: %check_clang_tidy %s bugprone-fold-init-type %t
+// RUN: %check_clang_tidy %s bugprone-fold-init-type -std=c++17 %t
 
 namespace std {
 template 
-T accumulate(InputIt first, InputIt last, T init);
+T accumulate(InputIt first, InputIt last, T init) {
+  // When `InputIt::operator*` returns a deduced `auto` type that refers to a
+  // dependent type, the return type is deduced only if `InputIt::operator*`
+  // is instantiated. In practice this happens somewhere in the implementation
+  // of `accumulate`. For tests, do it here.
+  (void)*first;
+}
 
 template 
-T reduce(InputIt first, InputIt last, T init);
+T reduce(InputIt first, InputIt last, T init) { (void)*first; }
 template 
 T reduce(ExecutionPolicy &&policy,
- InputIt first, InputIt last, T init);
+ InputIt first, InputIt last, T init) { (void)*first; }
 
 struct parallel_execution_policy {};
 constexpr parallel_execution_policy par{};
 
 template 
 T inner_product(InputIt1 first1, InputIt1 last1,
-InputIt2 first2, T value);
+InputIt2 first2, T value) { (void)*first1; (void)*first2; }
 
 template 
 T inner_product(ExecutionPolicy &&policy, InputIt1 first1, InputIt1 last1,
-InputIt2 first2, T value);
+InputIt2 first2, T value) { (void)*first1; (void)*first2; }
 
 } // namespace std
 
 struct FloatIterator {
-  typedef float value_type;
+  const float &operator*() const;
 };
+
+struct DerivedFloatIterator : public FloatIterator {
+};
+
+template  struct ByValueTemplateIterator {
+  ValueType operator*() const;
+};
+
+template  struct ByRefTemplateIterator {
+  ValueType &operator*();
+};
+
+template  struct ByRefTemplateIteratorWithAlias {
+  using reference = const ValueType&;
+  reference operator*();
+};
+
+template  struct AutoByValueTemplateIterator {
+  auto operator*() const { return ValueType{}; }
+};
+
+template  struct AutoByRefTemplateIterator {
+  decltype(auto) operator*() const { return value_; }
+  ValueType value_;
+};
+
 template 
-struct TypedefTemplateIterator { typedef ValueType value_type; };
-template 
-struct UsingTemplateIterator { using value_type = ValueType; };
-template 
-struct DependentTypedefTemplateIterator { typedef typename ValueType::value_type value_type; };
-template 
-struct DependentUsingTemplateIterator : public TypedefTemplateIterator { using typename TypedefTemplateIterator::value_type; };
+struct InheritingByConstRefTemplateIterator
+: public ByRefTemplateIterator {};
+
 using TypedeffedIterator = FloatIterator;
 
 // Positives.
@@ -51,39 +79,57 @@
 }
 
 int accumulatePositive3() {
+  DerivedFloatIterator it;
+  return std::accumulate(it, it, 0);
+  // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'float' into type 'int'
+}
+
+int accumulatePositive4() {
   double a[1] = {0.0};
   return std::accumulate(a, a + 1, 0.0f);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'double' into type 'float'
 }
 
-int accumulatePositive4() {
-  TypedefTemplateIterator it;
+int accumulatePositive5() {
+  ByValueTemplateIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
 }
 
-int accumulatePositive5() {
-  UsingTemplateIterator it;
+int accumulatePositive6() {
+  ByRefTemplateIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
 }
 
-int accumulatePositive6() {
-  DependentTypedefTemplateIterator> it;
+int accumulatePositive7() {
+  AutoByValueTemplateIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
 }
 
-int accumulatePositive7() {
+int accumulatePositive8() {
   TypedeffedIterator it;
   return std::accumulate(it, it, 0);
   // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'float' into type 'int'
 }
 
-int accumulatePositive8() {
-  DependentUsingTemplateIterator it;
+int accumulatePositive9() {
+  InheritingByConstRefTemplateIterator it;
+  return std::accumulate(it, it, 0);
+  // CHECK-MESSAGES: [[@LINE-1]]:10: warning: folding type 'unsigned int' into type 'int'
+}
+
+int accumulatePositive10() {
+  AutoByRefTemplateIterator it;
   return std::a

[PATCH] D137698: [include-cleaner] Add self-contained file support for PragmaIncludes.

2022-11-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

i guess this patch needs a rebase for other pieces as well? but LG in general




Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:47
+ const PragmaIncludes &PI) {
+  const FileEntry *FE = SM.getFileEntryForID(FID);
+  for (; FID != SM.getMainFileID(); FE = SM.getFileEntryForID(FID)) {

with the API i suggested in the base revision this should look like:
```
while(FID != SM.getMainFileID() && !PI.isSelfContained(FID))
  FID = SM.getFileID(SM.getIncludeLoc(FID));
return SM.getFileEntryForID(FID);
```

i think feels more natural



Comment at: clang-tools-extra/include-cleaner/lib/Record.cpp:53
+  Out->NonSelfContainedFiles.erase(
+  SM.getFileEntryForID(PrevFID)->getUniqueID());
+else

`FE->getUniqueID()`, same below



Comment at: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp:149
+  Inputs.ExtraFiles["detail2.h"] = guard("");
+  Inputs.ExtraFiles["imp.inc"] = "";
   TestAST AST(Inputs);

nit: rather than introducing a 3rd header, i'd just include it in `header2.h`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137698

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


[PATCH] D134859: [clang][Interp] Implement basic support for floating point values

2022-11-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 474551.

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

https://reviews.llvm.org/D134859

Files:
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Floating.cpp
  clang/lib/AST/Interp/Floating.h
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpStack.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/PrimType.h
  clang/lib/AST/Interp/Primitives.h
  clang/test/AST/Interp/const-fpfeatures.cpp
  clang/test/AST/Interp/floats.cpp
  clang/test/SemaCXX/rounding-math.cpp

Index: clang/test/SemaCXX/rounding-math.cpp
===
--- clang/test/SemaCXX/rounding-math.cpp
+++ clang/test/SemaCXX/rounding-math.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-linux -verify=norounding -Wno-unknown-pragmas %s
 // RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -Wno-unknown-pragmas
+// RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -fexperimental-new-constant-interpreter -Wno-unknown-pragmas
 // rounding-no-diagnostics
 
 #define fold(x) (__builtin_constant_p(x) ? (x) : (x))
Index: clang/test/AST/Interp/floats.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/floats.cpp
@@ -0,0 +1,50 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+constexpr int i = 2;
+constexpr float f = 1.0f;
+static_assert(f == 1.0f, "");
+
+constexpr float f2 = 1u * f;
+static_assert(f2 == 1.0f, "");
+
+constexpr float f3 = 1.5;
+constexpr int i3 = f3;
+static_assert(i3 == 1);
+
+constexpr bool b3 = f3;
+static_assert(b3);
+
+
+static_assert(1.0f + 3u == 4, "");
+static_assert(4.0f / 1.0f == 4, "");
+static_assert(10.0f * false == 0, "");
+
+constexpr float floats[] = {1.0f, 2.0f, 3.0f, 4.0f};
+
+constexpr float m = 5.0f / 0.0f; // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{division by zero}} \
+ // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{division by zero}}
+
+static_assert(~2.0f == 3, ""); // ref-error {{invalid argument type 'float' to unary expression}} \
+   // expected-error {{invalid argument type 'float' to unary expression}}
+
+/// Initialized by a double.
+constexpr float df = 0.0;
+/// The other way around.
+constexpr double fd = 0.0f;
+
+static_assert(0.0f == -0.0f, "");
+
+const int k = 3 * (1.0f / 3.0f);
+static_assert(k == 1, "");
+
+constexpr bool b = 1.0;
+static_assert(b, "");
+
+constexpr double db = true;
+static_assert(db == 1.0, "");
+
+constexpr float fa[] = {1.0f, 2.0, 1, false};
+constexpr float da[] = {1.0f, 2.0, 1, false};
Index: clang/test/AST/Interp/const-fpfeatures.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/const-fpfeatures.cpp
@@ -0,0 +1,65 @@
+// RUN: %clang_cc1 -S -emit-llvm -triple i386-linux -std=c++2a -Wno-unknown-pragmas %s -o - | FileCheck %s
+// RUN: %clang_cc1 -S -emit-llvm -triple i386-linux -fexperimental-new-constant-interpreter -std=c++2a -Wno-unknown-pragmas %s -o - | FileCheck %s
+
+
+#pragma STDC FENV_ROUND FE_UPWARD
+
+float F1u = 1.0F + 0x0.02p0F;
+float F2u = 1.0F + 0x0.01p0F;
+float F3u = 0x1.01p0;
+// CHECK: @F1u = {{.*}} float 0x3FF02000
+// CHECK: @F2u = {{.*}} float 0x3FF02000
+// CHECK: @F3u = {{.*}} float 0x3FF02000
+
+#pragma STDC FENV_ROUND FE_DOWNWARD
+
+float F1d = 1.0F + 0x0.02p0F;
+float F2d = 1.0F + 0x0.01p0F;
+float F3d = 0x1.01p0;
+
+// CHECK: @F1d = {{.*}} float 0x3FF02000
+// CHECK: @F2d = {{.*}} float 1.00e+00
+// CHECK: @F3d = {{.*}} float 1.00e+00
+
+// nextUp(1.F) == 0x1.02p0F
+
+constexpr float add_round_down(float x, float y) {
+  #pragma STDC FENV_ROUND FE_DOWNWARD
+  float res = x;
+  res += y;
+  return res;
+}
+
+constexpr float add_round_up(float x, float y) {
+  #pragma STDC FENV_ROUND FE_UPWARD
+  float res = x;
+  res += y;
+  return res;
+}
+
+float V1 = add_round_down(1.0F, 0x0.01p0F);
+float V2 = add_round_up(1.0F, 0x0.01p0F);
+// CHECK: @V1 = {{.*}} float 1.00e+00
+// CHECK: @V2 = {{.*}} float 0x3FF02000
+
+constexpr float add_cast_round_down(float x, double y) {
+  #pragma STDC FENV_ROUND FE_DOWNWARD
+  float res = x;
+  res += y;
+  return res;
+}
+
+constexpr float add_cast_round_up(float x, double y) {
+  #pragma STDC FENV_ROUND FE_UPWARD
+  float res = x;
+  res += y;
+  return res;
+}
+
+float V3 = add_cast_round_down(1.0F, 0x0.01p0F);
+flo

[PATCH] D135247: [clang][analyzer] Add stream functions to StdLibraryFunctionsChecker.

2022-11-10 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 474556.
balazske added a comment.

Rebase to main and D137722 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135247

Files:
  clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/Inputs/system-header-simulator.h
  clang/test/Analysis/std-c-library-functions-POSIX.c
  clang/test/Analysis/std-c-library-functions-vs-stream-checker.c
  clang/test/Analysis/stream-errno-note.c
  clang/test/Analysis/stream-errno.c
  clang/test/Analysis/stream-noopen.c

Index: clang/test/Analysis/stream-noopen.c
===
--- /dev/null
+++ clang/test/Analysis/stream-noopen.c
@@ -0,0 +1,97 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-checker=alpha.unix.Stream \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+// enable only StdCLibraryFunctions checker
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+#include "Inputs/system-header-simulator.h"
+#include "Inputs/errno_var.h"
+
+void clang_analyzer_eval(int);
+
+const char *WBuf = "123456789";
+char RBuf[10];
+
+void test_freopen(FILE *F) {
+  F = freopen("xxx", "w", F);
+  if (F) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+}
+
+void test_fread(FILE *F) {
+  size_t Ret = fread(RBuf, 1, 10, F);
+  if (Ret == 10) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void test_fwrite(FILE *F) {
+  size_t Ret = fwrite(WBuf, 1, 10, F);
+  if (Ret == 10) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void test_fclose(FILE *F) {
+  int Ret = fclose(F);
+  if (Ret == 0) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(Ret == EOF); // expected-warning {{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void test_fseek(FILE *F) {
+  int Ret = fseek(F, SEEK_SET, 1);
+  if (Ret == 0) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(Ret == -1); // expected-warning {{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void freadwrite_zerosize(FILE *F) {
+  fwrite(WBuf, 1, 0, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+  fwrite(WBuf, 0, 1, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+  fread(RBuf, 1, 0, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+  fread(RBuf, 0, 1, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+}
Index: clang/test/Analysis/stream-errno.c
===
--- /dev/null
+++ clang/test/Analysis/stream-errno.c
@@ -0,0 +1,138 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.Stream,alpha.unix.Errno,apiModeling.StdCLibraryFunctions,debug.ExprInspection \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true -verify %s
+
+#include "Inputs/system-header-simulator.h"
+#include "Inputs/errno_func.h"
+
+exte

[PATCH] D135360: [clang][analyzer] Add some more functions to StreamChecker and StdLibraryFunctionsChecker.

2022-11-10 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 474558.
balazske added a comment.

Rebase to main and D137722 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135360

Files:
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/stream-errno-note.c
  clang/test/Analysis/stream-errno.c
  clang/test/Analysis/stream-noopen.c

Index: clang/test/Analysis/stream-noopen.c
===
--- clang/test/Analysis/stream-noopen.c
+++ clang/test/Analysis/stream-noopen.c
@@ -77,6 +77,49 @@
   clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
 }
 
+void check_fgetpos(FILE *F) {
+  errno = 0;
+  fpos_t Pos;
+  int Ret = fgetpos(F, &Pos);
+  if (Ret)
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+  else
+clang_analyzer_eval(errno == 0); // expected-warning{{TRUE}}
+ // expected-warning@-1{{FALSE}}
+  if (errno) {} // no-warning
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void check_fsetpos(FILE *F) {
+  errno = 0;
+  fpos_t Pos;
+  int Ret = fsetpos(F, &Pos);
+  if (Ret)
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+  else
+clang_analyzer_eval(errno == 0); // expected-warning{{TRUE}}
+ // expected-warning@-1{{FALSE}}
+  if (errno) {} // no-warning
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void check_ftell(FILE *F) {
+  errno = 0;
+  long Ret = ftell(F);
+  if (Ret == -1) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+  } else {
+clang_analyzer_eval(errno == 0); // expected-warning{{TRUE}}
+ // expected-warning@-1{{FALSE}}
+clang_analyzer_eval(Ret >= 0); // expected-warning{{TRUE}}
+  }
+  if (errno) {} // no-warning
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
 void freadwrite_zerosize(FILE *F) {
   fwrite(WBuf, 1, 0, F);
   clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
Index: clang/test/Analysis/stream-errno.c
===
--- clang/test/Analysis/stream-errno.c
+++ clang/test/Analysis/stream-errno.c
@@ -123,6 +123,64 @@
   fclose(F);
 }
 
+void check_fgetpos(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  errno = 0;
+  fpos_t Pos;
+  int Ret = fgetpos(F, &Pos);
+  if (Ret)
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+  else
+clang_analyzer_eval(errno == 0); // expected-warning{{TRUE}}
+  if (errno) {} // no-warning
+  fclose(F);
+}
+
+void check_fsetpos(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  errno = 0;
+  fpos_t Pos;
+  int Ret = fsetpos(F, &Pos);
+  if (Ret)
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+  else
+clang_analyzer_eval(errno == 0); // expected-warning{{TRUE}}
+  if (errno) {} // no-warning
+  fclose(F);
+}
+
+void check_ftell(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  errno = 0;
+  long Ret = ftell(F);
+  if (Ret == -1) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+  } else {
+clang_analyzer_eval(errno == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(Ret >= 0); // expected-warning{{TRUE}}
+  }
+  if (errno) {} // no-warning
+  fclose(F);
+}
+
+void check_rewind(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  errno = 0;
+  rewind(F);
+  clang_analyzer_eval(errno == 0);
+  // expected-warning@-1{{FALSE}}
+  // expected-warning@-2{{TRUE}}
+  fclose(F);
+}
+
 void check_fileno(void) {
   FILE *F = tmpfile();
   if (!F)
Index: clang/test/Analysis/stream-errno-note.c
===
--- clang/test/Analysis/stream-errno-note.c
+++ clang/test/Analysis/stream-errno-note.c
@@ -98,6 +98,18 @@
   (void)fclose(F);
 }
 
+void check_rewind_errnocheck(void) {
+  FILE *F = tmpfile();
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F)
+return;
+  errno = 0;
+  rewind(F); // expected-note{{Function 'rewind' indicates failure only by setting of 'errno'}}
+  fclose(F); // expected-warning{{Value of 'errno' was not checked and may be overwritten by function 'fclose' [alpha.unix.Errno]}}
+  // expected-note@-1{{Value of 'errno' was not checked and may be overwritten by function 'fclose'}}
+}
+
 void check_fileno(void) {
   FILE *F = tmpfile();
   // expected-note@+2{{'F' is non-null}}
Inde

[PATCH] D137790: [clang][analyzer] Remove report of null stream from StreamChecker.

2022-11-10 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: steakhal, manas, ASDenysPetrov, martong, gamesh411, 
dkrupp, donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, 
baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a reviewer: NoQ.
Herald added a project: All.
balazske requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The case of NULL stream passed to stream functions was reported by 
StreamChecker.
The same condition is checked already by StdLibraryFunctionsChecker and it is
enough to check at one place. The StreamChecker stops now analysis if a passed 
NULL
stream is encountered but generates no report.
This change removes a dependency between StdCLibraryFunctionArgs checker and
StreamChecker. There is now no more specific message reported by StreamChecker,
the previous weak-dependency is not needed. And StreamChecker can be used
without StdCLibraryFunctions checker or its ModelPOSIX option.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137790

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
  clang/test/Analysis/std-c-library-functions-arg-weakdeps.c
  clang/test/Analysis/stream-noopen.c
  clang/test/Analysis/stream-note.c
  clang/test/Analysis/stream-stdlibraryfunctionargs.c
  clang/test/Analysis/stream.c

Index: clang/test/Analysis/stream.c
===
--- clang/test/Analysis/stream.c
+++ clang/test/Analysis/stream.c
@@ -2,81 +2,6 @@
 
 #include "Inputs/system-header-simulator.h"
 
-void check_fread(void) {
-  FILE *fp = tmpfile();
-  fread(0, 0, 0, fp); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_fwrite(void) {
-  FILE *fp = tmpfile();
-  fwrite(0, 0, 0, fp); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_fseek(void) {
-  FILE *fp = tmpfile();
-  fseek(fp, 0, 0); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_ftell(void) {
-  FILE *fp = tmpfile();
-  ftell(fp); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_rewind(void) {
-  FILE *fp = tmpfile();
-  rewind(fp); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_fgetpos(void) {
-  FILE *fp = tmpfile();
-  fpos_t pos;
-  fgetpos(fp, &pos); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_fsetpos(void) {
-  FILE *fp = tmpfile();
-  fpos_t pos;
-  fsetpos(fp, &pos); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_clearerr(void) {
-  FILE *fp = tmpfile();
-  clearerr(fp); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_feof(void) {
-  FILE *fp = tmpfile();
-  feof(fp); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_ferror(void) {
-  FILE *fp = tmpfile();
-  ferror(fp); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void check_fileno(void) {
-  FILE *fp = tmpfile();
-  fileno(fp); // expected-warning {{Stream pointer might be NULL}}
-  fclose(fp);
-}
-
-void f_open(void) {
-  FILE *p = fopen("foo", "r");
-  char buf[1024];
-  fread(buf, 1, 1, p); // expected-warning {{Stream pointer might be NULL}}
-  fclose(p);
-}
-
 void f_seek(void) {
   FILE *p = fopen("foo", "r");
   if (!p)
@@ -161,7 +86,7 @@
 }
 
 void check_freopen_1(void) {
-  FILE *f1 = freopen("foo.c", "r", (FILE *)0); // expected-warning {{Stream pointer might be NULL}}
+  FILE *f1 = freopen("foo.c", "r", (FILE *)0); // Not reported by the stream checker.
   f1 = freopen(0, "w", (FILE *)0x123456);  // Do not report this as error.
 }
 
Index: clang/test/Analysis/stream-stdlibraryfunctionargs.c
===
--- /dev/null
+++ clang/test/Analysis/stream-stdlibraryfunctionargs.c
@@ -0,0 +1,142 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.Stream,alpha.unix.StdCLibraryFunctionArgs,debug.ExprInspection \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true -verify=stdargs,any %s
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.Stream,debug.ExprInspection \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true -verify=any %s
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.StdCLibraryFunctionArgs,debug.ExprInspection \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true -verify=stdargs,any %s
+
+#include "Inputs/system-header-simulator.h"
+
+extern void clang_analyzer_eval(int);
+
+void *buf;
+size_t size;
+size_t n;
+
+void test_fopen(void) {
+  FILE *fp = fopen("path", "r");
+  clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}} any-warning{{FALSE}}
+

[PATCH] D135750: [clang][Interp] Track initialization state of local variables

2022-11-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Ping. This review has been open for a month now and a lot of following 
functionality depends on it, so if you need to decide which one of the patches 
to review, choose this one :)


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

https://reviews.llvm.org/D135750

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


[PATCH] D137714: Do not merge traps in functions annotated optnone

2022-11-10 Thread Félix Cloutier via Phabricator via cfe-commits
fcloutier requested changes to this revision.
fcloutier added inline comments.
This revision now requires changes to proceed.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:5321
 
+  SetLLVMFunctionAttributesForDefinition(D, Fn);
   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);

hnrklssn wrote:
> delcypher wrote:
> > I'm a little worried about this ordering change here. Could this have some 
> > unintended consequences?
> Yeah I was also a bit worried about that when making the change, since the 
> functions are both quite broad and I'm not familiar with them from before. 
> However it doesn't break any test cases, so I'm not sure what the 
> consequences would be exactly.
> 
> For reference, also moving the call to setNonAliasAttributes so that it is 
> still before the call to SetLLVMFunctionAttributesForDefinition breaks a ton 
> of test cases so I'm somewhat hopeful that we have good test coverage for 
> this type of change.
Could you get it from `CurCodeDecl->hasAttr()` in CGExpr 
instead? Then you wouldn't have to change this.

Caveat: am not sure that `CurCodeDecl` is always set. For instance, do you have 
a `CurCodeDecl` when you generate a C++ static initializer? On the upside, if 
it's NULL, you can just bail out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137714

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


[PATCH] D137790: [clang][analyzer] Remove report of null stream from StreamChecker.

2022-11-10 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Test file //std-c-library-functions-vs-stream-checker.c// could be removed. It 
tests the same as the newly added //stream-stdlibraryfunctionargs.c//.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137790

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


How can Autoconf help with the transition to stricter compilation defaults?

2022-11-10 Thread Zack Weinberg via cfe-commits
I’m the closest thing Autoconf has to a lead maintainer at present.

It’s come to my attention (via https://lwn.net/Articles/913505/ and
https://fedoraproject.org/wiki/Changes/PortingToModernC) that GCC and
Clang both plan to disable several “legacy” C language features by
default in a near-future release (GCC 14, Clang 16) (see the Fedora
wiki link for a list).  I understand that this change potentially
breaks a lot of old dusty code, and in particular that
Autoconf-generated configure scripts use constructs that may *silently
give the wrong answer to a probe* when a stricter compiler is in use.

Nobody has a whole lot of time to work on Autoconf at present, but I
would like to ask, anyway, what Autoconf could potentially do to make
this transition easier.  I’m already aware that the test code Autoconf
2.71 uses to probe for C89/C99/C11 support is broken; this has been
fixed in development trunk to the extent it is possible for me to test
it with GCC 12 (commit:
).
Several other places using K&R function definitions and/or
unprototyped function declarations (including the ubiquitously used
AC_CHECK_FUNC) have also been fixed on trunk,
.
Changes to handle C23 built-in ‘bool’ better are under development but
the design has not yet been finalized.

The biggest remaining (potential) problem, that I’m aware of, is that
AC_CHECK_FUNC unconditionally declares the function we’re probing for
as ‘char NAME (void)’, and asks the compiler to call it with no
arguments, regardless of what its prototype actually is.  It is not
clear to me whether this will still work with the planned changes to
the compilers.  Both GCC 12 and Clang 14 have on-by-default warnings
triggered by ‘extern char memcpy(void);’ (or any other standard
library function whose prototype is coded into the compiler) and this
already causes problems for people who run configure scripts with
CC='cc -Werror'.  Unfortunately this is very hard to fix — we would
have to build a comprehensive list of library functions into Autoconf,
mapping each to either its documented prototype or to a header where
it ought to be declared; in the latter case we would also have to make
e.g. AC_CHECK_FUNCS([getaddrinfo]) imply AC_CHECK_HEADERS([sys/types.h
sys/socket.h netdb.h]) which might mess up configure scripts that
aren’t expecting headers to be probed at that point.

How important do you think it is for this to be fixed?

Are there any other changes you would like to see in a near-future
Autoconf 2.72 in order to make this transition easier?

zw

p.s. GCC and Clang folks: As long as you’re changing the defaults out
from under people, can you please also remove the last few predefined
user-namespace macros (-Dlinux, -Dunix, -Darm, etc) from all the
-std=gnuXX modes?
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D135011: Add builtin_elementwise_sin and builtin_elementwise_cos

2022-11-10 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper added a comment.
This revision is now accepted and ready to land.

LGTM to me with those formatting fixes.




Comment at: clang/test/CodeGen/builtins-elementwise-math.c:337
+void test_builtin_elementwise_cos(float f1, float f2, double d1, double d2,
+  float4 vf1, float4 vf2) {
+  // CHECK-LABEL: define void @test_builtin_elementwise_cos(

Line these up with the start of the arguments on the previous line.



Comment at: clang/test/CodeGen/builtins-elementwise-math.c:385
+void test_builtin_elementwise_sin(float f1, float f2, double d1, double d2,
+  float4 vf1, float4 vf2) {
+  // CHECK-LABEL: define void @test_builtin_elementwise_sin(

Same


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135011

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


[PATCH] D137246: Add clang_CXXMethod_isMoveAssignmentOperator to libclang

2022-11-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

In D137246#3911881 , @diseraluca 
wrote:

> I finally had some time to look into the pre-merge failure. I couldn't 
> replicate it on my machine by following 
> https://buildkite.com/llvm-project/premerge-checks/builds/119952#01843856-e8c7-4709-89c6-d52d0286862a
>  .
>
> Looking at the log it does not seem related to the patch, I think it might be 
> a flaky failing.
> Is there a way to rerun the pre-merge checks?

Yeah, that looks like a flaky test. You can restart CI by clicking the "Restart 
Build" link on the Harbormaster instance, I believe 
(https://reviews.llvm.org/harbormaster/build/296625/). If all else fails, you 
can usually rebase the patch on main and upload the new patch.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137246

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


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-10 Thread Jonathan Wakely via cfe-commits
On Thu, 10 Nov 2022 at 17:52, Nick Bowler wrote:
> It saddens me to see so much breakage happening in "modern C", a
> language that has (until now) a long history of new language features
> being carefully introduced to avoid these sort of problems.

The features were introduced in 1999. Compilers just continued to
accept broken code, because people seem to think accepting garbage
forever is "compatibility".
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-10 Thread Florian Weimer via cfe-commits
* Zack Weinberg via Gcc:

> I’m the closest thing Autoconf has to a lead maintainer at present.
>
> It’s come to my attention (via https://lwn.net/Articles/913505/ and
> https://fedoraproject.org/wiki/Changes/PortingToModernC) that GCC and
> Clang both plan to disable several “legacy” C language features by
> default in a near-future release (GCC 14, Clang 16) (see the Fedora
> wiki link for a list).  I understand that this change potentially
> breaks a lot of old dusty code, and in particular that
> Autoconf-generated configure scripts use constructs that may *silently
> give the wrong answer to a probe* when a stricter compiler is in use.

Thank you for reaching out.  The c-std-porting list isn't even
bootstrapped yet, the Fedora documentation is still in flux, and the
Fedora oversight body just approved working on this in the Fedora
context.  That LWN article caught me a bit off guard.

Anyway, based on a limited attempt to get this fixed about three years
ago, I expect that many of the problematic packages have not had their
configure scripts regenerated using autoconf for a decade or more.  This
means that as an autoconf maintainer, you unfortunately won't be able to
help us much.

> Nobody has a whole lot of time to work on Autoconf at present, but I
> would like to ask, anyway, what Autoconf could potentially do to make
> this transition easier.  I’m already aware that the test code Autoconf
> 2.71 uses to probe for C89/C99/C11 support is broken; this has been
> fixed in development trunk to the extent it is possible for me to test
> it with GCC 12 (commit:
> ).

Thanks, these changes are going to be helpful to get a clean run from
our Fedora tester.

I also noticed some issues in the automake test suite, and I hope
Frederic can have a look at them:

  automake: Port to modern C
  

> Several other places using K&R function definitions and/or
> unprototyped function declarations (including the ubiquitously used
> AC_CHECK_FUNC) have also been fixed on trunk,
> .

One reason I hesitate to recommend wide testing with -Werror=… is that
it is actually impossible to model future GCC behavior with -Werror=…
options today.  I very much doubt that the AC_CHECK_FUNC change [that
is, () → (void)] will ever be required by real GCC.  I'm worried that
some of this -Werror=… testing merely introduces unnecessary churn.
These changes help maintainers who wnat to build their packages with
CC="gcc -Werror=…" or something like that, so I guess they still make
sense for autoconf.  But perhaps not as a general model for everyone
else.

> The biggest remaining (potential) problem, that I’m aware of, is that
> AC_CHECK_FUNC unconditionally declares the function we’re probing for
> as ‘char NAME (void)’, and asks the compiler to call it with no
> arguments, regardless of what its prototype actually is.  It is not
> clear to me whether this will still work with the planned changes to
> the compilers.  Both GCC 12 and Clang 14 have on-by-default warnings
> triggered by ‘extern char memcpy(void);’ (or any other standard
> library function whose prototype is coded into the compiler) and this
> already causes problems for people who run configure scripts with
> CC='cc -Werror'.

I think t his approach is actually the most portable approach, at least
as far as GCC is concerned.  GCC treats a function as a compiler
built-in only if the declared prototype matches its expectations.  I
doubt there are any such functions returning char, which makes this
declaration a good choice.  I do not expect any medium-term changes to
the situation here.  The warning will stay, it will not turn into an
error.

> Unfortunately this is very hard to fix — we would
> have to build a comprehensive list of library functions into Autoconf,
> mapping each to either its documented prototype or to a header where
> it ought to be declared; in the latter case we would also have to make
> e.g. AC_CHECK_FUNCS([getaddrinfo]) imply AC_CHECK_HEADERS([sys/types.h
> sys/socket.h netdb.h]) which might mess up configure scripts that
> aren’t expecting headers to be probed at that point.

Once you include the header, you also need to know function parameters,
otherwise you won't be able to form a valid call.  Python
setuptools/distutils tried to do something along this lines, but I can't
see how it can work, as explained here:

  Unclear how CCompiler.has_function works for functions with parameters
  

The char-returning prototype does not seem so bad in the end.  The
function is actually called and the result returned from main, so it's
even compatible with LTO.

> How important do you think it is for this to be fixed?

In isolation?  Not important at all.  Maybe it wo

Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-10 Thread Jonathan Wakely via cfe-commits
On Thu, 10 Nov 2022 at 17:58, Jonathan Wakely wrote:
>
> On Thu, 10 Nov 2022 at 17:52, Nick Bowler wrote:
> > It saddens me to see so much breakage happening in "modern C", a
> > language that has (until now) a long history of new language features
> > being carefully introduced to avoid these sort of problems.
>
> The features were introduced in 1999.

Well, some of them were. Some more are coming now in C2x but the
problem has existed since C99 it's just that compilers "protected"
most users from having to fix their code at the time. But it's been
more than two decades and it's time to accept that missing prototypes,
implicit conversions between pointers and ints etc are a hazard and
should be diagnosed not ignored for the benefit of people who never
want to fix their questionable code.

> Compilers just continued to
> accept broken code, because people seem to think accepting garbage
> forever is "compatibility".
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128223: [clang] Cached linkage assertion for static locals of static function

2022-11-10 Thread Chris Bowler via Phabricator via cfe-commits
cebowleratibm updated this revision to Diff 473756.
cebowleratibm retitled this revision from "[clang] Linkage computation of 
static locals may require forcing visibility computation" to "[clang] Cached 
linkage assertion for static locals of static function".
cebowleratibm edited the summary of this revision.
This revision is now accepted and ready to land.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128223

Files:
  clang/lib/AST/Decl.cpp
  clang/test/CodeGenCXX/linkage-static-local-crash.cpp


Index: clang/test/CodeGenCXX/linkage-static-local-crash.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/linkage-static-local-crash.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -triple powerpc-ibm-aix 
-mdefault-visibility-export-mapping=explicit -fvisibility-inlines-hidden 
-emit-llvm %s -o - | FileCheck %s
+
+struct C {
+  template  
+  __attribute__((__visibility__("hidden"))) 
+  static int& f() {
+static int g = 42;
+return g;
+  }
+};
+
+template
+void foo(T i) { C::f(); }
+
+void bar() {
+  foo([]{});
+}
+
+// CHECK: @"_ZZN1C1fIZ3barvE3$_0EERivE1g" = internal global i32 42, align 4
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -1368,7 +1368,8 @@
 // is not explicitly attributed as a hidden function,
 // we should not make static local variables in the function hidden.
 LV = getLVForDecl(FD, computation);
-if (isa(D) && useInlineVisibilityHidden(FD) &&
+if (isExternallyVisible(LV.getLinkage()) &&
+isa(D) && useInlineVisibilityHidden(FD) &&
 !LV.isVisibilityExplicit() &&
 !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
   assert(cast(D)->isStaticLocal());


Index: clang/test/CodeGenCXX/linkage-static-local-crash.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/linkage-static-local-crash.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -triple powerpc-ibm-aix -mdefault-visibility-export-mapping=explicit -fvisibility-inlines-hidden -emit-llvm %s -o - | FileCheck %s
+
+struct C {
+  template  
+  __attribute__((__visibility__("hidden"))) 
+  static int& f() {
+static int g = 42;
+return g;
+  }
+};
+
+template
+void foo(T i) { C::f(); }
+
+void bar() {
+  foo([]{});
+}
+
+// CHECK: @"_ZZN1C1fIZ3barvE3$_0EERivE1g" = internal global i32 42, align 4
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -1368,7 +1368,8 @@
 // is not explicitly attributed as a hidden function,
 // we should not make static local variables in the function hidden.
 LV = getLVForDecl(FD, computation);
-if (isa(D) && useInlineVisibilityHidden(FD) &&
+if (isExternallyVisible(LV.getLinkage()) &&
+isa(D) && useInlineVisibilityHidden(FD) &&
 !LV.isVisibilityExplicit() &&
 !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
   assert(cast(D)->isStaticLocal());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D135011: Add builtin_elementwise_sin and builtin_elementwise_cos

2022-11-10 Thread Joshua Batista via Phabricator via cfe-commits
bob80905 updated this revision to Diff 474570.
bob80905 added a comment.

- make format change


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135011

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Builtins.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/aarch64-sve-vector-trig-ops.c
  clang/test/Sema/builtins-elementwise-math.c
  clang/test/Sema/riscv-sve-vector-trig-ops.c
  clang/test/SemaCXX/builtins-elementwise-math.cpp

Index: clang/test/SemaCXX/builtins-elementwise-math.cpp
===
--- clang/test/SemaCXX/builtins-elementwise-math.cpp
+++ clang/test/SemaCXX/builtins-elementwise-math.cpp
@@ -59,3 +59,17 @@
   static_assert(!is_const::value);
   static_assert(!is_const::value);
 }
+
+void test_builtin_elementwise_cos() {
+  const float a = 42.0;
+  float b = 42.3;
+  static_assert(!is_const::value);
+  static_assert(!is_const::value);
+}
+
+void test_builtin_elementwise_sin() {
+  const float a = 42.0;
+  float b = 42.3;
+  static_assert(!is_const::value);
+  static_assert(!is_const::value);
+}
Index: clang/test/Sema/riscv-sve-vector-trig-ops.c
===
--- /dev/null
+++ clang/test/Sema/riscv-sve-vector-trig-ops.c
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -triple riscv64 -target-feature +f -target-feature +d \
+// RUN:   -target-feature +v -target-feature +zfh -target-feature +experimental-zvfh \
+// RUN:   -disable-O0-optnone -o - -fsyntax-only %s -verify 
+
+#include 
+
+
+vfloat32mf2_t test_sin_vv_i8mf8(vfloat32mf2_t v) {
+
+  return __builtin_elementwise_sin(v);
+  // expected-error@-1 {{1st argument must be a vector, integer or floating point type}}
+}
+
+vfloat32mf2_t test_cos_vv_i8mf8(vfloat32mf2_t v) {
+
+  return __builtin_elementwise_cos(v);
+  // expected-error@-1 {{1st argument must be a vector, integer or floating point type}}
+}
Index: clang/test/Sema/builtins-elementwise-math.c
===
--- clang/test/Sema/builtins-elementwise-math.c
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -280,6 +280,27 @@
   // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned4' (vector of 4 'unsigned int' values))}}
 }
 
+void test_builtin_elementwise_cos(int i, float f, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
+
+  struct Foo s = __builtin_elementwise_cos(f);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'float'}}
+
+  i = __builtin_elementwise_cos();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_elementwise_cos(i);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int')}}
+
+  i = __builtin_elementwise_cos(f, f);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  u = __builtin_elementwise_cos(u);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned int')}}
+
+  uv = __builtin_elementwise_cos(uv);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned4' (vector of 4 'unsigned int' values))}}
+}
+
 void test_builtin_elementwise_floor(int i, float f, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
 
   struct Foo s = __builtin_elementwise_floor(f);
@@ -322,6 +343,27 @@
   // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned4' (vector of 4 'unsigned int' values))}}
 }
 
+void test_builtin_elementwise_sin(int i, float f, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
+
+  struct Foo s = __builtin_elementwise_sin(f);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'float'}}
+
+  i = __builtin_elementwise_sin();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_elementwise_sin(i);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int')}}
+
+  i = __builtin_elementwise_sin(f, f);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  u = __builtin_elementwise_sin(u);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned int')}}
+
+  uv = __builtin_elementwise_sin(uv);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned4' (vector of 4 'unsigned int' values))}}
+}
+
 void test_builtin_elementwise_trunc(int i, float f, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
 
   struct Foo s = __builtin_elementwise_trunc(f);
Index: clang/test/Sema/aarch64-sve-vector-trig-ops.c
===
--- /dev/null
+++ clang/test/Sema/aarch64-sve-vector-t

Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-10 Thread Aaron Ballman via cfe-commits
On Thu, Nov 10, 2022 at 12:16 PM Zack Weinberg via cfe-commits
 wrote:
>
> I’m the closest thing Autoconf has to a lead maintainer at present.
>
> It’s come to my attention (via https://lwn.net/Articles/913505/ and
> https://fedoraproject.org/wiki/Changes/PortingToModernC) that GCC and
> Clang both plan to disable several “legacy” C language features by
> default in a near-future release (GCC 14, Clang 16) (see the Fedora
> wiki link for a list).  I understand that this change potentially
> breaks a lot of old dusty code, and in particular that
> Autoconf-generated configure scripts use constructs that may *silently
> give the wrong answer to a probe* when a stricter compiler is in use.
>
> Nobody has a whole lot of time to work on Autoconf at present, but I
> would like to ask, anyway, what Autoconf could potentially do to make
> this transition easier.  I’m already aware that the test code Autoconf
> 2.71 uses to probe for C89/C99/C11 support is broken; this has been
> fixed in development trunk to the extent it is possible for me to test
> it with GCC 12 (commit:
> ).
> Several other places using K&R function definitions and/or
> unprototyped function declarations (including the ubiquitously used
> AC_CHECK_FUNC) have also been fixed on trunk,
> .
> Changes to handle C23 built-in ‘bool’ better are under development but
> the design has not yet been finalized.

Thank you for all of your efforts in modernizing autoconf in response
to all these changes, it's greatly appreciated!

> The biggest remaining (potential) problem, that I’m aware of, is that
> AC_CHECK_FUNC unconditionally declares the function we’re probing for
> as ‘char NAME (void)’, and asks the compiler to call it with no
> arguments, regardless of what its prototype actually is.  It is not
> clear to me whether this will still work with the planned changes to
> the compilers.  Both GCC 12 and Clang 14 have on-by-default warnings
> triggered by ‘extern char memcpy(void);’ (or any other standard
> library function whose prototype is coded into the compiler) and this
> already causes problems for people who run configure scripts with
> CC='cc -Werror'.  Unfortunately this is very hard to fix — we would
> have to build a comprehensive list of library functions into Autoconf,
> mapping each to either its documented prototype or to a header where
> it ought to be declared; in the latter case we would also have to make
> e.g. AC_CHECK_FUNCS([getaddrinfo]) imply AC_CHECK_HEADERS([sys/types.h
> sys/socket.h netdb.h]) which might mess up configure scripts that
> aren’t expecting headers to be probed at that point.

In terms of the Clang side of things, I don't think we've formed any
sort of official stance on how to handle that yet. It's UB (you can
declare the C standard library interface without UB but calling any
function with a mismatched signature is UB) and that UB has some
amount of security implications associated with it, so I would say
there's a potential we might want to upgrade the diagnostic severity,
but it's not assured. FWIW, we're working on improving communication
about potentially disruptive changes to Clang, so you might want to
consider either subscribing to the clang-vendors code review group at
https://reviews.llvm.org/project/members/113/ (if you want to be
involved in code review before things land) or the Announcements
discourse channel at https://discourse.llvm.org/c/announce/ (if you
want to be notified after something lands but before Clang ships).

> How important do you think it is for this to be fixed?
>
> Are there any other changes you would like to see in a near-future
> Autoconf 2.72 in order to make this transition easier?

I don't have a specific list, but as a general request: moving away
from deprecated facilities of C or reliance on UB is a very pragmatic
idea given that the C committee is recapturing some of that design
space (like what happened with K&R C signatures) and implementers are
trying to improve the security posture for C.

> zw
>
> p.s. GCC and Clang folks: As long as you’re changing the defaults out
> from under people, can you please also remove the last few predefined
> user-namespace macros (-Dlinux, -Dunix, -Darm, etc) from all the
> -std=gnuXX modes?

If we can do so without breaking the world, I personally think it
would be nice to remove them.

~Aaron

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


[PATCH] D128223: [clang] Cached linkage assertion for static locals of static function

2022-11-10 Thread Chris Bowler via Phabricator via cfe-commits
cebowleratibm added a comment.

I believe the fix for a52d151f9dde7 inadvertently exposed a code path where by 
the linkage of a static local of a static function, which would otherwise 
return LinkageInfo::none() may now return VisibleNoLinkage depending on the 
incoming computation argument.

I don't think a static local of a function with no linkage should ever return 
VisibleNoLinkage so I've added the appropriate guard such that the linkage 
evaluation with return no linkage regardless of the computation argument.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128223

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


[PATCH] D128457: [clangd] Add new IncludeType to IncludeHeaderWithReferences

2022-11-10 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 474571.
dgoldman marked an inline comment as done.
dgoldman added a comment.

Fix serialization and isSelfContainedHeader

- Keep serialization as a single var uint32
- Keep old imported logic in isSelfContainedHeader in addition to a new check 
for import lines only for main files


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128457

Files:
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/index/Serialization.cpp
  clang-tools-extra/clangd/index/Symbol.h
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/index/SymbolCollector.h
  clang-tools-extra/clangd/index/YAMLSerialization.cpp
  clang-tools-extra/clangd/index/remote/Index.proto
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
  clang-tools-extra/clangd/test/index-serialization/Inputs/sample.idx
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp
  clang-tools-extra/clangd/unittests/SerializationTests.cpp

Index: clang-tools-extra/clangd/unittests/SerializationTests.cpp
===
--- clang-tools-extra/clangd/unittests/SerializationTests.cpp
+++ clang-tools-extra/clangd/unittests/SerializationTests.cpp
@@ -53,8 +53,16 @@
 IncludeHeaders:
   - Header:'include1'
 References:7
+Directives:  [ Include ]
   - Header:'include2'
 References:3
+Directives:  [ Import ]
+  - Header:'include3'
+References:2
+Directives:  [ Include, Import ]
+  - Header:'include4'
+References:1
+Directives:  [ ]
 ...
 ---
 !Symbol
@@ -114,8 +122,11 @@
 
 MATCHER_P(id, I, "") { return arg.ID == cantFail(SymbolID::fromStr(I)); }
 MATCHER_P(qName, Name, "") { return (arg.Scope + arg.Name).str() == Name; }
-MATCHER_P2(IncludeHeaderWithRef, IncludeHeader, References, "") {
-  return (arg.IncludeHeader == IncludeHeader) && (arg.References == References);
+MATCHER_P3(IncludeHeaderWithRefAndDirectives, IncludeHeader, References,
+   SupportedDirectives, "") {
+  return (arg.IncludeHeader == IncludeHeader) &&
+ (arg.References == References) &&
+ (arg.SupportedDirectives == SupportedDirectives);
 }
 
 auto readIndexFile(llvm::StringRef Text) {
@@ -148,9 +159,14 @@
   EXPECT_EQ(static_cast(Sym1.Flags), 129);
   EXPECT_TRUE(Sym1.Flags & Symbol::IndexedForCodeCompletion);
   EXPECT_FALSE(Sym1.Flags & Symbol::Deprecated);
-  EXPECT_THAT(Sym1.IncludeHeaders,
-  UnorderedElementsAre(IncludeHeaderWithRef("include1", 7u),
-   IncludeHeaderWithRef("include2", 3u)));
+  EXPECT_THAT(
+  Sym1.IncludeHeaders,
+  UnorderedElementsAre(
+  IncludeHeaderWithRefAndDirectives("include1", 7u, Symbol::Include),
+  IncludeHeaderWithRefAndDirectives("include2", 3u, Symbol::Import),
+  IncludeHeaderWithRefAndDirectives(
+  "include3", 2u, Symbol::Include | Symbol::Import),
+  IncludeHeaderWithRefAndDirectives("include4", 1u, Symbol::Invalid)));
 
   EXPECT_THAT(Sym2, qName("clang::Foo2"));
   EXPECT_EQ(Sym2.Signature, "-sig");
Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -567,9 +567,9 @@
   L.Name = "left";
   R.Name = "right";
   L.ID = R.ID = SymbolID("hello");
-  L.IncludeHeaders.emplace_back("common", 1);
-  R.IncludeHeaders.emplace_back("common", 1);
-  R.IncludeHeaders.emplace_back("new", 1);
+  L.IncludeHeaders.emplace_back("common", 1, Symbol::Include);
+  R.IncludeHeaders.emplace_back("common", 1, Symbol::Include);
+  R.IncludeHeaders.emplace_back("new", 1, Symbol::Include);
 
   // Both have no definition.
   Symbol M = mergeSymbol(L, R);
@@ -615,7 +615,7 @@
 std::move(DynData), DynSize);
 
   SymbolSlab::Builder StaticB;
-  S.IncludeHeaders.push_back({"", 0});
+  S.IncludeHeaders.push_back({"", 0, Symbol::Include});
   StaticB.insert(S);
   auto StaticIndex =
   MemIndex::build(std::move(StaticB).build(), RefSlab(), RelationSlab());
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1071,7 +1071,7 @@
 Sym.Flags |= Symbol::IndexedForCodeCompletion;
 Sym.CanonicalDeclaration.FileURI = S.DeclaringFile.c_str();
 Sym.Definition.FileURI = S.DeclaringFile.c_str();
-Sym.IncludeHeaders.emplace_back(S.IncludeHeader, 1);
+Sym.IncludeHeaders.em

Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-10 Thread Nick Bowler via cfe-commits
On 2022-11-10, Zack Weinberg  wrote:
> The biggest remaining (potential) problem, that I’m aware of, is that
> AC_CHECK_FUNC unconditionally declares the function we’re probing for
> as ‘char NAME (void)’, and asks the compiler to call it with no
> arguments, regardless of what its prototype actually is.  It is not
> clear to me whether this will still work with the planned changes to
> the compilers.  Both GCC 12 and Clang 14 have on-by-default warnings
> triggered by ‘extern char memcpy(void);’ (or any other standard
> library function whose prototype is coded into the compiler) and this
> already causes problems for people who run configure scripts with
> CC='cc -Werror'.  Unfortunately this is very hard to fix — we would
> have to build a comprehensive list of library functions into Autoconf,
> mapping each to either its documented prototype or to a header where
> it ought to be declared; in the latter case we would also have to make
> e.g. AC_CHECK_FUNCS([getaddrinfo]) imply AC_CHECK_HEADERS([sys/types.h
> sys/socket.h netdb.h]) which might mess up configure scripts that
> aren’t expecting headers to be probed at that point.
>
> How important do you think it is for this to be fixed?

My gut feeling is that Autoconf should just determine the necessary
options to get compatible behaviour out of these modern compilers, at
least for the purpose of running configure tests.  For example, Autoconf
should probably build the AC_CHECK_FUNC programs using gcc's
-fno-builtin option, which should avoid problems with gcc complaining
about memcpy (and may also improve test accuracy, since gcc won't use
its knowledge of C library behaviour to possibly elide the call to
memcpy).

It saddens me to see so much breakage happening in "modern C", a
language that has (until now) a long history of new language features
being carefully introduced to avoid these sort of problems.

The fact that even the C standard authors don't even seem to care about
existing codebases is a concerning change in direction.  Nobody has
learned anything from the Python 3 debacle, I guess.

> p.s. GCC and Clang folks: As long as you’re changing the defaults out
> from under people, can you please also remove the last few predefined
> user-namespace macros (-Dlinux, -Dunix, -Darm, etc) from all the
> -std=gnuXX modes?

Meh, even though these macros are a small thing I don't accept the
"things are breaking anyway so let's break even more things" attitude.
This was something that many library authors did during the python 3
transition and that just made the problems orders of magnitude more
horrible.

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


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-10 Thread Rich Felker via cfe-commits
On Thu, Nov 10, 2022 at 12:16:20PM -0500, Zack Weinberg wrote:
> I’m the closest thing Autoconf has to a lead maintainer at present.
> 
> It’s come to my attention (via https://lwn.net/Articles/913505/ and
> https://fedoraproject.org/wiki/Changes/PortingToModernC) that GCC and
> Clang both plan to disable several “legacy” C language features by
> default in a near-future release (GCC 14, Clang 16) (see the Fedora
> wiki link for a list).  I understand that this change potentially
> breaks a lot of old dusty code, and in particular that
> Autoconf-generated configure scripts use constructs that may *silently
> give the wrong answer to a probe* when a stricter compiler is in use.
> 
> Nobody has a whole lot of time to work on Autoconf at present, but I
> would like to ask, anyway, what Autoconf could potentially do to make
> this transition easier.  I’m already aware that the test code Autoconf
> 2.71 uses to probe for C89/C99/C11 support is broken; this has been
> fixed in development trunk to the extent it is possible for me to test
> it with GCC 12 (commit:
> ).
> Several other places using K&R function definitions and/or
> unprototyped function declarations (including the ubiquitously used
> AC_CHECK_FUNC) have also been fixed on trunk,
> .
> Changes to handle C23 built-in ‘bool’ better are under development but
> the design has not yet been finalized.
> 
> The biggest remaining (potential) problem, that I’m aware of, is that
> AC_CHECK_FUNC unconditionally declares the function we’re probing for
> as ‘char NAME (void)’, and asks the compiler to call it with no
> arguments, regardless of what its prototype actually is.  It is not
> clear to me whether this will still work with the planned changes to
> the compilers.  Both GCC 12 and Clang 14 have on-by-default warnings
> triggered by ‘extern char memcpy(void);’ (or any other standard
> library function whose prototype is coded into the compiler) and this
> already causes problems for people who run configure scripts with
> CC='cc -Werror'.  Unfortunately this is very hard to fix — we would
> have to build a comprehensive list of library functions into Autoconf,
> mapping each to either its documented prototype or to a header where
> it ought to be declared; in the latter case we would also have to make
> e.g. AC_CHECK_FUNCS([getaddrinfo]) imply AC_CHECK_HEADERS([sys/types.h
> sys/socket.h netdb.h]) which might mess up configure scripts that
> aren’t expecting headers to be probed at that point.
> 
> How important do you think it is for this to be fixed?
> 
> Are there any other changes you would like to see in a near-future
> Autoconf 2.72 in order to make this transition easier?

Thanks for bringing this up. It is very important and I am very much
in favor of making these changes and doing it in a way that existing
broken and unmaintained software can be made to work just by
re-generating configure scripts with up-to-date autoconf, even if that
means hard-coding a list of headers needed to get the right
declarations and automatically pulling them in. Otherwise this is
going to be a gigantic burden on distro maintainers/systems
integrators.

I've been writing/complaining about autoconf doing this wrong for
decades, with the best writeup around 9 years ago at
https://ewontfix.com/13/. Part of the reason is that this has bitten
musl libc users over and over again due to configure finding symbols
that were intended only as ABI-compat and trying to use them (without
declarations) at the source level, leading to various messes, some of
which we're only just extricating ourselves from now:

https://git.musl-libc.org/cgit/musl/commit/?id=246f1c811448f37a44b41cd8df8d0ef9736d95f4
https://git.musl-libc.org/cgit/musl/commit/?id=25e6fee27f4a293728dd15b659170e7b9c7db9bc

But aside from issues like this, just the fact that autoconf was
precluding making -Werror=implicit-function-declaration default must
have wasted tens if not hundreds of thousands of human hours debugging
broken builds.

What I'd like to see happen is complete deprecation of the autoconf
link-only tests -- only keeping them for use by legacy unmaintained
projects in the form where they actually implicitly include the right
header and test compile and link using that.

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


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-10 Thread Aaron Ballman via cfe-commits
On Thu, Nov 10, 2022 at 1:12 PM Jonathan Wakely via cfe-commits
 wrote:
>
> On Thu, 10 Nov 2022 at 17:58, Jonathan Wakely wrote:
> >
> > On Thu, 10 Nov 2022 at 17:52, Nick Bowler wrote:
> > > It saddens me to see so much breakage happening in "modern C", a
> > > language that has (until now) a long history of new language features
> > > being carefully introduced to avoid these sort of problems.
> >
> > The features were introduced in 1999.
>
> Well, some of them were. Some more are coming now in C2x but the
> problem has existed since C99 it's just that compilers "protected"
> most users from having to fix their code at the time. But it's been
> more than two decades and it's time to accept that missing prototypes,
> implicit conversions between pointers and ints etc are a hazard and
> should be diagnosed not ignored for the benefit of people who never
> want to fix their questionable code.

Functions without prototypes were deprecated in ANSI C and came into
ISO C as deprecated. They were obsoleted with the release of the 2nd
edition of K&R C (circa 1978) when prototypes were introduced, IIRC.
They've literally never been a recommended practice in standard C.
Implicit function declarations and implicit int were outright removed
from C99 without a deprecation period due to the security concerns
they caused.

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


[PATCH] D137269: [Clang][AArch64][Darwin] Enable GlobalISel by default for Darwin ARM64 platforms.

2022-11-10 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Looks like there are a few issues flagged already. Is someone reverting, or 
what's the plan?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137269

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


[PATCH] D137350: [RISCV] Implement assembler support for XVentanaCondOps

2022-11-10 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added inline comments.



Comment at: llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp:469
+if (STI.getFeatureBits()[RISCV::FeatureVendorXVentanaCondOps]) {
+  LLVM_DEBUG(dbgs() << "Trying Vemtama custom opcode table:\n");
+  Result = decodeInstruction(DecoderTableVentana32, MI, Insn, Address, 
this,

Typo, should be "Trying Ventana..."



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfo.td:1785
+//===--===//
+// Vendor extensions
+//===--===//

reames wrote:
> How do we want to manage td files for vendor extensions?
> 
> I put them inline - which is probably not the right answer.  I'm leaning 
> towards a vendor specific td file with extensions split out if complexity 
> justifies it.  So, this patch would add a RISCVInstInfoXVentana.td.  
> 
> Is that the precedent we want here?
I would suggest put into `RISCVInstInfoXVentana.td` instead of inline here, I 
could imagine once this get merged, T-head extensions might try to upstream 
too, so put into separated now could prevent they reference this commit and try 
to inline their extensions IMO :)


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

https://reviews.llvm.org/D137350

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


[PATCH] D137269: [Clang][AArch64][Darwin] Enable GlobalISel by default for Darwin ARM64 platforms.

2022-11-10 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

In D137269#3916916 , @nikic wrote:

> I'd like to object to enabling this via the frontend. This means that 
> non-clang frontends will now use a non-default configuration that is not 
> extensively tested by upstream anymore.
>
> If you don't want to change tests, you can adjust the RUN lines to explicitly 
> disable globalisel.

+1, even in-tree if you use lld/LTO you won't be using globalisel


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137269

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


[clang] 790cbaa - [OpenCL] Fix diagnostics with templates in kernel args.

2022-11-10 Thread Anastasia Stulova via cfe-commits

Author: Anastasia Stulova
Date: 2022-11-10T18:55:12Z
New Revision: 790cbaafc9e276aa740373c00849951338056174

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

LOG: [OpenCL] Fix diagnostics with templates in kernel args.

Improve checking for the standard layout type when diagnosing
the kernel argument with templated types. The check doesn't work
correctly for references or pointers due to the lazy template
instantiation.

Current fix only improves cases where nested types in the templates
do not depend on the template parameters.

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

Added: 


Modified: 
clang/lib/Sema/SemaDecl.cpp
clang/test/SemaOpenCLCXX/invalid-kernel.clcpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 3bec6b0f65e7b..bac87c0127236 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -9234,10 +9234,23 @@ static OpenCLParamType 
getOpenCLKernelParameterType(Sema &S, QualType PT) {
 // reference if an implementation supports them in kernel parameters.
 if (S.getLangOpts().OpenCLCPlusPlus &&
 !S.getOpenCLOptions().isAvailableOption(
-"__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
-!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
-!PointeeType->isStandardLayoutType())
+"__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
+ auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
+ bool IsStandardLayoutType = true;
+ if (CXXRec) {
+   // If template type is not ODR-used its definition is only available
+   // in the template definition not its instantiation.
+   // FIXME: This logic doesn't work for types that depend on template
+   // parameter (PR58590).
+   if (!CXXRec->hasDefinition())
+ CXXRec = CXXRec->getTemplateInstantiationPattern();
+   if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
+ IsStandardLayoutType = false;
+ }
+ if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
+!IsStandardLayoutType)
   return InvalidKernelParam;
+}
 
 return PtrKernelParam;
   }

diff  --git a/clang/test/SemaOpenCLCXX/invalid-kernel.clcpp 
b/clang/test/SemaOpenCLCXX/invalid-kernel.clcpp
index 9bd147364483c..8795fd7173018 100644
--- a/clang/test/SemaOpenCLCXX/invalid-kernel.clcpp
+++ b/clang/test/SemaOpenCLCXX/invalid-kernel.clcpp
@@ -93,3 +93,24 @@ kernel void trivial_r(__global Trivial &in) {}
 #ifndef UNSAFEKERNELPARAMETER
 //expected-error@-2{{'__global Trivial &__private' cannot be used as the type 
of a kernel parameter}}
 #endif
+
+// Nested types and templates
+struct Outer {
+  struct Inner{
+int i;
+  };
+};
+template
+struct OuterTempl {
+  struct Inner{
+int i;
+  };
+};
+// FIXME: (PR58590) Use of template parameter dependent types doesn't
+// work yet due to lazy instantiation of reference types.
+//template
+//struct Templ {
+//T i;
+//};
+
+extern kernel void nested(constant Outer::Inner& r1, constant 
OuterTempl::Inner& r2/*, constant Templ& r3*/);



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


[PATCH] D134445: [PR57881][OpenCL] Fix incorrect diagnostics with templated types in kernel arguments

2022-11-10 Thread Anastasia Stulova 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 rG790cbaafc9e2: [OpenCL] Fix diagnostics with templates in 
kernel args. (authored by Anastasia).
Herald added a subscriber: ldrumm.
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D134445?vs=470458&id=474577#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134445

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaOpenCLCXX/invalid-kernel.clcpp


Index: clang/test/SemaOpenCLCXX/invalid-kernel.clcpp
===
--- clang/test/SemaOpenCLCXX/invalid-kernel.clcpp
+++ clang/test/SemaOpenCLCXX/invalid-kernel.clcpp
@@ -93,3 +93,24 @@
 #ifndef UNSAFEKERNELPARAMETER
 //expected-error@-2{{'__global Trivial &__private' cannot be used as the type 
of a kernel parameter}}
 #endif
+
+// Nested types and templates
+struct Outer {
+  struct Inner{
+int i;
+  };
+};
+template
+struct OuterTempl {
+  struct Inner{
+int i;
+  };
+};
+// FIXME: (PR58590) Use of template parameter dependent types doesn't
+// work yet due to lazy instantiation of reference types.
+//template
+//struct Templ {
+//T i;
+//};
+
+extern kernel void nested(constant Outer::Inner& r1, constant 
OuterTempl::Inner& r2/*, constant Templ& r3*/);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -9234,10 +9234,23 @@
 // reference if an implementation supports them in kernel parameters.
 if (S.getLangOpts().OpenCLCPlusPlus &&
 !S.getOpenCLOptions().isAvailableOption(
-"__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
-!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
-!PointeeType->isStandardLayoutType())
+"__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
+ auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
+ bool IsStandardLayoutType = true;
+ if (CXXRec) {
+   // If template type is not ODR-used its definition is only available
+   // in the template definition not its instantiation.
+   // FIXME: This logic doesn't work for types that depend on template
+   // parameter (PR58590).
+   if (!CXXRec->hasDefinition())
+ CXXRec = CXXRec->getTemplateInstantiationPattern();
+   if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
+ IsStandardLayoutType = false;
+ }
+ if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
+!IsStandardLayoutType)
   return InvalidKernelParam;
+}
 
 return PtrKernelParam;
   }


Index: clang/test/SemaOpenCLCXX/invalid-kernel.clcpp
===
--- clang/test/SemaOpenCLCXX/invalid-kernel.clcpp
+++ clang/test/SemaOpenCLCXX/invalid-kernel.clcpp
@@ -93,3 +93,24 @@
 #ifndef UNSAFEKERNELPARAMETER
 //expected-error@-2{{'__global Trivial &__private' cannot be used as the type of a kernel parameter}}
 #endif
+
+// Nested types and templates
+struct Outer {
+  struct Inner{
+int i;
+  };
+};
+template
+struct OuterTempl {
+  struct Inner{
+int i;
+  };
+};
+// FIXME: (PR58590) Use of template parameter dependent types doesn't
+// work yet due to lazy instantiation of reference types.
+//template
+//struct Templ {
+//T i;
+//};
+
+extern kernel void nested(constant Outer::Inner& r1, constant OuterTempl::Inner& r2/*, constant Templ& r3*/);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -9234,10 +9234,23 @@
 // reference if an implementation supports them in kernel parameters.
 if (S.getLangOpts().OpenCLCPlusPlus &&
 !S.getOpenCLOptions().isAvailableOption(
-"__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
-!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
-!PointeeType->isStandardLayoutType())
+"__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
+ auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
+ bool IsStandardLayoutType = true;
+ if (CXXRec) {
+   // If template type is not ODR-used its definition is only available
+   // in the template definition not its instantiation.
+   // FIXME: This logic doesn't work for types that depend on template
+   // parameter (PR58590).
+   if (!CXXRec->hasDefinition())
+ CXXRec = CXXRec->getTemplateInstantiationPattern();
+   if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
+ IsStandardLayoutType = false;
+ }
+ if (!PointeeType->isAtomicType() && !Pointe

[PATCH] D137794: [clangd] Enable configuring include insertions

2022-11-10 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: sammccall, kadircet, nridge.
Herald added a subscriber: arphaman.
Herald added a project: All.
njames93 requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

See https://github.com/clangd/clangd/issues/1367


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137794

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/CodeComplete.h
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/IncludeFixer.cpp
  clang-tools-extra/clangd/IncludeFixer.h
  clang-tools-extra/clangd/IncludeRenamer.cpp
  clang-tools-extra/clangd/IncludeRenamer.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -11,6 +11,7 @@
 #include "Diagnostics.h"
 #include "Feature.h"
 #include "FeatureModule.h"
+#include "IncludeRenamer.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "TestFS.h"
@@ -1294,6 +1295,35 @@
   "Include \"b.h\" for symbol na::nb::X");
 }
 
+TEST(IncludeFixerTest, InsertIncludeRules) {
+  Annotations Test(R"cpp(// error-ok
+$insert[[]]namespace na {
+namespace nb {
+void foo() {
+  $unqualified[[X]] x;
+}
+}
+}
+  )cpp");
+  auto TU = TestTU::withCode(Test.code());
+  auto Index = buildIndexWithSymbol(
+  {SymbolWithHeader{"na::X", "unittest:///foo.h", "\"foo.h\""},
+   SymbolWithHeader{"na::nb::X", "unittest:///bar.h", "\"bar.h\""}});
+  TU.ExternalIndex = Index.get();
+  Config Cfg;
+  Cfg.IncludeRules->addRule({std::make_shared("^foo"),
+ IncludeRule::Type::Angled, std::string("my_foo")});
+  Cfg.IncludeRules->addRule({std::make_shared("^bar"),
+ IncludeRule::Type::Disabled, None});
+  WithContextValue Ctx(Config::Key, std::move(Cfg));
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  UnorderedElementsAre(AllOf(
+  Diag(Test.range("unqualified"), "unknown type name 'X'"),
+  diagName("unknown_typename"),
+  withFix(Fix(Test.range("insert"), "#include \n",
+  "Include  for symbol na::X");
+}
+
 TEST(IncludeFixerTest, NoCrashMemberAccess) {
   Annotations Test(R"cpp(// error-ok
 struct X { int  xyz; };
Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -274,6 +274,31 @@
   EXPECT_THAT(Results[0].Style.FullyQualifiedNamespaces,
   ElementsAre(val("foo"), val("bar")));
 }
+
+TEST(ParseYAML, IncludeRules) {
+  CapturedDiags Diags;
+  Annotations YAML(R"yaml(
+IncludeRules:
+  - PathMatch: 'Library/'
+Type:   Angled
+  - PathMatch: 'Library2/'
+Type:   Quoted
+Replace:'Libary/'
+---
+IncludeRules:
+  $listinput^PathMatch:  'Library/'
+  Type:   Angled
+  Replace:'Library2/'
+)yaml");
+  auto Results =
+  Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback());
+  ASSERT_EQ(Results.size(), 1u);
+  EXPECT_EQ(Results[0].IncludeRules.size(), 2U);
+  EXPECT_THAT(Diags.Diagnostics,
+  ElementsAre(AllOf(diagMessage("Expected list of Input Rules"),
+diagKind(llvm::SourceMgr::DK_Error),
+diagPos(YAML.point("listinput");
+}
 } // namespace
 } // namespace config
 } // namespace clangd
Index: clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
@@ -544,6 +544,71 @@
   EXPECT_TRUE(compileAndApply());
   EXPECT_THAT(Conf.Style.FullyQualifiedNamespaces, ElementsAre("foo", "bar"));
 }
+
+TEST_F(ConfigCompileTests, IncludeRules) {
+
+  auto Add = [&](llvm::StringRef PathMatch = "", llvm::StringRef Type = "",
+ llvm::StringRef Replace = "") {
+Fragment::IncludeRuleBlock IRB;
+if (!PathMatch.empty())
+  IRB.PathMatch.emplace(PathMatch.str());
+if (!Type.empty())
+  IRB.Type.emplace(Type.str());
+if (!Replac

[PATCH] D137107: Allow MS extension: support of constexpr with __declspec(dllimport).

2022-11-10 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

In D137107#3906766 , @rnk wrote:

> In D137107#3905443 , @zahiraam 
> wrote:
>
>>   extern int __declspec(dllimport) next(int n);
>>   int main () {
>> extern int _declspec(dllimport) val;
>> constexpr int& val_ref = val;
>> int i = next(val_ref);
>> return i;
>>   } 
>>
>> @rnk Shouldn't this run?
>
> Yes, I agree, this is a bug. Clang should compile this and reference 
> `__imp_next` here. However, Clang should continue producing errors when a 
> dllimport symbol is used to initialize a constexpr global variable, which was 
> one of the other cases mentioned in the initial report.

@rnk would you mind looking at the fix I am proposing for this bug? Thanks.


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

https://reviews.llvm.org/D137107

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


[PATCH] D133249: [libc++] Documents details of the pre-commit CI.

2022-11-10 Thread Mark de Wever via Phabricator via cfe-commits
Mordante marked 6 inline comments as done.
Mordante added a comment.

Thanks for all feedback!




Comment at: clang/www/hacking.html:311-312
+  Unlike Clang, libc++ supports multiple versions of Clang. Therefore when a
+  patch changes the diagnostics it might be required to use a regex in the
+  "expected" tests to make it pass the CI.
+

aaron.ballman wrote:
> ldionne wrote:
> > Mordante wrote:
> > > Mordante wrote:
> > > > philnik wrote:
> > > > > aaron.ballman wrote:
> > > > > > Should we document the expectation that breaking libc++ due to 
> > > > > > conforming changes in Clang (in terms of diagnostics and bug fixes, 
> > > > > > not so much in terms of introducing new language extensions) are 
> > > > > > generally the responsibility of libc++ maintainers to address, but 
> > > > > > Clang contributors should attempt to reduce disruptions as much as 
> > > > > > possible by collaborating with libc++ maintainers when this 
> > > > > > situation comes up?
> > > > > That's definitely a good idea. Maybe mention that clang contributors 
> > > > > should ping the #libc group to get the attention of libc++ 
> > > > > contributors so we can prepare a follow-up patch or, if the author is 
> > > > > comfortable with it, also fix libc++ in the same patch (and hopefully 
> > > > > get fast approval). Most breakages should be relatively simple to fix.
> > > > I like the idea to collaborate more.
> > > > 
> > > > I want to give this some thought and especially how to word it. I want 
> > > > to avoid that it's seen as a carte blanche to commit Clang changes 
> > > > which break libc++. This would mean HEAD is broken and that's a huge 
> > > > issue for downstream users like Google who tend to follow HEAD closely.
> > > > 
> > > > I would prefer to use commandeering and instead of two patches where 
> > > > one leave HEAD in a broken state. Even if it's short it would make 
> > > > bi-secting harder. Personally I really dislike the idea of having 
> > > > commits that knowingly leave a repository in a broken state. It also 
> > > > doesn't align with the LLVM developer policy 
> > > > https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy 
> > > > ```
> > > > As a community, we strongly value having the tip of tree in a good 
> > > > state while allowing rapid iterative development. 
> > > > ```
> > > > 
> > > > Should we document the expectation that breaking libc++ due to 
> > > > conforming changes in Clang (in terms of diagnostics and bug fixes, not 
> > > > so much in terms of introducing new language extensions) are generally 
> > > > the responsibility of libc++ maintainers to address, but Clang 
> > > > contributors should attempt to reduce disruptions as much as possible 
> > > > by collaborating with libc++ maintainers when this situation comes up?
> > > 
> > > @aaron.ballman I have given this some thought. I think it would be best 
> > > to discuss this with some libc++ and Clang contributors/code owners. For 
> > > libc++ at least @ldionne should be present since he's the libc++ code 
> > > owner. I would like to be present too. After we have agreement we can 
> > > update this documentation accordingly.
> > I remember discussing this with @aaron.ballman.
> > 
> > I am 100% on-board with the notion that if Clang makes a legitimate 
> > conforming change and it breaks libc++ (most likely because we are doing 
> > something wrong, UB, or relying on Clang details), then it is *primarily* 
> > libc++'s responsibility to fix this ASAP. I also remember that we agreed it 
> > should be a collaborative effort, i.e. the Clang folks should try to help 
> > us understand the failure, and should be understanding if the fix on our 
> > side is really non-trivial. But, the bottom line is that if they change 
> > something and it breaks us because we're doing something wrong, it's our 
> > responsibility to fix our stuff ASAP to get the CI green again.
> > 
> > This is the same situation that we sometimes have with the LLDB data 
> > formatters, and I think the dynamics need to be the same there as well. If 
> > we break that because of a 100% legitimate change in libc++, our 
> > expectation is that they'll fix it ASAP, and their expectation is that 
> > we'll provide support as needed.
> > 
> > I think it would be useful to document that, since it technically departs 
> > from LLVM's usual policy of "revert when it breaks anything at all". And 
> > more generally speaking, I strongly think that this policy needs to be 
> > revisited, however that's beyond the scope of this documentation 
> > improvement.
> > I am 100% on-board with the notion that if Clang makes a legitimate 
> > conforming change and it breaks libc++ (most likely because we are doing 
> > something wrong, UB, or relying on Clang details), then it is *primarily* 
> > libc++'s responsibility to fix this ASAP. I also remember that we agreed it 
> > should be a collaborative effort, i.e. the Clang folks sho

[clang] 0c111dd - [libc++] Documents details of the pre-commit CI.

2022-11-10 Thread Mark de Wever via cfe-commits

Author: Mark de Wever
Date: 2022-11-10T20:20:17+01:00
New Revision: 0c111dd86fffa91fbca502fd5f8e3db28f89270a

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

LOG: [libc++] Documents details of the pre-commit CI.

This documentation aims to make it cleare how the libc++ pre-commit CI
works. For libc++ developers and other LLVM projects whose changes can
affect libc++.

This was discusses with @aaron.ballman as a follow on some unclearities
for the Clang communitee how the libc++ pre-commit CI works.

Note some parts depend on patches under review as commented in the
documentation.

Reviewed By: ldionne, #libc, philnik

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

Added: 


Modified: 
clang/www/hacking.html
libcxx/docs/Contributing.rst
libcxx/docs/index.rst

Removed: 




diff  --git a/clang/www/hacking.html b/clang/www/hacking.html
index 1128a5553b82a..55c4f0f9f5cf6 100755
--- a/clang/www/hacking.html
+++ b/clang/www/hacking.html
@@ -30,6 +30,7 @@ Hacking on Clang
 Testing on Unix-like Systems
 Testing using Visual Studio on 
Windows
 Testing on the Command Line
+Testing changes affecting libc++
   
   
   Creating Patch Files
@@ -271,6 +272,41 @@ Testing on the Command Line
 
   The statistic, "Failed" (not shown if all tests pass), is the important 
one.
 
+  
+  Testing changes affecting libc++
+  
+
+  Some changes in Clang affect https://libcxx.llvm.org";>libc++,
+  for example:
+  
+  Changing the output of Clang's diagnostics.
+  Changing compiler builtins, especially the builtins used for type 
traits
+  or replacements of library functions like std::move or
+  std::forward.
+  
+
+  After adjusting libc++ to work with the changes, the next revision will be
+  tested by libc++'s
+  https://buildkite.com/llvm-project/libcxx-ci";>pre-commit CI.
+
+  For most configurations, the pre-commit CI uses a recent
+  https://apt.llvm.org/";>nightly build of Clang from LLVM's main
+  branch. These configurations do not use the Clang changes in the
+  patch. They only use the libc++ changes.
+
+  The "Bootstrapping build" builds Clang and uses it to build and
+  test libc++. This build does use the Clang changes in the patch.
+
+  Libc++ supports multiple versions of Clang. Therefore when a patch changes
+  the diagnostics it might be required to use a regex in the
+  "expected" tests to make it pass the CI.
+
+  Libc++ has more
+  https://libcxx.llvm.org/Contributing.html#pre-commit-ci";>
+  documentation about the pre-commit CI. For questions regarding
+  libc++, the best place to ask is the #libcxx channel on
+  https://discord.gg/jzUbyP26tQ";>LLVM's Discord server.
+
   
   Creating Patch Files
   

diff  --git a/libcxx/docs/Contributing.rst b/libcxx/docs/Contributing.rst
index 15c75e8c51681..faa904c4ba1f6 100644
--- a/libcxx/docs/Contributing.rst
+++ b/libcxx/docs/Contributing.rst
@@ -84,5 +84,136 @@ updated list from the failed build at
 Look for the failed build and select the ``artifacts`` tab. There, download the
 abilist for the platform, e.g.:
 
-* C++20 for the Linux platform.
-* MacOS C++20 for the Apple platform.
+* C++.
+* MacOS X86_64 and MacOS arm64 for the Apple platform.
+
+
+Pre-commit CI
+=
+
+Introduction
+
+
+Unlike most parts of the LLVM project, libc++ uses a pre-commit CI [#]_. This
+CI is hosted on `Buildkite `__ 
and
+the build results are visible in the review on Phabricator. Please make sure
+the CI is green before committing a patch.
+
+The CI tests libc++ for all :ref:`supported platforms `.
+The build is started for every 
diff  uploaded to Phabricator. A complete CI run
+takes approximately one hour. To reduce the load:
+
+* The build is cancelled when a new 
diff  for the same revision is uploaded.
+* The build is done in several stages and cancelled when a stage fails.
+
+Typically, the libc++ jobs use a Ubuntu Docker image. This image contains
+recent `nightly builds `__ of all supported versions of
+Clang and the current version of the ``main`` branch. These versions of Clang
+are used to build libc++ and execute its tests.
+
+Unless specified otherwise, the configurations:
+
+* use a nightly build of the ``main`` branch of Clang,
+* execute the tests using the language C++. This is the version
+  "developed" by the C++ committee.
+
+.. note:: Updating the Clang nightly builds in the Docker image is a manual
+   process and is done at an irregular interval on purpose. When you need to
+   have the latest nightly build to test recent Clang changes, ask in the
+   ``#libcxx`` channel on `LLVM's Discord server
+   `__.
+
+.. [#] There's `LLVM Dev Me

[PATCH] D133249: [libc++] Documents details of the pre-commit CI.

2022-11-10 Thread Mark de Wever via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Mordante marked an inline comment as done.
Closed by commit rG0c111dd86fff: [libc++] Documents details of the pre-commit 
CI. (authored by Mordante).

Changed prior to commit:
  https://reviews.llvm.org/D133249?vs=460827&id=474582#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133249

Files:
  clang/www/hacking.html
  libcxx/docs/Contributing.rst
  libcxx/docs/index.rst

Index: libcxx/docs/index.rst
===
--- libcxx/docs/index.rst
+++ libcxx/docs/index.rst
@@ -93,6 +93,7 @@
   Further, both projects are apparently abandoned: STLport 5.2.1 was
   released in Oct'08, and STDCXX 4.2.1 in May'08.
 
+.. _SupportedPlatforms:
 
 Platform and Compiler Support
 =
Index: libcxx/docs/Contributing.rst
===
--- libcxx/docs/Contributing.rst
+++ libcxx/docs/Contributing.rst
@@ -84,5 +84,136 @@
 Look for the failed build and select the ``artifacts`` tab. There, download the
 abilist for the platform, e.g.:
 
-* C++20 for the Linux platform.
-* MacOS C++20 for the Apple platform.
+* C++.
+* MacOS X86_64 and MacOS arm64 for the Apple platform.
+
+
+Pre-commit CI
+=
+
+Introduction
+
+
+Unlike most parts of the LLVM project, libc++ uses a pre-commit CI [#]_. This
+CI is hosted on `Buildkite `__ and
+the build results are visible in the review on Phabricator. Please make sure
+the CI is green before committing a patch.
+
+The CI tests libc++ for all :ref:`supported platforms `.
+The build is started for every diff uploaded to Phabricator. A complete CI run
+takes approximately one hour. To reduce the load:
+
+* The build is cancelled when a new diff for the same revision is uploaded.
+* The build is done in several stages and cancelled when a stage fails.
+
+Typically, the libc++ jobs use a Ubuntu Docker image. This image contains
+recent `nightly builds `__ of all supported versions of
+Clang and the current version of the ``main`` branch. These versions of Clang
+are used to build libc++ and execute its tests.
+
+Unless specified otherwise, the configurations:
+
+* use a nightly build of the ``main`` branch of Clang,
+* execute the tests using the language C++. This is the version
+  "developed" by the C++ committee.
+
+.. note:: Updating the Clang nightly builds in the Docker image is a manual
+   process and is done at an irregular interval on purpose. When you need to
+   have the latest nightly build to test recent Clang changes, ask in the
+   ``#libcxx`` channel on `LLVM's Discord server
+   `__.
+
+.. [#] There's `LLVM Dev Meeting talk `__
+   explaining the benefits of libc++'s pre-commit CI.
+
+Builds
+--
+
+Below is a short description of the most interesting CI builds [#]_:
+
+* ``Format`` runs ``clang-format`` and uploads its output as an artifact. At the
+  moment this build is a soft error and doesn't fail the build.
+* ``Generated output`` runs the ``libcxx-generate-files`` build target and
+  tests for non-ASCII characters in libcxx. Some files are excluded since they
+  use Unicode, mainly tests. The output of these commands are uploaded as
+  artifact.
+* ``Documentation`` builds the documentation. (This is done early in the build
+  process since it is cheap to run.)
+* ``C++`` these build steps test the various C++ versions, making sure all
+  C++ language versions work with the changes made.
+* ``Clang `` these build steps test whether the changes work with all
+  supported Clang versions.
+* ``Booststrapping build`` builds Clang using the revision of the patch and
+  uses that Clang version to build and test libc++. This validates the current
+  Clang and lib++ are compatible.
+
+  When a crash occurs in this build, the crash reproducer is available as an
+  artifact.
+
+* ``Modular build`` tests libc++ using Clang modules [#]_.
+* ``GCC `` tests libc++ with the latest stable GCC version. Only C++11
+  and the latest C++ version are tested.
+* ``Santitizers`` tests libc++ using the Clang sanitizers.
+* ``Parts disabled`` tests libc++ with certain libc++ features disabled.
+* ``Windows`` tests libc++ using MinGW and clang-cl.
+* ``Apple`` tests libc++ on MacOS.
+* ``ARM`` tests libc++ on various Linux ARM platforms.
+* ``AIX`` tests libc++ on AIX.
+
+.. [#] Not all all steps are listed: steps are added and removed when the need
+   arises.
+.. [#] Clang modules are not the same as C++20's modules.
+
+Infrastructure
+--
+
+All files of the CI infrastructure are in the directory ``libcxx/utils/ci``.
+Note that quite a bit of this infrastructure is heavily Linux focused. This is
+the platform used by most of libc++

[PATCH] D136919: [X86][RFC] Change mangle name of __bf16 from u6__bf16 to DF16b

2022-11-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Okay.  That raises the question of what the default semantics should be for 
`std::bfloat16_t`, i.e. whether we should semantically default the type to 
using excess-precision `float` arithmetic.  If we did, we'd still be able to 
demote solitary `float` operations to BF16, but anything more complex than that 
would often force promotion without user intervention.

Of course, even if we do default the type to excess precision, we could still 
have a flag to disable that, and we could potentially have different default 
values on different targets.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136919

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


[clang] 380a038 - Updated contact email address.

2022-11-10 Thread Anastasia Stulova via cfe-commits

Author: Anastasia Stulova
Date: 2022-11-10T19:50:19Z
New Revision: 380a038d147454afb16b97fd9739f4c3d7307401

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

LOG: Updated contact email address.

Added: 


Modified: 
clang/CodeOwners.rst

Removed: 




diff  --git a/clang/CodeOwners.rst b/clang/CodeOwners.rst
index 70662a6a580d..25c8521b2e06 100644
--- a/clang/CodeOwners.rst
+++ b/clang/CodeOwners.rst
@@ -229,7 +229,7 @@ OpenMP conformance
 OpenCL conformance
 ~~
 | Anastasia Stulova
-| anastasia.stulova\@arm.com (email), Anastasia (Phabricator), 
AnastasiaStulova (GitHub)
+| anastasia\@compiler-experts.com (email), Anastasia (Phabricator), 
AnastasiaStulova (GitHub)
 
 
 SYCL conformance



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


[PATCH] D137205: [clang-tidy] Add performance-unnecessary-copy-on-last-use check

2022-11-10 Thread Oliver Stöneberg via Phabricator via cfe-commits
firewave added a comment.

Getting this false positive:

  #include 
  
  extern std::string str()
  {
std::string ret;
return ret.empty() ? ret : ret.substr(1);
  }



  input.cpp:6:23: warning: Parameter 'ret' is copied on last use, consider 
moving it instead. [performance-unnecessary-copy-on-last-use]
  return ret.empty() ? ret : ret.substr(1);
   ^
   std::move( )


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137205

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


[PATCH] D137205: [clang-tidy] Add performance-unnecessary-copy-on-last-use check

2022-11-10 Thread Oliver Stöneberg via Phabricator via cfe-commits
firewave added a comment.

Another false positive:

  #include 
  
  void evaluateLibraryFunction()
  {
std::unordered_map m;
  
auto f = [m]() {};
  }



  input.cpp:7:12: warning: Parameter 'm' is copied on last use, consider moving 
it instead. [performance-unnecessary-copy-on-last-use]
  auto f = [m]() {};
^
std::move( )

This is suggested regardless of the C++ standard defined (unfortunately I 
didn't get a `-Wc++14-extensions` warning out of clang-tidy).

Also the fix-it will result in invalid code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137205

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


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-10 Thread Paul Eggert via cfe-commits

On 2022-11-10 09:16, Zack Weinberg wrote:

Changes to handle C23 built-in ‘bool’ better are under development but
the design has not yet been finalized.


[I'm cc'ing this to bug-gnulib too.]

To my mind this is the biggest outstanding issue in Autoconf as far as 
C23 goes, as the upgrade path for Autoconf's existing bool support is 
not entirely clear. As Florian mentioned, distros can't assume Autoconf 
upgrades when building other packages; that being said, we should get 
Autoconf's bool support fixed sooner rather than later as bool hassles 
will remain until Autoconf is fixed and these fixes are propagated to 
Autoconf's users.


Here's the main Autoconf issue issue with bool. Traditionally, Autoconf 
supported K&R C, C89, C99, etc. At some point (I'm not sure when), 
Autoconf started requiring C89 or later. Is it now OK for Autoconf to 
require C99 or later, as far as bool is concerned? If so, that'll 
considerably simplify the ongoing maintenance hassle for bool.


Requiring C99-or-later bool is the option that Gnulib has taken. Its 
'stdbool' module and its gl_C_BOOL macro assumes C99 or later, and as 
far as I know no Gnulib-using package is using Gnulib's 'stdbool-c99' 
module which we kept around in case somebody still needed bool to work 
atop a C89 system. (We considered supporting C23 bool atop C89 but it 
was too painful.)


If we follow Gnulib's lead, Autoconf will generate a config.h that does 
"#include " on pre-C23 systems, and this config.h will not 
not work on pre-C99 systems. This of course could in theory break some 
programs, just as compiling them with C23 can break them. But I don't 
see any better option at this point. And besides, what package outside 
of a museum still requires C89 and don't work with C99?


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


[PATCH] D135011: Add builtin_elementwise_sin and builtin_elementwise_cos

2022-11-10 Thread Xiang Li via Phabricator via cfe-commits
python3kgae added inline comments.



Comment at: clang/test/Sema/aarch64-sve-vector-trig-ops.c:4
+// RUN:   -disable-O0-optnone -o - -fsyntax-only %s -verify 
+
+#include 

Need limit to aarch64 enabled with
// REQUIRES: aarch64-registered-target



Comment at: clang/test/Sema/riscv-sve-vector-trig-ops.c:4
+// RUN:   -disable-O0-optnone -o - -fsyntax-only %s -verify 
+
+#include 

// REQUIRES: riscv-registered-target


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135011

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


[PATCH] D137205: [clang-tidy] Add performance-unnecessary-copy-on-last-use check

2022-11-10 Thread Oliver Stöneberg via Phabricator via cfe-commits
firewave added a comment.

I am also experiencing a crash:

  #include 
  #include 
  
  class Token;
  
  class Value {
public:
using ErrorPathItem = std::pair;
using ErrorPath = std::list;
  
explicit Value(long long val = 0)
{}
  
Value(const Token* c, long long val);
  
ErrorPath errorPath; // removing this fixes the crash
  };
  
  void setTokenValue(Value value);
  
  template
  static void valueFlowForwardConst(const ContainerOfValue& values)
  {
[&] {
for (Value value : values) {
setTokenValue(value);
}
}();
  }



  Stack dump:
  0.  Program arguments: /mnt/s/GitHub/llvm-project/build/bin/clang-tidy 
-checks=-*,-clang-analyzer-*,performance-unnecessary-copy-on-last-use -fix 
/mnt/s/___temp/input.cpp
  1.   parser at end of file
  2.  ASTMatcher: Processing 'performance-unnecessary-copy-on-last-use' 
against:
  CXXConstructExpr : 
  --- Bound Nodes Begin ---
  constructExpr - { CXXConstructExpr :  }
  param - { DeclRefExpr :  }
  --- Bound Nodes End ---
  Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH 
or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it):
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN4llvm3sys15PrintStackTraceERNS_11raw_ostreamEi+0x23)[0x7f2fcfefa393]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN4llvm3sys17RunSignalHandlersEv+0xee)[0x7f2fcfef82ee]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x3e3582f)[0x7f2fcfefa82f]
  /lib/x86_64-linux-gnu/libpthread.so.0(+0x14420)[0x7f2fcc06a420]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang4tidy11performance29UnnecessaryCopyOnLastUseCheck5checkERKNS_12ast_matchers11MatchFinder11MatchResultE+0xfe)[0x7f2fcd598d5e]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x2ffab94)[0x7f2fcf0bfb94]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang12ast_matchers8internal21BoundNodesTreeBuilder12visitMatchesEPNS2_7VisitorE+0x11c)[0x7f2fcf0ecdbc]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x2ffa5be)[0x7f2fcf0bf5be]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x3016505)[0x7f2fcf0db505]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x300b8a2)[0x7f2fcf0d08a2]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x3009a73)[0x7f2fcf0cea73]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x3009a73)[0x7f2fcf0cea73]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x30277c7)[0x7f2fcf0ec7c7]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x3002c02)[0x7f2fcf0c7c02]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x2ffd4f3)[0x7f2fcf0c24f3]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x30005b1)[0x7f2fcf0c55b1]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x2ffd2cb)[0x7f2fcf0c22cb]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x300522b)[0x7f2fcf0ca22b]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x2ffd7b1)[0x7f2fcf0c27b1]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang12ast_matchers11MatchFinder8matchASTERNS_10ASTContextE+0x357)[0x7f2fcf095f77]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang17MultiplexConsumer21HandleTranslationUnitERNS_10ASTContextE+0x2c)[0x7f2fce3dde8c]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang8ParseASTERNS_4SemaEbb+0x33f)[0x7f2fce5f4f5f]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang14FrontendAction7ExecuteEv+0x59)[0x7f2fce3a2799]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang16CompilerInstance13ExecuteActionERNS_14FrontendActionE+0x316)[0x7f2fce3151a6]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang7tooling21FrontendActionFactory13runInvocationESt10shared_ptrINS_18CompilerInvocationEEPNS_11FileManagerES2_INS_22PCHContainerOperationsEEPNS_18DiagnosticConsumerE+0x1ad)[0x7f2fcddc1d9d]
  /mnt/s/GitHub/llvm-project/build/bin/clang-tidy(+0x1cc85e6)[0x7f2fcdd8d5e6]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang7tooling14ToolInvocation13runInvocationEPKcPNS_6driver11CompilationESt10shared_ptrINS_18CompilerInvocationEES7_INS_22PCHContainerOperationsEE+0x11a)[0x7f2fcddc1afa]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang7tooling14ToolInvocation3runEv+0x56c)[0x7f2fcddc092c]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang7tooling9ClangTool3runEPNS0_10ToolActionE+0xf9b)[0x7f2fcddc34ab]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang4tidy12runClangTidyERNS0_16ClangTidyContextERKNS_7tooling19CompilationDatabaseEN4llvm8ArrayRefINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcENS7_18IntrusiveRefCntPtrINS7_3vfs17OverlayFileSystemEEEbbNS7_9StringRefE+0x3f7)[0x7f2fcdd88ba7]
  
/mnt/s/GitHub/llvm-project/build/bin/clang-tidy(_ZN5clang4tidy13clangTidyMainEiPPKc+0x2eaa)[0x7f2fcd0b9b8a]
  /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf3)[0x7f2fcbaa4083]
  /mnt/s/GitHub/l

[clang] f6b2529 - [clang-format] Add BreakBeforeInlineASMColon configuration

2022-11-10 Thread Björn Schäpers via cfe-commits

Author: Anastasiia Lukianenko
Date: 2022-11-10T22:31:09+01:00
New Revision: f6b252978c40bc437d8495218a69e3bd166b105b

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

LOG: [clang-format] Add BreakBeforeInlineASMColon configuration

If true, colons in ASM parameters will be placed after line breaks.

true:
asm volatile("string",
 :
 : val);

false:
asm volatile("string", : : val);

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/Format.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 5ac5f7d4189e..a90511734177 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2317,6 +2317,40 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+**BreakBeforeInlineASMColon** (``BreakBeforeInlineASMColonStyle``) 
:versionbadge:`clang-format 16`
+  The inline ASM colon style to use.
+
+  Possible values:
+
+  * ``BBIAS_Never`` (in configuration: ``Never``)
+No break before inline ASM colon.
+
+.. code-block:: c++
+
+   asm volatile("string", : : val);
+
+  * ``BBIAS_OnlyMultiline`` (in configuration: ``OnlyMultiline``)
+Break before inline ASM colon if the line length is longer than column
+limit.
+
+.. code-block:: c++
+
+   asm volatile("string", : : val);
+   asm("cmoveq %1, %2, %[result]"
+   : [result] "=r"(result)
+   : "r"(test), "r"(new), "[result]"(old));
+
+  * ``BBIAS_Always`` (in configuration: ``Always``)
+Always break before inline ASM colon.
+
+.. code-block:: c++
+
+   asm volatile("string",
+:
+: val);
+
+
+
 **BreakBeforeTernaryOperators** (``Boolean``) :versionbadge:`clang-format 3.7`
   If ``true``, ternary operators will be placed after line breaks.
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 40a7aecce762..276725406f29 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1752,6 +1752,35 @@ struct FormatStyle {
   /// \version 12
   BreakBeforeConceptDeclarationsStyle BreakBeforeConceptDeclarations;
 
+  /// Different ways to break ASM parameters.
+  enum BreakBeforeInlineASMColonStyle : int8_t {
+/// No break before inline ASM colon.
+/// \code
+///asm volatile("string", : : val);
+/// \endcode
+BBIAS_Never,
+/// Break before inline ASM colon if the line length is longer than column
+/// limit.
+/// \code
+///asm volatile("string", : : val);
+///asm("cmoveq %1, %2, %[result]"
+///: [result] "=r"(result)
+///: "r"(test), "r"(new), "[result]"(old));
+/// \endcode
+BBIAS_OnlyMultiline,
+/// Always break before inline ASM colon.
+/// \code
+///asm volatile("string",
+/// :
+/// : val);
+/// \endcode
+BBIAS_Always,
+  };
+
+  /// The inline ASM colon style to use.
+  /// \version 16
+  BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon;
+
   /// If ``true``, ternary operators will be placed after line breaks.
   /// \code
   ///true:
@@ -4016,6 +4045,7 @@ struct FormatStyle {
BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
BreakBeforeBraces == R.BreakBeforeBraces &&
BreakBeforeConceptDeclarations == R.BreakBeforeConceptDeclarations 
&&
+   BreakBeforeInlineASMColon == R.BreakBeforeInlineASMColon &&
BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
BreakConstructorInitializers == R.BreakConstructorInitializers &&
BreakInheritanceList == R.BreakInheritanceList &&

diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 3fa3e6bcbb56..26e48164acde 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -352,8 +352,12 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
 auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
 return LambdaBodyLength > getColumnLimit(State);
   }
-  if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
+  if (Current.MustBreakBefore ||
+  (Current.is(TT_InlineASMColon) &&
+   (Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always ||
+Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_OnlyMultiline))) 
{
 return t

[PATCH] D91950: [clang-format] Add BreakBeforeInlineASMColon configuration

2022-11-10 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf6b252978c40: [clang-format] Add BreakBeforeInlineASMColon 
configuration (authored by anastasiia_lukianenko, committed by 
HazardyKnusperkeks).

Changed prior to commit:
  https://reviews.llvm.org/D91950?vs=363418&id=474602#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91950

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -7259,6 +7259,59 @@
 format(Input, Style));
 }
 
+TEST_F(FormatTest, BreakBeforeInlineASMColon) {
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_Never;
+  /* Test the behaviour with long lines */
+  Style.ColumnLimit = 40;
+  verifyFormat("asm volatile(\"lng\",\n"
+   " : : val);",
+   Style);
+  verifyFormat("asm volatile(\"lng\",\n"
+   " : val1 : val2);",
+   Style);
+  verifyFormat("asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
+   "\"cpuid\\n\\t\"\n"
+   "\"xchgq\\t%%rbx %%rsi\\n\\t\",\n"
+   ": \"=a\" : \"a\");",
+   Style);
+  Style.ColumnLimit = 80;
+  verifyFormat("asm volatile(\"string\", : : val);", Style);
+  verifyFormat("asm volatile(\"string\", : val1 : val2);", Style);
+
+  Style.BreakBeforeInlineASMColon = FormatStyle::BBIAS_Always;
+  verifyFormat("asm volatile(\"string\",\n"
+   " :\n"
+   " : val);",
+   Style);
+  verifyFormat("asm volatile(\"string\",\n"
+   " : val1\n"
+   " : val2);",
+   Style);
+  /* Test the behaviour with long lines */
+  Style.ColumnLimit = 40;
+  verifyFormat("asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
+   "\"cpuid\\n\\t\"\n"
+   "\"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
+   ": \"=a\"(*rEAX)\n"
+   ": \"a\"(value));",
+   Style);
+  verifyFormat("asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
+   "\"cpuid\\n\\t\"\n"
+   "\"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
+   ":\n"
+   ": \"a\"(value));",
+   Style);
+  verifyFormat("asm volatile(\"lng\",\n"
+   " :\n"
+   " : val);",
+   Style);
+  verifyFormat("asm volatile(\"lng\",\n"
+   " : val1\n"
+   " : val2);",
+   Style);
+}
+
 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
   FormatStyle Style = getLLVMStyle();
   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -4443,6 +4443,11 @@
 }
   }
 
+  if (Line.startsWith(tok::kw_asm) && Right.is(TT_InlineASMColon) &&
+  Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always) {
+return true;
+  }
+
   // If the last token before a '}', ']', or ')' is a comma or a trailing
   // comment, the intention is to insert a line break after it in order to make
   // shuffling around entries easier. Import statements, especially in
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -229,6 +229,15 @@
   }
 };
 
+template <>
+struct ScalarEnumerationTraits {
+  static void enumeration(IO &IO,
+  FormatStyle::BreakBeforeInlineASMColonStyle &Value) {
+IO.enumCase(Value, "Never", FormatStyle::BBIAS_Never);
+IO.enumCase(Value, "OnlyMultiline", FormatStyle::BBIAS_OnlyMultiline);
+IO.enumCase(Value, "Always", FormatStyle::BBIAS_Always);
+  }
+};
 template <>
 struct ScalarEnumerationTraits {
   static void
@@ -827,6 +836,8 @@
 IO.mapOptional("BreakBeforeConceptDeclarations",
Style.BreakBeforeConceptDeclarations);
 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
+IO.mapOptional("BreakBeforeInlineASMColon",
+   Style.BreakBeforeInlineASMColon);
 IO.mapOptional("BreakBeforeTernaryOperators",
Style.BreakBeforeTernaryOperators);
 IO.mapOptional("BreakConstructorInitializers",
@@ -1263,6 +1274,7 @@
   LLVMStyle.Break

  1   2   >