[PATCH] D123538: [symbolizer] Parse DW_TAG_variable DIs to show line info for globals

2022-05-03 Thread James Henderson via Phabricator via cfe-commits
jhenderson added inline comments.



Comment at: llvm/test/tools/llvm-symbolizer/data-location.yaml:46
+## symbolized correctly. In future (if D123534 gets merged), this can be 
updated
+## to include a check that llvm-symbolize can also symbolize constant strings,
+## like `const char* string = "123456"` (and &"123456" should be symbolizable)

Nit


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123538

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


[PATCH] D124611: [RISCV][Clang] add more tests for clang driver. (NFC)

2022-05-03 Thread Zakk Chen via Phabricator via cfe-commits
khchen updated this revision to Diff 426587.
khchen added a comment.

Add zve64* tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124611

Files:
  clang/test/Driver/riscv-arch.c


Index: clang/test/Driver/riscv-arch.c
===
--- clang/test/Driver/riscv-arch.c
+++ clang/test/Driver/riscv-arch.c
@@ -412,6 +412,26 @@
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZFHMIN %s
 // RV32-ZFHMIN: "-target-feature" "+zfhmin"
 
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-NOFLAG 
%s
+// RV32-EXPERIMENTAL-NOFLAG: error: invalid arch name 'rv32izbt'
+// RV32-EXPERIMENTAL-NOFLAG: requires '-menable-experimental-extensions'
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt 
-menable-experimental-extensions -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-NOVERS 
%s
+// RV32-EXPERIMENTAL-NOVERS: error: invalid arch name 'rv32izbt'
+// RV32-EXPERIMENTAL-NOVERS: experimental extension requires explicit version 
number
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt0p1 
-menable-experimental-extensions -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-BADVERS 
%s
+// RV32-EXPERIMENTAL-BADVERS: error: invalid arch name 'rv32izbt0p1'
+// RV32-EXPERIMENTAL-BADVERS: unsupported version number 0.1 for experimental 
extension
+// RV32-EXPERIMENTAL-BADVERS: 'zbt'(this compiler supports 0.93)
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izbt0p93 
-menable-experimental-extensions -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck 
-check-prefix=RV32-EXPERIMENTAL-GOODVERS %s
+// RV32-EXPERIMENTAL-GOODVERS: "-target-feature" "+experimental-zbt"
+
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32izbb1p0 -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZBB %s
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32izbb -### %s \
@@ -494,3 +514,48 @@
 // RUN: %clang --target=riscv32-unknown-elf -march=rv32izk1p0 -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZK %s
 // RV32-ZK: "-target-feature" "+zk"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izfh1p0 -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-RV32-ZFH %s
+// CHECK-RV32-ZFH: "-target-feature" "+zfh"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izfhmin1p0 -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-RV32-ZFHMIN %s
+// CHECK-RV32-ZFHMIN: "-target-feature" "+zfhmin"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve32x0p1 -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32X-BADVERS %s
+// RV32-ZVE32X-BADVERS: error: invalid arch name 'rv32izve32x0p1'
+// RV32-ZVE32X-BADVERS: unsupported version number 0.1 for extension 'zve32x'
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve32x -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32X-GOODVERS %s
+// RV32-ZVE32X-GOODVERS: "-target-feature" "+zve32x"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve32f -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32F-REQUIRE-F %s
+// RV32-ZVE32F-REQUIRE-F: error: invalid arch name 'rv32izve32f', zve32f 
requires f or zfinx extension to also be specified
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifzve32f -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE32F-GOOD %s
+// RV32-ZVE32F-GOOD: "-target-feature" "+zve32f"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve64x -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64X %s
+// RV32-ZVE64X: "-target-feature" "+zve64x"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32izve64f -### %s -c 2>&1 
| \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64F-REQUIRE-F %s
+// RV32-ZVE64F-REQUIRE-F: error: invalid arch name 'rv32izve64f', zve32f 
requires f or zfinx extension to also be specified
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifzve64f -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64F-GOOD %s
+// RV32-ZVE64F-GOOD: "-target-feature" "+zve64f"
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifzve64d -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64D-REQUIRE-D %s
+// RV32-ZVE64D-REQUIRE-D: error: invalid arch name 'rv32ifzve64d', zve64d 
requires d or zdinx extension to also be specified
+
+// RUN: %clang --target=riscv32-unknown-elf -march=rv32ifdzve64d -### %s -c 
2>&1 | \
+// RUN:   FileCheck -check-prefix=RV32-ZVE64D-GOOD %s
+// RV32-ZVE64D-GOOD: "-target-feature" "+zve64d"


Index: clang/test/Driver/riscv-arch.c
===
--- clang/test/Driver/riscv-arch.c
+++ clang/test/Driver/riscv-arch.c
@@ -412,6 +412,26 @@
 // RUN:

[PATCH] D124621: [Analyzer] Fix assumptions about const field with member-initializer

2022-05-03 Thread Marco Antognini via Phabricator via cfe-commits
mantognini added a comment.

In D124621#3486004 , @r.stahl wrote:

> I can confirm the issue with my patch, so this piece of code needs to be 
> removed.
>
> As long as the following test still succeeds, this looks good to me. Back 
> then, the analyzer was not able to cover that case without that addition.
>
> https://github.com/llvm/llvm-project/blob/main/clang/test/Analysis/globals.cpp#L110

Thanks for digging in the past. I confirm I didn't see any regression in 
existing tests, so I'll land it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124621

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


[PATCH] D124719: [docs] PCH usage documentation update

2022-05-03 Thread Ivan Murashko via Phabricator via cfe-commits
ivanmurashko updated this revision to Diff 426588.
ivanmurashko added a comment.

Some clarifications for the direct include example were added


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124719

Files:
  clang/docs/UsersManual.rst


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -1219,23 +1219,22 @@
 Using a PCH File
 
 
-A PCH file can then be used as a prefix header when a :option:`-include`
+A PCH file can then be used as a prefix header when a :option:`-include-pch`
 option is passed to ``clang``:
 
 .. code-block:: console
 
-  $ clang -include test.h test.c -o test
+  $ clang -include-pch test.h.pch test.c -o test
 
-The ``clang`` driver will first check if a PCH file for ``test.h`` is
+The ``clang`` driver will check if the PCH file ``test.h.pch`` is
 available; if so, the contents of ``test.h`` (and the files it includes)
-will be processed from the PCH file. Otherwise, Clang falls back to
-directly processing the content of ``test.h``. This mirrors the behavior
-of GCC.
+will be processed from the PCH file. Otherwise, Clang will report an error.
 
 .. note::
 
   Clang does *not* automatically use PCH files for headers that are directly
-  included within a source file. For example:
+  included within a source file or indirectly via :option:`-include`.
+  For example:
 
   .. code-block:: console
 
@@ -1246,8 +1245,8 @@
 
   In this example, ``clang`` will not automatically use the PCH file for
   ``test.h`` since ``test.h`` was included directly in the source file and not
-  specified on the command line using :option:`-include`.
-
+  specified on the command line using :option:`-include-pch`.
+  
 Relocatable PCH Files
 ^
 


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -1219,23 +1219,22 @@
 Using a PCH File
 
 
-A PCH file can then be used as a prefix header when a :option:`-include`
+A PCH file can then be used as a prefix header when a :option:`-include-pch`
 option is passed to ``clang``:
 
 .. code-block:: console
 
-  $ clang -include test.h test.c -o test
+  $ clang -include-pch test.h.pch test.c -o test
 
-The ``clang`` driver will first check if a PCH file for ``test.h`` is
+The ``clang`` driver will check if the PCH file ``test.h.pch`` is
 available; if so, the contents of ``test.h`` (and the files it includes)
-will be processed from the PCH file. Otherwise, Clang falls back to
-directly processing the content of ``test.h``. This mirrors the behavior
-of GCC.
+will be processed from the PCH file. Otherwise, Clang will report an error.
 
 .. note::
 
   Clang does *not* automatically use PCH files for headers that are directly
-  included within a source file. For example:
+  included within a source file or indirectly via :option:`-include`.
+  For example:
 
   .. code-block:: console
 
@@ -1246,8 +1245,8 @@
 
   In this example, ``clang`` will not automatically use the PCH file for
   ``test.h`` since ``test.h`` was included directly in the source file and not
-  specified on the command line using :option:`-include`.
-
+  specified on the command line using :option:`-include-pch`.
+  
 Relocatable PCH Files
 ^
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124621: [Analyzer] Fix assumptions about const field with member-initializer

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

In D124621#3487507 , @mantognini 
wrote:

> Thanks for digging in the past. I confirm I didn't see any regression in 
> existing tests, so I'll land it.

Go for it!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124621

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


[clang] f6112f4 - [docs] PCH usage documentation update

2022-05-03 Thread Ivan Murashko via cfe-commits

Author: Ivan Murashko
Date: 2022-05-03T08:26:13+01:00
New Revision: f6112f490cfeed05b42ae33cc994292000aee0da

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

LOG: [docs] PCH usage documentation update

The documentation has an incorrect example of PCH files usage via `-include` 
option. The possibility has not been available since [llvm-svn: 
174385](https://reviews.llvm.org/rG48b72d81c8968f3d342557582db986a60aef2c54).

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

Added: 


Modified: 
clang/docs/UsersManual.rst

Removed: 




diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 2dc32448f959b..402029c8a64b3 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -1219,23 +1219,22 @@ for generating PCH files:
 Using a PCH File
 
 
-A PCH file can then be used as a prefix header when a :option:`-include`
+A PCH file can then be used as a prefix header when a :option:`-include-pch`
 option is passed to ``clang``:
 
 .. code-block:: console
 
-  $ clang -include test.h test.c -o test
+  $ clang -include-pch test.h.pch test.c -o test
 
-The ``clang`` driver will first check if a PCH file for ``test.h`` is
+The ``clang`` driver will check if the PCH file ``test.h.pch`` is
 available; if so, the contents of ``test.h`` (and the files it includes)
-will be processed from the PCH file. Otherwise, Clang falls back to
-directly processing the content of ``test.h``. This mirrors the behavior
-of GCC.
+will be processed from the PCH file. Otherwise, Clang will report an error.
 
 .. note::
 
   Clang does *not* automatically use PCH files for headers that are directly
-  included within a source file. For example:
+  included within a source file or indirectly via :option:`-include`.
+  For example:
 
   .. code-block:: console
 
@@ -1246,7 +1245,7 @@ of GCC.
 
   In this example, ``clang`` will not automatically use the PCH file for
   ``test.h`` since ``test.h`` was included directly in the source file and not
-  specified on the command line using :option:`-include`.
+  specified on the command line using :option:`-include-pch`.
 
 Relocatable PCH Files
 ^



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


[PATCH] D124719: [docs] PCH usage documentation update

2022-05-03 Thread Ivan Murashko 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 rGf6112f490cfe: [docs] PCH usage documentation update 
(authored by ivanmurashko).

Changed prior to commit:
  https://reviews.llvm.org/D124719?vs=426588&id=426589#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124719

Files:
  clang/docs/UsersManual.rst


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -1219,23 +1219,22 @@
 Using a PCH File
 
 
-A PCH file can then be used as a prefix header when a :option:`-include`
+A PCH file can then be used as a prefix header when a :option:`-include-pch`
 option is passed to ``clang``:
 
 .. code-block:: console
 
-  $ clang -include test.h test.c -o test
+  $ clang -include-pch test.h.pch test.c -o test
 
-The ``clang`` driver will first check if a PCH file for ``test.h`` is
+The ``clang`` driver will check if the PCH file ``test.h.pch`` is
 available; if so, the contents of ``test.h`` (and the files it includes)
-will be processed from the PCH file. Otherwise, Clang falls back to
-directly processing the content of ``test.h``. This mirrors the behavior
-of GCC.
+will be processed from the PCH file. Otherwise, Clang will report an error.
 
 .. note::
 
   Clang does *not* automatically use PCH files for headers that are directly
-  included within a source file. For example:
+  included within a source file or indirectly via :option:`-include`.
+  For example:
 
   .. code-block:: console
 
@@ -1246,7 +1245,7 @@
 
   In this example, ``clang`` will not automatically use the PCH file for
   ``test.h`` since ``test.h`` was included directly in the source file and not
-  specified on the command line using :option:`-include`.
+  specified on the command line using :option:`-include-pch`.
 
 Relocatable PCH Files
 ^


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -1219,23 +1219,22 @@
 Using a PCH File
 
 
-A PCH file can then be used as a prefix header when a :option:`-include`
+A PCH file can then be used as a prefix header when a :option:`-include-pch`
 option is passed to ``clang``:
 
 .. code-block:: console
 
-  $ clang -include test.h test.c -o test
+  $ clang -include-pch test.h.pch test.c -o test
 
-The ``clang`` driver will first check if a PCH file for ``test.h`` is
+The ``clang`` driver will check if the PCH file ``test.h.pch`` is
 available; if so, the contents of ``test.h`` (and the files it includes)
-will be processed from the PCH file. Otherwise, Clang falls back to
-directly processing the content of ``test.h``. This mirrors the behavior
-of GCC.
+will be processed from the PCH file. Otherwise, Clang will report an error.
 
 .. note::
 
   Clang does *not* automatically use PCH files for headers that are directly
-  included within a source file. For example:
+  included within a source file or indirectly via :option:`-include`.
+  For example:
 
   .. code-block:: console
 
@@ -1246,7 +1245,7 @@
 
   In this example, ``clang`` will not automatically use the PCH file for
   ``test.h`` since ``test.h`` was included directly in the source file and not
-  specified on the command line using :option:`-include`.
+  specified on the command line using :option:`-include-pch`.
 
 Relocatable PCH Files
 ^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120495: [clang][dataflow] Add transfer functions for structured bindings

2022-05-03 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added inline comments.
Herald added a project: All.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:80
+///
+/// FIXME: Consider adding support for structured bindings to the CFG builder.
+class DecompositionVisitor : public ConstStmtVisitor {

xazax.hun wrote:
> Did you look into how hard would it be to add structured bindings to the CFG 
> builder? If the effort is comparable to this patch (and not significantly 
> bigger), it might be better to do that work instead of spending effort on 
> some temporary workaround. What do you think?
Circling back to this after a while. I believe we explored changing the CFG 
briefly, but don't have a fully fleshed out proposal for it. I recently noticed 
https://discourse.llvm.org/t/implement-support-for-c-17-structured-bindings-in-the-clang-static-analyzer/60588.
 It seems that part of the project is exploring necessary changes to the CFG. 
What do you think about submitting this patch with local pattern matching and 
revisiting that once the GSoC project completes?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120495

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


[PATCH] D124827: [pseudo] Simplify the forest dump, NFC.

2022-05-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a project: All.
hokein requested review of this revision.
Herald added a subscriber: alextsao1999.
Herald added a project: clang-tools-extra.

The code was written to handle nullable grammar, and we disallow
nullable grammar, so it is not necessary to keep it around.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124827

Files:
  clang-tools-extra/pseudo/lib/Forest.cpp


Index: clang-tools-extra/pseudo/lib/Forest.cpp
===
--- clang-tools-extra/pseudo/lib/Forest.cpp
+++ clang-tools-extra/pseudo/lib/Forest.cpp
@@ -74,16 +74,13 @@
 } else if (P->kind() == Sequence) {
   Children = P->elements();
   if (Abbreviated) {
-if (P->startTokenIndex() == End)
-  return;
-for (size_t I = 0; I < Children.size(); ++I)
-  if (Children[I]->startTokenIndex() == P->startTokenIndex() &&
-  EndOfElement(I) == End) {
-return Dump(
-Children[I], End,
-/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
-LineDec);
-  }
+if (Children.size() == 1) {
+  assert(Children[0]->startTokenIndex() == P->startTokenIndex() &&
+ EndOfElement(0) == End);
+  return Dump(Children[0], End,
+  
/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
+  LineDec);
+}
   }
 }
 


Index: clang-tools-extra/pseudo/lib/Forest.cpp
===
--- clang-tools-extra/pseudo/lib/Forest.cpp
+++ clang-tools-extra/pseudo/lib/Forest.cpp
@@ -74,16 +74,13 @@
 } else if (P->kind() == Sequence) {
   Children = P->elements();
   if (Abbreviated) {
-if (P->startTokenIndex() == End)
-  return;
-for (size_t I = 0; I < Children.size(); ++I)
-  if (Children[I]->startTokenIndex() == P->startTokenIndex() &&
-  EndOfElement(I) == End) {
-return Dump(
-Children[I], End,
-/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
-LineDec);
-  }
+if (Children.size() == 1) {
+  assert(Children[0]->startTokenIndex() == P->startTokenIndex() &&
+ EndOfElement(0) == End);
+  return Dump(Children[0], End,
+  /*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
+  LineDec);
+}
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124669: [flang][driver] Add support for -save-temps

2022-05-03 Thread Diana Picus via Phabricator via cfe-commits
rovka added a comment.

I think I confused myself yesterday, it does make sense to add 
-fno-integrated-as for this. Could we add a test for it independent of 
save-temps?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124669

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


[PATCH] D124831: [pseudo] Use a real language option in the parser.

2022-05-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a project: All.
hokein requested review of this revision.
Herald added a subscriber: alextsao1999.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124831

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/Token.h
  clang-tools-extra/pseudo/lib/Token.cpp
  clang-tools-extra/pseudo/test/glr.cpp
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp

Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -53,14 +53,12 @@
 int main(int argc, char *argv[]) {
   llvm::cl::ParseCommandLineOptions(argc, argv, "");
 
-  clang::LangOptions LangOpts; // FIXME: use real options.
-  LangOpts.CPlusPlus = 1;
+  clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
   llvm::Optional RawStream;
   llvm::Optional DirectiveStructure;
   llvm::Optional ParseableStream;
   if (Source.getNumOccurrences()) {
 std::string Text = readOrDie(Source);
-clang::LangOptions LangOpts; // FIXME: use real options.
 RawStream = clang::pseudo::lex(Text, LangOpts);
 DirectiveStructure = clang::pseudo::DirectiveTree::parse(*RawStream);
 clang::pseudo::chooseConditionalBranches(*DirectiveStructure, *RawStream);
Index: clang-tools-extra/pseudo/test/glr.cpp
===
--- clang-tools-extra/pseudo/test/glr.cpp
+++ clang-tools-extra/pseudo/test/glr.cpp
@@ -21,3 +21,15 @@
 // CHECK-NEXT:   │ └─ptr-declarator~IDENTIFIER := tok[7]
 // CHECK-NEXT:   └─; := tok[8]
 }
+
+bool operator<();
+// CHECK:  declaration~simple-declaration := decl-specifier-seq init-declarator-list ;
+// CHECK-NEXT: ├─decl-specifier-seq~BOOL
+// CHECK-NEXT: ├─init-declarator-list~noptr-declarator := noptr-declarator parameters-and-qualifiers
+// CHECK-NEXT: │ ├─noptr-declarator~operator-function-id := OPERATOR operator-name
+// CHECK-NEXT: │ │ ├─OPERATOR
+// CHECK-NEXT: │ │ └─operator-name~<
+// CHECK-NEXT: │ └─parameters-and-qualifiers := ( )
+// CHECK-NEXT: │   ├─(
+// CHECK-NEXT: │   └─)
+// CHECK-NEXT: └─;
Index: clang-tools-extra/pseudo/lib/Token.cpp
===
--- clang-tools-extra/pseudo/lib/Token.cpp
+++ clang-tools-extra/pseudo/lib/Token.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang-pseudo/Token.h"
+#include "clang/Basic/LangOptions.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Format.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -92,6 +93,28 @@
 OS << '\n';
 }
 
+clang::LangOptions genericLangOpts(clang::Language Lang,
+   clang::LangStandard::Kind Standard) {
+  clang::LangOptions Opts;
+  std::vector UnusedIncludes;
+  LangOptions::setLangDefaults(Opts, Lang, llvm::Triple(), UnusedIncludes,
+   Standard);
+
+  // Some options are "on by default", but e.g. at the driver level.
+  if (Opts.CPlusPlus)
+Opts.CXXOperatorNames = true;
+  if (Opts.CPlusPlus20)
+Opts.Coroutines = true;
+
+  // Some options are off by default, but define keywords we want to tolerate.
+  if (Opts.CPlusPlus)
+Opts.MicrosoftExt = true;  // kw__try, kw__finally
+  Opts.DeclSpecKeyword = true; // __declspec
+  Opts.WChar = true;
+
+  return Opts;
+}
+
 TokenStream stripComments(const TokenStream &Input) {
   TokenStream Out;
   for (const Token &T : Input.tokens()) {
Index: clang-tools-extra/pseudo/include/clang-pseudo/Token.h
===
--- clang-tools-extra/pseudo/include/clang-pseudo/Token.h
+++ clang-tools-extra/pseudo/include/clang-pseudo/Token.h
@@ -29,6 +29,7 @@
 #define CLANG_PSEUDO_TOKEN_H
 
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangStandard.h"
 #include "clang/Basic/TokenKinds.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/raw_ostream.h"
@@ -193,6 +194,10 @@
   /// The text() of such tokens will contain the raw trigrah.
   NeedsCleaning = 1 << 1,
 };
+/// A generic lang options suitable for lexing/parsing a langage.
+clang::LangOptions genericLangOpts(
+clang::Language = clang::Language::CXX,
+clang::LangStandard::Kind = clang::LangStandard::lang_unspecified);
 
 /// Derives a token stream by decoding escapes, interpreting raw_identifiers and
 /// splitting the greatergreater token.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c819dce - [clang-format] Add a regression test for aligning macros with keywords.

2022-05-03 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-05-03T11:09:38+02:00
New Revision: c819dce2d304817ae7f47628067092f4353a148e

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

LOG: [clang-format] Add a regression test for aligning macros with keywords.

Test from issue https://github.com/llvm/llvm-project/issues/54953.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index da25395b7df49..37f32691a1d36 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -16030,6 +16030,10 @@ TEST_F(FormatTest, AlignConsecutiveMacros) {
"#define ccc  (5)",
Style);
 
+  verifyFormat("#define true  1\n"
+   "#define false 0",
+   Style);
+
   verifyFormat("#define f(x) (x * x)\n"
"#define fff(x, y, z) (x * y + z)\n"
"#define (x, y)   (x - y)",



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


[clang] 68ee5ec - [Analyzer] Fix assumptions about const field with member-initializer

2022-05-03 Thread Marco Antognini via cfe-commits

Author: Marco Antognini
Date: 2022-05-03T11:27:45+02:00
New Revision: 68ee5ec07d4a169baf287acad9ad7fa85d764a22

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

LOG: [Analyzer] Fix assumptions about const field with member-initializer

Essentially, having a default member initializer for a constant member
does not necessarily imply the member will have the given default value.

Remove part of a2e053638bbf ([analyzer] Treat more const variables and
fields as known contants., 2018-05-04).

Fix #47878

Reviewed By: r.stahl, steakhal

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

Added: 
clang/test/Analysis/cxx-member-initializer-const-field.cpp

Modified: 
clang/lib/StaticAnalyzer/Core/RegionStore.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp 
b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index 9d062ddb3e8c1..20b167c9b3b22 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1983,15 +1983,9 @@ SVal 
RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
   if (const Optional &V = B.getDirectBinding(R))
 return *V;
 
-  // Is the field declared constant and has an in-class initializer?
+  // If the containing record was initialized, try to get its constant value.
   const FieldDecl *FD = R->getDecl();
   QualType Ty = FD->getType();
-  if (Ty.isConstQualified())
-if (const Expr *Init = FD->getInClassInitializer())
-  if (Optional V = svalBuilder.getConstantVal(Init))
-return *V;
-
-  // If the containing record was initialized, try to get its constant value.
   const MemRegion* superR = R->getSuperRegion();
   if (const auto *VR = dyn_cast(superR)) {
 const VarDecl *VD = VR->getDecl();

diff  --git a/clang/test/Analysis/cxx-member-initializer-const-field.cpp 
b/clang/test/Analysis/cxx-member-initializer-const-field.cpp
new file mode 100644
index 0..f0abbddbc4441
--- /dev/null
+++ b/clang/test/Analysis/cxx-member-initializer-const-field.cpp
@@ -0,0 +1,120 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+
+// This tests false-positive issues related to PR48534.
+//
+// Essentially, having a default member initializer for a constant member does
+// not necessarily imply the member will have the given default value.
+
+struct WithConstructor {
+  int *const ptr = nullptr;
+  WithConstructor(int *x) : ptr(x) {}
+
+  static auto compliant() {
+WithConstructor c(new int);
+return *(c.ptr); // no warning
+  }
+
+  static auto compliantWithParam(WithConstructor c) {
+return *(c.ptr); // no warning
+  }
+
+  static auto issue() {
+WithConstructor c(nullptr);
+return *(c.ptr); // expected-warning{{Dereference of null pointer (loaded 
from field 'ptr')}}
+  }
+};
+
+struct RegularAggregate {
+  int *const ptr = nullptr;
+
+  static int compliant() {
+RegularAggregate c{new int};
+return *(c.ptr); // no warning
+  }
+
+  static int issue() {
+RegularAggregate c;
+return *(c.ptr); // expected-warning{{Dereference of null pointer (loaded 
from field 'ptr')}}
+  }
+};
+
+struct WithConstructorAndArithmetic {
+  int const i = 0;
+  WithConstructorAndArithmetic(int x) : i(x + 1) {}
+
+  static int compliant(int y) {
+WithConstructorAndArithmetic c(0);
+return y / c.i; // no warning
+  }
+
+  static int issue(int y) {
+WithConstructorAndArithmetic c(-1);
+return y / c.i; // expected-warning{{Division by zero}}
+  }
+};
+
+struct WithConstructorDeclarationOnly {
+  int const i = 0;
+  WithConstructorDeclarationOnly(int x); // definition not visible.
+
+  static int compliant1(int y) {
+WithConstructorDeclarationOnly c(0);
+return y / c.i; // no warning
+  }
+
+  static int compliant2(int y) {
+WithConstructorDeclarationOnly c(-1);
+return y / c.i; // no warning
+  }
+};
+
+// NonAggregateFP is not an aggregate (j is a private non-static field) and 
has no custom constructor.
+// So we know i and j will always be 0 and 42, respectively.
+// That being said, this is not implemented because it is deemed too rare to 
be worth the complexity.
+struct NonAggregateFP {
+public:
+  int const i = 0;
+
+private:
+  int const j = 42;
+
+public:
+  static int falsePositive1(NonAggregateFP c) {
+return 10 / c.i; // FIXME: Currently, no warning.
+  }
+
+  static int falsePositive2(NonAggregateFP c) {
+return 10 / (c.j - 42); // FIXME: Currently, no warning.
+  }
+};
+
+struct NonAggregate {
+public:
+  int const i = 0;
+
+private:
+  int const j = 42;
+
+  NonAggregate(NonAggregate const &); // not provided, could set i and j to 
arbitrary values.
+
+public:
+  static int compliant1(NonAggregate c) {
+return 10 / c.i; // no warning
+  }
+
+  static int compliant2(NonAg

[PATCH] D124621: [Analyzer] Fix assumptions about const field with member-initializer

2022-05-03 Thread Marco Antognini via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG68ee5ec07d4a: [Analyzer] Fix assumptions about const field 
with member-initializer (authored by mantognini).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124621

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/cxx-member-initializer-const-field.cpp

Index: clang/test/Analysis/cxx-member-initializer-const-field.cpp
===
--- /dev/null
+++ clang/test/Analysis/cxx-member-initializer-const-field.cpp
@@ -0,0 +1,120 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+
+// This tests false-positive issues related to PR48534.
+//
+// Essentially, having a default member initializer for a constant member does
+// not necessarily imply the member will have the given default value.
+
+struct WithConstructor {
+  int *const ptr = nullptr;
+  WithConstructor(int *x) : ptr(x) {}
+
+  static auto compliant() {
+WithConstructor c(new int);
+return *(c.ptr); // no warning
+  }
+
+  static auto compliantWithParam(WithConstructor c) {
+return *(c.ptr); // no warning
+  }
+
+  static auto issue() {
+WithConstructor c(nullptr);
+return *(c.ptr); // expected-warning{{Dereference of null pointer (loaded from field 'ptr')}}
+  }
+};
+
+struct RegularAggregate {
+  int *const ptr = nullptr;
+
+  static int compliant() {
+RegularAggregate c{new int};
+return *(c.ptr); // no warning
+  }
+
+  static int issue() {
+RegularAggregate c;
+return *(c.ptr); // expected-warning{{Dereference of null pointer (loaded from field 'ptr')}}
+  }
+};
+
+struct WithConstructorAndArithmetic {
+  int const i = 0;
+  WithConstructorAndArithmetic(int x) : i(x + 1) {}
+
+  static int compliant(int y) {
+WithConstructorAndArithmetic c(0);
+return y / c.i; // no warning
+  }
+
+  static int issue(int y) {
+WithConstructorAndArithmetic c(-1);
+return y / c.i; // expected-warning{{Division by zero}}
+  }
+};
+
+struct WithConstructorDeclarationOnly {
+  int const i = 0;
+  WithConstructorDeclarationOnly(int x); // definition not visible.
+
+  static int compliant1(int y) {
+WithConstructorDeclarationOnly c(0);
+return y / c.i; // no warning
+  }
+
+  static int compliant2(int y) {
+WithConstructorDeclarationOnly c(-1);
+return y / c.i; // no warning
+  }
+};
+
+// NonAggregateFP is not an aggregate (j is a private non-static field) and has no custom constructor.
+// So we know i and j will always be 0 and 42, respectively.
+// That being said, this is not implemented because it is deemed too rare to be worth the complexity.
+struct NonAggregateFP {
+public:
+  int const i = 0;
+
+private:
+  int const j = 42;
+
+public:
+  static int falsePositive1(NonAggregateFP c) {
+return 10 / c.i; // FIXME: Currently, no warning.
+  }
+
+  static int falsePositive2(NonAggregateFP c) {
+return 10 / (c.j - 42); // FIXME: Currently, no warning.
+  }
+};
+
+struct NonAggregate {
+public:
+  int const i = 0;
+
+private:
+  int const j = 42;
+
+  NonAggregate(NonAggregate const &); // not provided, could set i and j to arbitrary values.
+
+public:
+  static int compliant1(NonAggregate c) {
+return 10 / c.i; // no warning
+  }
+
+  static int compliant2(NonAggregate c) {
+return 10 / (c.j - 42); // no warning
+  }
+};
+
+struct WithStaticMember {
+  static int const i = 0;
+
+  static int issue1(WithStaticMember c) {
+return 10 / c.i; // expected-warning{{division by zero is undefined}} expected-warning{{Division by zero}}
+  }
+
+  static int issue2() {
+return 10 / WithStaticMember::i; // expected-warning{{division by zero is undefined}} expected-warning{{Division by zero}}
+  }
+};
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1983,15 +1983,9 @@
   if (const Optional &V = B.getDirectBinding(R))
 return *V;
 
-  // Is the field declared constant and has an in-class initializer?
+  // If the containing record was initialized, try to get its constant value.
   const FieldDecl *FD = R->getDecl();
   QualType Ty = FD->getType();
-  if (Ty.isConstQualified())
-if (const Expr *Init = FD->getInClassInitializer())
-  if (Optional V = svalBuilder.getConstantVal(Init))
-return *V;
-
-  // If the containing record was initialized, try to get its constant value.
   const MemRegion* superR = R->getSuperRegion();
   if (const auto *VR = dyn_cast(superR)) {
 const VarDecl *VD = VR->getDecl();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124613: In MSVC compatibility mode, friend function declarations behave as function declarations

2022-05-03 Thread Marco Antognini via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGad47114ad850: In MSVC compatibility mode, friend function 
declarations behave as function… (authored by frederic-tingaud-sonarsource, 
committed by mantognini).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124613

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaCXX/ms-friend-function-decl.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -2658,7 +2658,10 @@
   getTuDecl("struct X { friend void f(); };", Lang_CXX03, "input0.cc");
   auto *FromD = FirstDeclMatcher().match(FromTU, FunctionPattern);
   ASSERT_TRUE(FromD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  ASSERT_FALSE(FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  // Before CXX20, MSVC treats friend function declarations as function
+  // declarations
+  ASSERT_EQ(FromTU->getLangOpts().MSVCCompat,
+FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   {
 auto FromName = FromD->getDeclName();
 auto *Class = FirstDeclMatcher().match(FromTU, ClassPattern);
@@ -2702,7 +2705,10 @@
   auto *FromNormal =
   LastDeclMatcher().match(FromTU, FunctionPattern);
   ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  ASSERT_FALSE(FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  // Before CXX20, MSVC treats friend function declarations as function
+  // declarations
+  ASSERT_EQ(FromTU->getLangOpts().MSVCCompat,
+FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   ASSERT_FALSE(FromNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
   ASSERT_TRUE(FromNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary));
 
@@ -2793,7 +2799,10 @@
 
   ASSERT_TRUE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   ASSERT_FALSE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  ASSERT_FALSE(FromFriendF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  // Before CXX20, MSVC treats friend function declarations as function
+  // declarations
+  ASSERT_EQ(FromFriendTU->getLangOpts().MSVCCompat,
+FromFriendF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   ASSERT_TRUE(FromFriendF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
   auto LookupRes = FromNormalTU->noload_lookup(FromNormalName);
   ASSERT_TRUE(LookupRes.isSingleResult());
Index: clang/test/SemaCXX/ms-friend-function-decl.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/ms-friend-function-decl.cpp
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -std=c++03 -fms-compatibility -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=modern %s
+#if __cplusplus < 202002L
+// expected-no-diagnostics
+#endif
+
+namespace ns {
+
+class C {
+public:
+  template 
+  friend void funtemp();
+
+  friend void fun();
+
+  void test() {
+::ns::fun(); // modern-error {{no member named 'fun' in namespace 'ns'}}
+
+// modern-error@+3 {{no member named 'funtemp' in namespace 'ns'}}
+// modern-error@+2 {{expected '(' for function-style cast or type construction}}
+// modern-error@+1 {{expected expression}}
+::ns::funtemp();
+  }
+};
+
+void fun() {
+}
+
+template 
+void funtemp() {}
+
+} // namespace ns
+
+class Glob {
+public:
+  friend void funGlob();
+
+  void test() {
+funGlob(); // modern-error {{use of undeclared identifier 'funGlob'}}
+  }
+};
+
+void funGlob() {
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -9632,11 +9632,15 @@
 }
 
 if (isFriend) {
+  // In MSVC mode for older versions of the standard, friend function
+  // declarations behave as declarations
+  bool PerformFriendInjection =
+  getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20;
   if (FunctionTemplate) {
-FunctionTemplate->setObjectOfFriendDecl();
+FunctionTemplate->setObjectOfFriendDecl(PerformFriendInjection);
 FunctionTemplate->setAccess(AS_public);
   }
-  NewFD->setObjectOfFriendDecl();
+  NewFD->setObjectOfFriendDecl(PerformFriendInjection);
   NewFD->setAccess(AS_public);
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ad47114 - In MSVC compatibility mode, friend function declarations behave as function declarations

2022-05-03 Thread Marco Antognini via cfe-commits

Author: Fred Tingaud
Date: 2022-05-03T11:31:50+02:00
New Revision: ad47114ad8500c78046161d492ac13a8e3e610eb

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

LOG: In MSVC compatibility mode, friend function declarations behave as 
function declarations

Before C++20, MSVC treated any friend function declaration as a function 
declaration, so the following code would compile despite funGlob being declared 
after its first call:

```
class Glob {
public:
  friend void funGlob();

  void test() {
funGlob();
  }
};

void funGlob() {}
```
This proposed patch mimics the MSVC behavior when in MSVC compatibility mode

Reviewed By: rnk

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

Added: 
clang/test/SemaCXX/ms-friend-function-decl.cpp

Modified: 
clang/lib/Sema/SemaDecl.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5890bbc7d574b..f2b87c6d2e37e 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -9632,11 +9632,15 @@ Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, 
DeclContext *DC,
 }
 
 if (isFriend) {
+  // In MSVC mode for older versions of the standard, friend function
+  // declarations behave as declarations
+  bool PerformFriendInjection =
+  getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20;
   if (FunctionTemplate) {
-FunctionTemplate->setObjectOfFriendDecl();
+FunctionTemplate->setObjectOfFriendDecl(PerformFriendInjection);
 FunctionTemplate->setAccess(AS_public);
   }
-  NewFD->setObjectOfFriendDecl();
+  NewFD->setObjectOfFriendDecl(PerformFriendInjection);
   NewFD->setAccess(AS_public);
 }
 

diff  --git a/clang/test/SemaCXX/ms-friend-function-decl.cpp 
b/clang/test/SemaCXX/ms-friend-function-decl.cpp
new file mode 100644
index 0..d146305800738
--- /dev/null
+++ b/clang/test/SemaCXX/ms-friend-function-decl.cpp
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -std=c++03 -fms-compatibility -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=modern 
%s
+#if __cplusplus < 202002L
+// expected-no-diagnostics
+#endif
+
+namespace ns {
+
+class C {
+public:
+  template 
+  friend void funtemp();
+
+  friend void fun();
+
+  void test() {
+::ns::fun(); // modern-error {{no member named 'fun' in namespace 'ns'}}
+
+// modern-error@+3 {{no member named 'funtemp' in namespace 'ns'}}
+// modern-error@+2 {{expected '(' for function-style cast or type 
construction}}
+// modern-error@+1 {{expected expression}}
+::ns::funtemp();
+  }
+};
+
+void fun() {
+}
+
+template 
+void funtemp() {}
+
+} // namespace ns
+
+class Glob {
+public:
+  friend void funGlob();
+
+  void test() {
+funGlob(); // modern-error {{use of undeclared identifier 'funGlob'}}
+  }
+};
+
+void funGlob() {
+}

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 856010cd4d036..2cda013a45edc 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -2658,7 +2658,10 @@ TEST_P(ImportFriendFunctions, Lookup) {
   getTuDecl("struct X { friend void f(); };", Lang_CXX03, "input0.cc");
   auto *FromD = FirstDeclMatcher().match(FromTU, 
FunctionPattern);
   ASSERT_TRUE(FromD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  ASSERT_FALSE(FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  // Before CXX20, MSVC treats friend function declarations as function
+  // declarations
+  ASSERT_EQ(FromTU->getLangOpts().MSVCCompat,
+FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   {
 auto FromName = FromD->getDeclName();
 auto *Class = FirstDeclMatcher().match(FromTU, 
ClassPattern);
@@ -2702,7 +2705,10 @@ TEST_P(ImportFriendFunctions, LookupWithProtoAfter) {
   auto *FromNormal =
   LastDeclMatcher().match(FromTU, FunctionPattern);
   ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
-  ASSERT_FALSE(FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
+  // Before CXX20, MSVC treats friend function declarations as function
+  // declarations
+  ASSERT_EQ(FromTU->getLangOpts().MSVCCompat,
+FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   ASSERT_FALSE(FromNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
   ASSERT_TRUE(FromNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary));
 
@@ -2793,7 +2799,10 @@ TEST_P(ImportFriendFunctions, ImportFriendChangesLookup) 
{
 
   ASSERT_TRUE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
   
ASSERT_FALSE(FromNormalF->isInIde

[PATCH] D109467: [analyzer] check for std::__addressof for inner pointer checker

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

@alishuja, Shall I submit this patch with `--author="Ali Shuja Siddiqui 
"` (thus on your behalf) ?
The LLVM DeveloperPolicy 
 mandates me 
for asking permission.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109467

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


[PATCH] D117112: [AArch64] Support for Ampere1 core

2022-05-03 Thread Philipp Tomsich via Phabricator via cfe-commits
philipp.tomsich updated this revision to Diff 426622.
philipp.tomsich marked 4 inline comments as done.
philipp.tomsich added a comment.

Rebased to main.
The earlier base-regression was a precommitted test-case that caused 
SimpleLoopUnswitch tests (not related to these changes) to fail.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117112

Files:
  clang/test/Misc/target-invalid-cpu-note.c
  llvm/include/llvm/Support/AArch64TargetParser.def
  llvm/lib/Target/AArch64/AArch64.td
  llvm/lib/Target/AArch64/AArch64SchedAmpere1.td
  llvm/lib/Target/AArch64/AArch64SchedPredAmpere.td
  llvm/lib/Target/AArch64/AArch64SchedPredicates.td
  llvm/lib/Target/AArch64/AArch64Subtarget.cpp
  llvm/lib/Target/AArch64/AArch64Subtarget.h
  llvm/test/CodeGen/AArch64/cpus.ll
  llvm/test/CodeGen/AArch64/neon-dot-product.ll
  llvm/test/CodeGen/AArch64/remat.ll
  llvm/test/MC/AArch64/armv8.2a-dotprod.s
  llvm/test/MC/AArch64/armv8.3a-rcpc.s
  llvm/test/MC/Disassembler/AArch64/armv8.3a-rcpc.txt
  llvm/unittests/Support/TargetParserTest.cpp

Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -1195,6 +1195,14 @@
  AArch64::AEK_SVE2 | AArch64::AEK_SVE2BITPERM |
  AArch64::AEK_BF16 | AArch64::AEK_I8MM,
  "8.5-A"),
+ARMCPUTestParams("ampere1", "armv8.6-a", "crypto-neon-fp-armv8",
+ AArch64::AEK_CRC  | AArch64::AEK_FP   | AArch64::AEK_FP16   |
+ AArch64::AEK_SIMD | AArch64::AEK_RAS  | AArch64::AEK_LSE |
+ AArch64::AEK_RDM  | AArch64::AEK_RCPC | AArch64::AEK_DOTPROD |
+ AArch64::AEK_SM4  | AArch64::AEK_SHA3 | AArch64::AEK_BF16|
+ AArch64::AEK_SHA2 | AArch64::AEK_AES  | AArch64::AEK_I8MM|
+ AArch64::AEK_MTE  | AArch64::AEK_SSBS | AArch64::AEK_SB,
+ "8.6-A"),
 ARMCPUTestParams(
 "neoverse-512tvb", "armv8.4-a", "crypto-neon-fp-armv8",
 AArch64::AEK_RAS | AArch64::AEK_SVE | AArch64::AEK_SSBS |
@@ -1256,7 +1264,7 @@
  AArch64::AEK_LSE | AArch64::AEK_RDM,
  "8.2-A")));
 
-static constexpr unsigned NumAArch64CPUArchs = 53;
+static constexpr unsigned NumAArch64CPUArchs = 54;
 
 TEST(TargetParserTest, testAArch64CPUArchList) {
   SmallVector List;
Index: llvm/test/MC/Disassembler/AArch64/armv8.3a-rcpc.txt
===
--- llvm/test/MC/Disassembler/AArch64/armv8.3a-rcpc.txt
+++ llvm/test/MC/Disassembler/AArch64/armv8.3a-rcpc.txt
@@ -12,6 +12,7 @@
 # RUN: llvm-mc -triple aarch64-none-linux-gnu -mcpu=neoverse-e1 --disassemble < %s | FileCheck %s
 # RUN: llvm-mc -triple aarch64-none-linux-gnu -mcpu=neoverse-n1 --disassemble < %s | FileCheck %s
 # RUN: llvm-mc -triple aarch64-none-linux-gnu -mcpu=neoverse-n2 --disassemble < %s | FileCheck %s
+# RUN: llvm-mc -triple aarch64-none-linux-gnu -mcpu=ampere1 --disassemble < %s | FileCheck %s
 
 # CHECK: ldaprb w0, [x0]
 # CHECK: ldaprh w0, [x0]
Index: llvm/test/MC/AArch64/armv8.3a-rcpc.s
===
--- llvm/test/MC/AArch64/armv8.3a-rcpc.s
+++ llvm/test/MC/AArch64/armv8.3a-rcpc.s
@@ -6,6 +6,7 @@
 // RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mcpu=neoverse-e1 < %s 2>&1 | FileCheck %s
 // RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mcpu=neoverse-n1 < %s 2>&1 | FileCheck %s
 // RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mcpu=neoverse-n2 < %s 2>&1 | FileCheck %s
+// RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mcpu=ampere1 < %s 2>&1 | FileCheck %s
 // RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mattr=+v8.2a -mattr=+rcpc < %s 2>&1 | FileCheck %s
 // RUN: not llvm-mc -triple aarch64-none-linux-gnu -mattr=+v8.2a < %s 2> %t
 // RUN: FileCheck --check-prefix=CHECK-REQ %s < %t
Index: llvm/test/MC/AArch64/armv8.2a-dotprod.s
===
--- llvm/test/MC/AArch64/armv8.2a-dotprod.s
+++ llvm/test/MC/AArch64/armv8.2a-dotprod.s
@@ -13,6 +13,7 @@
 // RUN: llvm-mc -triple aarch64 -mcpu=tsv110 -show-encoding < %s | FileCheck %s --check-prefix=CHECK-DOTPROD
 // RUN: llvm-mc -triple aarch64 -mcpu=cortex-r82 -show-encoding < %s | FileCheck %s --check-prefix=CHECK-DOTPROD
 // RUN: llvm-mc -triple aarch64 -mattr=+v8r -show-encoding < %s | FileCheck %s --check-prefix=CHECK-DOTPROD
+// RUN: llvm-mc -triple aarch64 -mcpu=ampere1 -show-encoding < %s | FileCheck %s --check-prefix=CHECK-DOTPROD
 
 // RUN: not llvm-mc -triple aarch64 -mattr=+v8.2a -show-encoding < %s 2> %t
 // RUN:

[PATCH] D124836: [AArch64] Add support for -fzero-call-used-regs

2022-05-03 Thread Bill Wendling via Phabricator via cfe-commits
void created this revision.
void added reviewers: nickdesaulniers, danielkiss, MaskRay.
Herald added subscribers: StephenFan, pengfei, hiraditya, kristof.beyls.
Herald added a project: All.
void requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Support the "-fzero-call-used-regs" option on AArch64. This involves much less
specialized code than the X86 version. Most of the checks can be done with
TableGen.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124836

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  llvm/lib/Target/AArch64/AArch64FrameLowering.cpp
  llvm/lib/Target/AArch64/AArch64FrameLowering.h
  llvm/lib/Target/AArch64/AArch64RegisterInfo.td
  llvm/lib/Target/X86/X86RegisterInfo.cpp
  llvm/test/CodeGen/AArch64/zero-call-used-regs.ll
  llvm/utils/TableGen/RegisterInfoEmitter.cpp

Index: llvm/utils/TableGen/RegisterInfoEmitter.cpp
===
--- llvm/utils/TableGen/RegisterInfoEmitter.cpp
+++ llvm/utils/TableGen/RegisterInfoEmitter.cpp
@@ -1188,6 +1188,8 @@
  << "MCRegister) const override;\n"
  << "  bool isFixedRegister(const MachineFunction &, "
  << "MCRegister) const override;\n"
+ << "  bool isArgumentRegister(const MachineFunction &, "
+ << "MCRegister) const override;\n"
  << "  /// Devirtualized TargetFrameLowering.\n"
  << "  static const " << TargetName << "FrameLowering *getFrameLowering(\n"
  << "  const MachineFunction &MF);\n"
@@ -1662,6 +1664,20 @@
   OS << "  false;\n";
   OS << "}\n\n";
 
+  OS << "bool " << ClassName << "::\n"
+ << "isArgumentRegister(const MachineFunction &MF, "
+ << "MCRegister PhysReg) const {\n"
+ << "  return\n";
+  for (const CodeGenRegisterCategory &Category : RegCategories)
+if (Category.getName() == "ArgumentRegisters") {
+  for (const CodeGenRegisterClass *RC : Category.getClasses())
+OS << "  " << RC->getQualifiedName()
+   << "RegClass.contains(PhysReg) ||\n";
+  break;
+}
+  OS << "  false;\n";
+  OS << "}\n\n";
+
   OS << "ArrayRef " << ClassName
  << "::getRegMaskNames() const {\n";
   if (!CSRSets.empty()) {
Index: llvm/test/CodeGen/AArch64/zero-call-used-regs.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AArch64/zero-call-used-regs.ll
@@ -0,0 +1,233 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=aarch64-unknown-unknown | FileCheck %s
+
+@result = dso_local global i32 0, align 4
+
+define dso_local i32 @skip(i32 noundef %a, i32 noundef %b, i32 noundef %c) local_unnamed_addr #0 "zero-call-used-regs"="skip" {
+; CHECK-LABEL: skip:
+; CHECK:   // %bb.0: // %entry
+; CHECK-NEXT:mul w8, w1, w0
+; CHECK-NEXT:orr w0, w8, w2
+; CHECK-NEXT:ret
+
+entry:
+  %mul = mul nsw i32 %b, %a
+  %or = or i32 %mul, %c
+  ret i32 %or
+}
+
+define dso_local i32 @used_gpr_arg(i32 noundef %a, i32 noundef %b, i32 noundef %c) local_unnamed_addr #0 noinline optnone "zero-call-used-regs"="used-gpr-arg" {
+; CHECK-LABEL: used_gpr_arg:
+; CHECK:   // %bb.0: // %entry
+; CHECK-NEXT:mul w8, w1, w0
+; CHECK-NEXT:orr w0, w8, w2
+; CHECK-NEXT:mov x1, #0
+; CHECK-NEXT:mov x2, #0
+; CHECK-NEXT:ret
+
+entry:
+  %mul = mul nsw i32 %b, %a
+  %or = or i32 %mul, %c
+  ret i32 %or
+}
+
+define dso_local i32 @used_gpr(i32 noundef %a, i32 noundef %b, i32 noundef %c) local_unnamed_addr #0 noinline optnone "zero-call-used-regs"="used-gpr" {
+; CHECK-LABEL: used_gpr:
+; CHECK:   // %bb.0: // %entry
+; CHECK-NEXT:mul w8, w1, w0
+; CHECK-NEXT:orr w0, w8, w2
+; CHECK-NEXT:mov x1, #0
+; CHECK-NEXT:mov x2, #0
+; CHECK-NEXT:mov x8, #0
+; CHECK-NEXT:ret
+
+entry:
+  %mul = mul nsw i32 %b, %a
+  %or = or i32 %mul, %c
+  ret i32 %or
+}
+
+define dso_local i32 @used_arg(i32 noundef %a, i32 noundef %b, i32 noundef %c) local_unnamed_addr #0 noinline optnone "zero-call-used-regs"="used-arg" {
+; CHECK-LABEL: used_arg:
+; CHECK:   // %bb.0: // %entry
+; CHECK-NEXT:mul w8, w1, w0
+; CHECK-NEXT:orr w0, w8, w2
+; CHECK-NEXT:mov x1, #0
+; CHECK-NEXT:mov x2, #0
+; CHECK-NEXT:ret
+
+entry:
+  %mul = mul nsw i32 %b, %a
+  %or = or i32 %mul, %c
+  ret i32 %or
+}
+
+define dso_local i32 @used(i32 noundef %a, i32 noundef %b, i32 noundef %c) local_unnamed_addr #0 noinline optnone "zero-call-used-regs"="used" {
+; CHECK-LABEL: used:
+; CHECK:   // %bb.0: // %entry
+; CHECK-NEXT:mul w8, w1, w0
+; CHECK-NEXT:orr w0, w8, w2
+; CHECK-NEXT:mov x1, #0
+; CHECK-NEXT:mov x2, #0
+; CHECK-NEXT:mov x8, #0
+; CHECK-NEXT:ret
+
+entry:
+  %mul = mul nsw i32 %b, %a
+  %or = or i32 %mul, %c
+  ret i32 %or
+}
+
+define dso_local i32 @all_gpr_arg(i32 noundef %a, i32 noundef %b, i32 noundef %c) local_unnamed_addr #0 "ze

[PATCH] D124836: [AArch64] Add support for -fzero-call-used-regs

2022-05-03 Thread Kristof Beyls via Phabricator via cfe-commits
kristof.beyls added inline comments.



Comment at: llvm/lib/Target/AArch64/AArch64FrameLowering.cpp:752
+#undef CASE
+  }
+}

Just a drive-by comment: I'm wondering if SVE registers should also be listed 
here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124836

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


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-03 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 426635.
martong marked 6 inline comments as done.
martong added a comment.

- Update according to review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/ProgramState.cpp
  clang/test/Analysis/sink-infeasible.c

Index: clang/test/Analysis/sink-infeasible.c
===
--- /dev/null
+++ clang/test/Analysis/sink-infeasible.c
@@ -0,0 +1,59 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test that if it turns out that the parent state is infeasible then
+// both children States (more precisely the ExplodedNodes) are marked as a
+// Sink.
+// We rely on an existing defect of the underlying constraint solver. However,
+// in the future we might strengthen the solver to discover the infeasibility
+// right when we create the parent state. At that point this test will fail,
+// and either we shall find another solver weakness to have this test case
+// functioning, or we shall simply remove this test.
+
+void clang_analyzer_warnIfReached();
+void clang_analyzer_eval(int);
+
+int a, b, c, d, e;
+void f() {
+
+  if (a == 0)
+return;
+
+  if (e != c)
+return;
+
+  d = e - c;
+  b = d;
+  a -= d;
+
+  if (a != 0)
+return;
+
+  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+
+  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
+  // The parent state is already infeasible, look at this contradiction:
+  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
+  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
+  // Crashes with expensive checks.
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning, OK
+return;
+  }
+  // Should not be reachable.
+  clang_analyzer_warnIfReached(); // expected-wrning{{REACHABLE}}
+  */
+
+  // The parent state is already infeasible, but we realize that only if b is
+  // constrained.
+  clang_analyzer_eval(b > 0);  // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(b <= 0); // expected-warning{{UNKNOWN}}
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning
+return;
+  }
+  clang_analyzer_warnIfReached(); // no-warning
+}
Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -55,7 +55,7 @@
 
 ProgramState::ProgramState(const ProgramState &RHS)
 : stateMgr(RHS.stateMgr), Env(RHS.Env), store(RHS.store), GDM(RHS.GDM),
-  refCount(0) {
+  Infeasible(RHS.Infeasible), refCount(0) {
   stateMgr->getStoreManager().incrementReferenceCount(store);
 }
 
@@ -429,6 +429,12 @@
   return getStateManager().getPersistentState(NewSt);
 }
 
+ProgramStateRef ProgramState::cloneAsInfeasible() const {
+  ProgramState NewSt(*this);
+  NewSt.Infeasible = true;
+  return getStateManager().getPersistentState(NewSt);
+}
+
 void ProgramState::setStore(const StoreRef &newStore) {
   Store newStoreStore = newStore.getStore();
   if (newStoreStore)
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -41,3 +41,32 @@
 return ConditionTruthVal(true);
   return {};
 }
+
+ConstraintManager::ProgramStatePair
+ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
+  ProgramStateRef StTrue = assume(State, Cond, true);
+
+  if (!StTrue) {
+ProgramStateRef StFalse = assume(State, Cond, false);
+if (!StFalse) { // both infeasible
+  ProgramStateRef StInfeasible = State->cloneAsInfeasible();
+  assert(StInfeasible->isInfeasible());
+  // Checkers might rely on the API contract that both returned states
+  // cannot be null. Thus, we return StInfeasible for both branches because
+  // it might happen that a Checker uncoditionally uses one of them if the
+  // other is a nullptr. This may also happen with the non-dual and
+  // adjacent `assume(true)` and `assume(false)` calls. By implementing
+  // assume in therms of assumeDual, we can keep our API contract there as
+  // well.
+  return ProgramStatePair(StInfeasible, StInfeasible);
+}
+return ProgramStatePair(nullptr, StFalse);
+  }
+
+  ProgramStateRef StFalse = assume(State, Co

[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-03 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp:51
+ProgramStateRef StFalse = assume(State, Cond, false);
+if (!StFalse) { // both infeasible
+  ProgramStateRef Infeasible = State->cloneAsInfeasible();

steakhal wrote:
> Should we mark this `LLVM_UNLIKELY(cond)`?
> I would expect this function to be quite hot, and infeasible states rare.
> 
> Could we measure this one?
Yes, it could be.

Let me come back with some measurement results soon. I am going to use llvm 
statistics macros to measure this, but that makes sense on top of D124758



Comment at: clang/test/Analysis/sink-infeasible.c:37-48
+  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
+  // The parent state is already infeasible, look at this contradiction:
+  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
+  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
+  // Crashes with expensive checks.
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning, OK

steakhal wrote:
> You could use a non-default check prefix.
No I can't, because this test code in the comment is meaningful only in the 
baseline, I cannot run both clang versions from lit.

So, actually there is no RUN line for these, it is here only to demonstrate 
what happens in the baseline.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-03 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D124674#3482765 , @steakhal wrote:

> Finally, we have this!

Thanks for the review.

> Can we have this https://godbolt.org/z/oferc6P5Y in addition to the one you 
> proposed?
> I find it more readable.

Sure, I find it also more readable. I will update soon.

> What performance hit will we suffer from this change?
> Please do a differential analysis.

I am doing that with the dependent patch https://reviews.llvm.org/D124758


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D121150: [pseudo][WIP] Implement a GLR parser.

2022-05-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

This looks really good, great job on the signatures & tests.
There are a few different ways to formulate the signatures of 
glrParse/glrReduce, and some possible optimizations, but I can't see anything 
that's an obvious improvement worth holding up over.




Comment at: clang-tools-extra/pseudo/include/clang-pseudo/GLR.h:71
+LRTable::StateID State;
+// Number of the parents of this node, which are stored as trailing 
objects.
+// The parents hold previous parsed symbols, and may resume control after

nit: *pointers* are stored as trailing objects, not the parents themselves



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/GLR.h:143
+// parsing process (glrShift, or glrReduce).
+using NewHeadCallback =
+std::function Parents)>;
+// Apply all PendingShift actions on a given GSS state, newly-created heads are
+// passed to the CB.

the comment says newly-created heads are passed, but actually their inputs are 
passed and the callback is responsible for creating them.

(Why not have glrShift create the node and pass it to the callback? Or maybe 
even pass the output vector of NewHeads& in for concreteness?)



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/GLR.h:147
+// Apply all PendingShift actions on a given GSS state, newly-created heads are
+// passed to the CB.
+//

Maybe also mention the interaction with PendingShift?

"When this function returns, PendingShift is empty."?



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/GLR.h:151
+void glrShift(std::vector &PendingShift, const ForestNode &NextTok,
+  const ParseParams &Params, NewHeadCallback CB);
+// Applies PendingReduce actions, until no more reduce actions are available.

nit: semantics of the callback aren't obvious, so I think "NewHead" is a better 
name than "CB"



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/GLR.h:153
+// Applies PendingReduce actions, until no more reduce actions are available.
+//
+// Exposed for testing only.

When this function returns, PendingReduce is empty. Calls to NewHeadCB may add 
elements to PendingReduce



Comment at: clang-tools-extra/pseudo/tool/ClangPseudo.cpp:39
   desc("Print directive structure of source code"));
+static opt PrintStats("print-stats", desc("Print GLR parser 
statistics"));
+static opt PrintForest("print-forest", desc("Print parse forest"));

nit: just "print statistics"? I think this should be orthogonal to other options



Comment at: clang-tools-extra/pseudo/unittests/GLRTest.cpp:34
+
+struct NewHeadResult {
+  LRTable::StateID State;

this looks so much like a GSS node: why not just use a GSS node?



Comment at: clang-tools-extra/pseudo/unittests/GLRTest.cpp:137
+  glrShift(PendingShift, SemiTerminal, {*G, T, Arena, GSS},
+   std::bind(&GLRTest::captureNewHeads, this, _1, _2, _3));
+

bind is ugly :-(

maybe just have GLRTest::captureNewHeads() return a std::function with the 
right signature?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121150

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


[clang] 1fc208d - Fix Clang sphinx build

2022-05-03 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-03T07:14:12-04:00
New Revision: 1fc208d40012103f81279ab85949a91f8188e7a1

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

LOG: Fix Clang sphinx build

It seems we don't have this option exposed via RST, so switching to use
generic backticks instead.

Added: 


Modified: 
clang/docs/UsersManual.rst

Removed: 




diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 402029c8a64b3..8eb676650ec61 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -1219,7 +1219,7 @@ for generating PCH files:
 Using a PCH File
 
 
-A PCH file can then be used as a prefix header when a :option:`-include-pch`
+A PCH file can then be used as a prefix header when a ``-include-pch``
 option is passed to ``clang``:
 
 .. code-block:: console
@@ -1245,7 +1245,7 @@ will be processed from the PCH file. Otherwise, Clang 
will report an error.
 
   In this example, ``clang`` will not automatically use the PCH file for
   ``test.h`` since ``test.h`` was included directly in the source file and not
-  specified on the command line using :option:`-include-pch`.
+  specified on the command line using ``-include-pch``.
 
 Relocatable PCH Files
 ^



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


[PATCH] D124694: [randstruct] Move initializer check to be more effective

2022-05-03 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 D124694#3486547 , @void wrote:

> In D124694#3485585 , @aaron.ballman 
> wrote:
>
>>   struct t {
>>  int a, b, c, d, e;
>>   } x = { .a = 2, 4, 5, 6 };
>>
>> This situation seems like it should be an error, shouldn't it? The user 
>> specified one designated initializer (yay, that one is correct), but the 
>> rest are positional initializers and so there's no telling what they 
>> actually initialize due to field randomization.
>
> That is diagnosed as an error. The issue is that after randomization, the `a` 
> field is placed at the end of the structure. The initializer checker then 
> sees the `.a = 2` and says, "Ah! That's the one at the end of the structure. 
> Any non-designated initializers afterwards will be excess ones," which is 
> what happens. But that warning is completely mysterious to the end users who 
> isn't told that they can't have a non-designated initializer on a randomized 
> structure. Moving the diagnostic check allows the correct warning to be 
> emitted instead of the "excess elements" one.

Oh! Thank you for the extra explanation, that makes a lot more sense to me 
now. LGTM with a commenting request.




Comment at: clang/test/Sema/init-randomized-struct.c:1
-// RUN: %clang_cc1 -triple=x86_64-unknown-linux 
-frandomize-layout-seed=1234567890abcdef \
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux 
-frandomize-layout-seed=1234567890abcded \
 // RUN:  -verify -fsyntax-only -Werror %s

void wrote:
> aaron.ballman wrote:
> > Why is this change needed?
> > 
> > (Also, shouldn't there be other test coverage added to the file?)
> That seed is how to replicate this issue. The test exists and is triggered by 
> this change. I can add a comment to that effect.
Yeah, adding such a comment would be helpful, both for code archeology and as a 
hint to others editing the file in the future that this seed value is special 
and should not be changed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124694

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


[PATCH] D122663: Mark identifier prefixes as substitutable

2022-05-03 Thread Nathan Sidwell via Phabricator via cfe-commits
urnathan added inline comments.



Comment at: clang/lib/AST/ItaniumMangle.cpp:6031
+bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {
+  NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
+  return mangleSubstitution(reinterpret_cast(NNS));

hvdijk wrote:
> rsmith wrote:
> > This seems a little error-prone to me: calling this on a type NNS would do 
> > the wrong thing (those are supposed to share a substitution number with the 
> > type, rather than have a substitution of their own).
> > 
> > We could handle the various cases here and dispatch to the right forms of 
> > `mangleSubstitution` depending on the kind of NNS, but that code would all 
> > be unreachable / untested. So maybe we should just make this assert that 
> > `NNS->getKind() == NestedNameSpecifier::Identifier`. (And optionally we 
> > could give this a more specific name, eg 
> > `mangleSubstitutionForIdentifierNNS`?)
> I have added the assert that you suggested. I would actually have preferred 
> for this function to be used for other NNS substitutions as well to better 
> align with how the spec says substitutions should be handled (it's a rule of 
> ``, not any component within) but that seemed like an unnecessarily 
> more invasive change. If you are okay with it I would like to keep the 
> function named just `mangleSubstitution` to keep that open as option for a 
> possible future clean-up.
One could name it `mangleSubstitutionForIdentifierNNS` now and rename it in the 
future, if your unification dream comes true?  That names it for what it does 
now.

Just a thought, not a requirement.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122663

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


[PATCH] D124500: [clang-tidy] Support expressions of literals in modernize-macro-to-enum

2022-05-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:99
+
+  if (!Current->isLiteral() || isStringLiteral(Current->getKind()) ||
+  !isIntegralConstant(*Current)) {

aaron.ballman wrote:
> LegalizeAdulthood wrote:
> > LegalizeAdulthood wrote:
> > > aaron.ballman wrote:
> > > > LegalizeAdulthood wrote:
> > > > > aaron.ballman wrote:
> > > > > > LegalizeAdulthood wrote:
> > > > > > > aaron.ballman wrote:
> > > > > > > > LegalizeAdulthood wrote:
> > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > I know this is code moved from elsewhere, but I suppose we 
> > > > > > > > > > never considered the odd edge case where a user does 
> > > > > > > > > > something like `"foo"[0]` as a really awful integer 
> > > > > > > > > > constant. :-D
> > > > > > > > > It's always possible to write crazy contorted code and have a 
> > > > > > > > > check not recognize it.  I don't think it's worthwhile to 
> > > > > > > > > spend time trying to handle torture cases unless we can find 
> > > > > > > > > data that shows it's prevalent in real world code.
> > > > > > > > > 
> > > > > > > > > If I was doing a code review and saw this:
> > > > > > > > > ```
> > > > > > > > > enum {
> > > > > > > > > FOO = "foo"[0]
> > > > > > > > > };
> > > > > > > > > ```
> > > > > > > > > I'd flag that in a code review as bogus, whereas if I saw:
> > > > > > > > > ```
> > > > > > > > > enum {
> > > > > > > > > FOO = 'f'
> > > > > > > > > };
> > > > > > > > > ```
> > > > > > > > > That would be acceptable, which is why character literals are 
> > > > > > > > > accepted as an integral literal initializer for an enum in 
> > > > > > > > > this check.
> > > > > > > > >  I don't think it's worthwhile to spend time trying to handle 
> > > > > > > > > torture cases unless we can find data that shows it's 
> > > > > > > > > prevalent in real world code.
> > > > > > > > 
> > > > > > > > I think I'm okay agreeing to that in this particular case, but 
> > > > > > > > this is more to point out that writing your own parser is a 
> > > > > > > > maintenance burden. Users will hit cases we've both forgotten 
> > > > > > > > about here, they'll file a bug, then someone has to deal with 
> > > > > > > > it. It's very hard to justify to users "we think you write 
> > > > > > > > silly code" because they often have creative ways in which 
> > > > > > > > their code is not actually so silly, especially when we support 
> > > > > > > > "most" valid expressions.
> > > > > > > Writing your own parser is unavoidable here because we can't just 
> > > > > > > assume that any old thing will be a valid initializer just by 
> > > > > > > looking at the set of tokens present in the macro body.  (There 
> > > > > > > is a separate discussion going on about improving the 
> > > > > > > preprocessor support and parsing things more deeply, but that 
> > > > > > > isn't even to the point of a prototype yet.)  The worst thing we 
> > > > > > > can do is create "fixits" that produce invalid code.
> > > > > > > 
> > > > > > > The worst that happens if your expression isn't recognized is 
> > > > > > > that your macro isn't matched as a candidate for an enum.  You 
> > > > > > > can always make it an enum manually and join it with adjacent 
> > > > > > > macros that were recognized and converted.
> > > > > > > 
> > > > > > > As it stands, the check only recognizes a single literal with an 
> > > > > > > optional unary operator.
> > > > > > > 
> > > > > > > This change expands the check to recognize a broad range of 
> > > > > > > expressions, allowing those macros to be converted to enums.  I 
> > > > > > > opened the issue because running modernize-macro-to-enum on the 
> > > > > > > [[ https://github.com/InsightSoftwareConsortium/ITK | ITK 
> > > > > > > codebase ]] showed some simple expressions involving literals 
> > > > > > > that weren't recognized and converted.
> > > > > > > 
> > > > > > > If an expression isn't recognized and an issue is opened, it will 
> > > > > > > be an enhancement request to support a broader range of 
> > > > > > > expression, not a bug that this check created invalid code.
> > > > > > > 
> > > > > > > IMO, the more useful thing that's missing from the grammar is 
> > > > > > > recognizing `sizeof` expressions rather than indexing string 
> > > > > > > literals with an integral literal subscript.
> > > > > > > 
> > > > > > > I had planned on doing another increment to recognize `sizeof` 
> > > > > > > expressions.
> > > > > > > Writing your own parser is unavoidable here because we can't just 
> > > > > > > assume that any old thing will be a valid initializer just by 
> > > > > > > looking at the set of tokens present in the macro body. 
> > > > > > 
> > > > > > If you ran the token sequence through clang's parser and got an AST 
> > > > > > node out, you'd have significantly *more* information as to whether 
> > > > > > someth

[PATCH] D109467: [analyzer] check for std::__addressof for inner pointer checker

2022-05-03 Thread Ali Shuja Siddiqui via Phabricator via cfe-commits
alishuja accepted this revision.
alishuja added a comment.

@steakhal yes please go ahead, thank you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109467

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


[PATCH] D124762: [WinEHPrepare] Avoid truncation of EH funclets with GNUstep ObjC runtime

2022-05-03 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz added a comment.

Thanks for your help! I will work on testing in calendar week 21.




Comment at: llvm/lib/CodeGen/WinEHPrepare.cpp:966
 
-if (FuncletBundleOperand == FuncletPad)
+if (!FuncletPad || FuncletBundleOperand == FuncletPad)
   continue;

rnk wrote:
> Is this change necessary? It seems like it shouldn't be after the clang and 
> preisel pass changes.
Yes, apparently it is necessary. There are cases, where 
`CodeGenFunction::getBundlesForFunclet()` registers a "funclet" bundle operand, 
but the `FuncletPad` here is null. My guess was it might be due to 
optimizations?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124762

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


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

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

I think I don't have anything left.
Let's see the numbers.




Comment at: clang/test/Analysis/sink-infeasible.c:37-48
+  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
+  // The parent state is already infeasible, look at this contradiction:
+  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
+  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
+  // Crashes with expensive checks.
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning, OK

martong wrote:
> steakhal wrote:
> > You could use a non-default check prefix.
> No I can't, because this test code in the comment is meaningful only in the 
> baseline, I cannot run both clang versions from lit.
> 
> So, actually there is no RUN line for these, it is here only to demonstrate 
> what happens in the baseline.
Okay, why don't we drop these if these are only applicable to the baseline?
Should we really introduce 'stale' comments?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D124842: [NFC][CUDA][HIP] rework mangling number for aux target

2022-05-03 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added a reviewer: tra.
Herald added subscribers: mattd, carlosgalvezp.
Herald added a project: All.
yaxunl requested review of this revision.

CUDA/HIP needs to mangle for aux target. When mangling for aux target,
the mangler should use mangling number for aux target. Previously
in https://reviews.llvm.org/D122734 a state was introduced in
ASTContext to let the mangler get mangling number for aux target
from ASTContext. This patch removes that state from ASTConext
and add an IsAux member to MangleContext to indicate that
the mangle context is for aux target. This reflects the reality that
the mangle context is created for mangling aux target and makes
ASTContext cleaner.


https://reviews.llvm.org/D124842

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/Mangle.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/MicrosoftMangle.cpp
  clang/lib/CodeGen/CGCUDANV.cpp

Index: clang/lib/CodeGen/CGCUDANV.cpp
===
--- clang/lib/CodeGen/CGCUDANV.cpp
+++ clang/lib/CodeGen/CGCUDANV.cpp
@@ -24,7 +24,6 @@
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/ReplaceConstant.h"
 #include "llvm/Support/Format.h"
-#include "llvm/Support/SaveAndRestore.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -261,8 +260,6 @@
 }
 
 std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) {
-  llvm::SaveAndRestore MangleAsDevice(
-  CGM.getContext().CUDAMangleDeviceNameInHostCompilation, true);
   GlobalDecl GD;
   // D could be either a kernel or a variable.
   if (auto *FD = dyn_cast(ND))
Index: clang/lib/AST/MicrosoftMangle.cpp
===
--- clang/lib/AST/MicrosoftMangle.cpp
+++ clang/lib/AST/MicrosoftMangle.cpp
@@ -147,7 +147,8 @@
   SmallString<16> AnonymousNamespaceHash;
 
 public:
-  MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags);
+  MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags,
+ bool IsAux = false);
   bool shouldMangleCXXName(const NamedDecl *D) override;
   bool shouldMangleStringLiteral(const StringLiteral *SL) override;
   void mangleCXXName(GlobalDecl GD, raw_ostream &Out) override;
@@ -221,7 +222,7 @@
 
 // Use the canonical number for externally visible decls.
 if (ND->isExternallyVisible()) {
-  disc = getASTContext().getManglingNumber(ND);
+  disc = getASTContext().getManglingNumber(ND, isAux());
   return true;
 }
 
@@ -459,8 +460,9 @@
 }
 
 MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
-   DiagnosticsEngine &Diags)
-: MicrosoftMangleContext(Context, Diags) {
+   DiagnosticsEngine &Diags,
+   bool IsAux)
+: MicrosoftMangleContext(Context, Diags, IsAux) {
   // To mangle anonymous namespaces, hash the path to the main source file. The
   // path should be whatever (probably relative) path was passed on the command
   // line. The goal is for the compiler to produce the same output regardless of
@@ -3944,7 +3946,8 @@
   Mangler.getStream() << '@';
 }
 
-MicrosoftMangleContext *
-MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
-  return new MicrosoftMangleContextImpl(Context, Diags);
+MicrosoftMangleContext *MicrosoftMangleContext::create(ASTContext &Context,
+   DiagnosticsEngine &Diags,
+   bool IsAux) {
+  return new MicrosoftMangleContextImpl(Context, Diags, IsAux);
 }
Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -78,8 +78,8 @@
 public:
   explicit ItaniumMangleContextImpl(
   ASTContext &Context, DiagnosticsEngine &Diags,
-  DiscriminatorOverrideTy DiscriminatorOverride)
-  : ItaniumMangleContext(Context, Diags),
+  DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
+  : ItaniumMangleContext(Context, Diags, IsAux),
 DiscriminatorOverride(DiscriminatorOverride) {}
 
   /// @name Mangler Entry Points
@@ -143,7 +143,7 @@
 
 // Use the canonical number for externally visible decls.
 if (ND->isExternallyVisible()) {
-  unsigned discriminator = getASTContext().getManglingNumber(ND);
+  unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
   if (discriminator == 1)
 return false;
   disc = discriminator - 2;
@@ -1564,7 +1564,8 @@
 }
 
 if (TD->isExternallyVisible()) {
-  unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
+  unsigned UnnamedMangle =
+  getASTContext().getManglingNumber(TD, Cont

[PATCH] D122734: [CUDA][HIP] Fix mangling number for local struct

2022-05-03 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked an inline comment as done.
yaxunl added inline comments.



Comment at: clang/include/clang/AST/ASTContext.h:682
+/// Current name mangling is for device name in host compilation.
+bool MangleDeviceNameInHostCompilation = false;
+  } CUDANameMangleCtx;

rnk wrote:
> yaxunl wrote:
> > rnk wrote:
> > > It doesn't feel right to store mutable state here in ASTContext. You are 
> > > effectively using this as a global variable to thread a boolean through 
> > > to `ASTContext::getManglingNumber`, which is called from the mangler. The 
> > > boolean indicates of host or device mangling numbers are desired for this 
> > > particular mangling. Is that more or less correct?
> > > 
> > > This makes me think that it was perhaps a mistake to store mangling 
> > > numbers in the AST Context in the first place. If we stored them in the 
> > > mangling context instead, I think we'd get the right behavior out of the 
> > > box. Is that correct? It it feasible to make that change?
> > > It doesn't feel right to store mutable state here in ASTContext. You are 
> > > effectively using this as a global variable to thread a boolean through 
> > > to `ASTContext::getManglingNumber`, which is called from the mangler. The 
> > > boolean indicates of host or device mangling numbers are desired for this 
> > > particular mangling. Is that more or less correct?
> > > 
> > > This makes me think that it was perhaps a mistake to store mangling 
> > > numbers in the AST Context in the first place. If we stored them in the 
> > > mangling context instead, I think we'd get the right behavior out of the 
> > > box. Is that correct? It it feasible to make that change?
> > 
> > It is possible but I feel it is too invasive. Mangling numbers need to be 
> > calculated during construction of AST since it is context dependent. Mangle 
> > contexts are created in ABI of codegen. To store mangling numbers in 
> > mangling contexts, we need to move mangling contexts from ABI to 
> > ASTContext. We also need to add device mangling context in ASTContext. Then 
> > for each use of get/set mangling number API, we need to add get/set device 
> > mangling number API. That would need lots of changes.
> > 
> > I would see the state added to ASTContext by my approach from the 
> > perspective of single source language. The program contains both device 
> > code and host code. Ideally the compiler should be able to compile the 
> > device code with device target and ABI and compile the host code with host 
> > target ABI and switch the target freely during codegen. When we try to get 
> > the device side mangled name in host compilation, what we trying to do is 
> > switch to device target momoentorily during the mangling. This needs a 
> > state in ASTContext indicating that we are doing mangling for device 
> > instead of host, therefore getManglingNumber should return device mangling 
> > number instead of host mangling number.
> After auditing call sites for setManglingNumber, I see that many of them 
> relate to template instantiation and AST serialization. With that in mind, I 
> think it makes sense to leave the ManglingNumbers DenseMap as you have it, 
> it's not worth updating all of those serialization and cloning codepaths.
> 
> However, I really would prefer to remove this boolean on the ASTContext, 
> which effectively stands in as an extra parameter to all getManglingNumber 
> calls. The manglers should be able to calculate this boolean when they are 
> created (they should know if they are the Itanium device mangler or the MS 
> host mangler) and pass the correct value to every call to 
> ASTContext::getManglingNumber. Does that make sense?
> 
> However, I really would prefer to remove this boolean on the ASTContext, 
> which effectively stands in as an extra parameter to all getManglingNumber 
> calls. The manglers should be able to calculate this boolean when they are 
> created (they should know if they are the Itanium device mangler or the MS 
> host mangler) and pass the correct value to every call to 
> ASTContext::getManglingNumber. Does that make sense?

Yes. Opened https://reviews.llvm.org/D124842 for this.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122734

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


[clang] cf7cd66 - [analyzer] Check for std::__addressof for inner pointer checker

2022-05-03 Thread Balazs Benics via cfe-commits

Author: Ali Shuja Siddiqui
Date: 2022-05-03T14:05:19+02:00
New Revision: cf7cd664f3fd212c0f1e4a83fd2fe96902569d20

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

LOG: [analyzer] Check for std::__addressof for inner pointer checker

This is an extension to diff D99260. This adds an additional exception
for `std::__addressof` in `InnerPointerChecker`.

Patch By alishuja (Ali Shuja Siddiqui)!

Reviewed By: martong, alishuja

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
clang/test/Analysis/inner-pointer.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
index a50674dc70f42..895212d134b88 100644
--- a/clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
@@ -35,9 +35,9 @@ namespace {
 class InnerPointerChecker
 : public Checker {
 
-  CallDescription AppendFn, AssignFn, AddressofFn, ClearFn, CStrFn, DataFn,
-  DataMemberFn, EraseFn, InsertFn, PopBackFn, PushBackFn, ReplaceFn,
-  ReserveFn, ResizeFn, ShrinkToFitFn, SwapFn;
+  CallDescription AppendFn, AssignFn, AddressofFn, AddressofFn_, ClearFn,
+  CStrFn, DataFn, DataMemberFn, EraseFn, InsertFn, PopBackFn, PushBackFn,
+  ReplaceFn, ReserveFn, ResizeFn, ShrinkToFitFn, SwapFn;
 
 public:
   class InnerPointerBRVisitor : public BugReporterVisitor {
@@ -74,7 +74,7 @@ class InnerPointerChecker
   InnerPointerChecker()
   : AppendFn({"std", "basic_string", "append"}),
 AssignFn({"std", "basic_string", "assign"}),
-AddressofFn({"std", "addressof"}),
+AddressofFn({"std", "addressof"}), AddressofFn_({"std", 
"__addressof"}),
 ClearFn({"std", "basic_string", "clear"}),
 CStrFn({"std", "basic_string", "c_str"}), DataFn({"std", "data"}, 1),
 DataMemberFn({"std", "basic_string", "data"}),
@@ -179,9 +179,9 @@ void InnerPointerChecker::checkFunctionArguments(const 
CallEvent &Call,
   if (!ArgRegion)
 continue;
 
-  // std::addressof function accepts a non-const reference as an argument,
+  // std::addressof functions accepts a non-const reference as an argument,
   // but doesn't modify it.
-  if (AddressofFn.matches(Call))
+  if (matchesAny(Call, AddressofFn, AddressofFn_))
 continue;
 
   markPtrSymbolsReleased(Call, State, ArgRegion, C);

diff  --git a/clang/test/Analysis/inner-pointer.cpp 
b/clang/test/Analysis/inner-pointer.cpp
index 5db17a952f90b..4cb194409412c 100644
--- a/clang/test/Analysis/inner-pointer.cpp
+++ b/clang/test/Analysis/inner-pointer.cpp
@@ -20,6 +20,9 @@ void default_arg(int a = 42, string &b = my_string);
 template 
 T *addressof(T &arg);
 
+template 
+T *__addressof(T &arg);
+
 char *data(std::string &c);
 
 } // end namespace std
@@ -383,6 +386,14 @@ void func_addressof() {
   consume(c); // no-warning
 }
 
+void func_AddressofFn_() {
+  const char *c;
+  std::string s;
+  c = s.c_str();
+  (void)std::__addressof(s);
+  consume(c); // no-warning
+}
+
 void func_std_data() {
   const char *c;
   std::string s;



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


[PATCH] D109467: [analyzer] check for std::__addressof for inner pointer checker

2022-05-03 Thread Balázs Benics 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 rGcf7cd664f3fd: [analyzer] Check for std::__addressof for 
inner pointer checker (authored by alishuja, committed by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109467

Files:
  clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
  clang/test/Analysis/inner-pointer.cpp


Index: clang/test/Analysis/inner-pointer.cpp
===
--- clang/test/Analysis/inner-pointer.cpp
+++ clang/test/Analysis/inner-pointer.cpp
@@ -20,6 +20,9 @@
 template 
 T *addressof(T &arg);
 
+template 
+T *__addressof(T &arg);
+
 char *data(std::string &c);
 
 } // end namespace std
@@ -383,6 +386,14 @@
   consume(c); // no-warning
 }
 
+void func_AddressofFn_() {
+  const char *c;
+  std::string s;
+  c = s.c_str();
+  (void)std::__addressof(s);
+  consume(c); // no-warning
+}
+
 void func_std_data() {
   const char *c;
   std::string s;
Index: clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
@@ -35,9 +35,9 @@
 class InnerPointerChecker
 : public Checker {
 
-  CallDescription AppendFn, AssignFn, AddressofFn, ClearFn, CStrFn, DataFn,
-  DataMemberFn, EraseFn, InsertFn, PopBackFn, PushBackFn, ReplaceFn,
-  ReserveFn, ResizeFn, ShrinkToFitFn, SwapFn;
+  CallDescription AppendFn, AssignFn, AddressofFn, AddressofFn_, ClearFn,
+  CStrFn, DataFn, DataMemberFn, EraseFn, InsertFn, PopBackFn, PushBackFn,
+  ReplaceFn, ReserveFn, ResizeFn, ShrinkToFitFn, SwapFn;
 
 public:
   class InnerPointerBRVisitor : public BugReporterVisitor {
@@ -74,7 +74,7 @@
   InnerPointerChecker()
   : AppendFn({"std", "basic_string", "append"}),
 AssignFn({"std", "basic_string", "assign"}),
-AddressofFn({"std", "addressof"}),
+AddressofFn({"std", "addressof"}), AddressofFn_({"std", 
"__addressof"}),
 ClearFn({"std", "basic_string", "clear"}),
 CStrFn({"std", "basic_string", "c_str"}), DataFn({"std", "data"}, 1),
 DataMemberFn({"std", "basic_string", "data"}),
@@ -179,9 +179,9 @@
   if (!ArgRegion)
 continue;
 
-  // std::addressof function accepts a non-const reference as an argument,
+  // std::addressof functions accepts a non-const reference as an argument,
   // but doesn't modify it.
-  if (AddressofFn.matches(Call))
+  if (matchesAny(Call, AddressofFn, AddressofFn_))
 continue;
 
   markPtrSymbolsReleased(Call, State, ArgRegion, C);


Index: clang/test/Analysis/inner-pointer.cpp
===
--- clang/test/Analysis/inner-pointer.cpp
+++ clang/test/Analysis/inner-pointer.cpp
@@ -20,6 +20,9 @@
 template 
 T *addressof(T &arg);
 
+template 
+T *__addressof(T &arg);
+
 char *data(std::string &c);
 
 } // end namespace std
@@ -383,6 +386,14 @@
   consume(c); // no-warning
 }
 
+void func_AddressofFn_() {
+  const char *c;
+  std::string s;
+  c = s.c_str();
+  (void)std::__addressof(s);
+  consume(c); // no-warning
+}
+
 void func_std_data() {
   const char *c;
   std::string s;
Index: clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
@@ -35,9 +35,9 @@
 class InnerPointerChecker
 : public Checker {
 
-  CallDescription AppendFn, AssignFn, AddressofFn, ClearFn, CStrFn, DataFn,
-  DataMemberFn, EraseFn, InsertFn, PopBackFn, PushBackFn, ReplaceFn,
-  ReserveFn, ResizeFn, ShrinkToFitFn, SwapFn;
+  CallDescription AppendFn, AssignFn, AddressofFn, AddressofFn_, ClearFn,
+  CStrFn, DataFn, DataMemberFn, EraseFn, InsertFn, PopBackFn, PushBackFn,
+  ReplaceFn, ReserveFn, ResizeFn, ShrinkToFitFn, SwapFn;
 
 public:
   class InnerPointerBRVisitor : public BugReporterVisitor {
@@ -74,7 +74,7 @@
   InnerPointerChecker()
   : AppendFn({"std", "basic_string", "append"}),
 AssignFn({"std", "basic_string", "assign"}),
-AddressofFn({"std", "addressof"}),
+AddressofFn({"std", "addressof"}), AddressofFn_({"std", "__addressof"}),
 ClearFn({"std", "basic_string", "clear"}),
 CStrFn({"std", "basic_string", "c_str"}), DataFn({"std", "data"}, 1),
 DataMemberFn({"std", "basic_string", "data"}),
@@ -179,9 +179,9 @@
   if (!ArgRegion)
 continue;
 
-  // std::addressof function accepts a non-const reference as an argument,
+  // std::addressof functions accepts a non-const reference as an argument,
   // but doesn't modify it.
-  i

[PATCH] D122663: Mark identifier prefixes as substitutable

2022-05-03 Thread Harald van Dijk via Phabricator via cfe-commits
hvdijk added inline comments.



Comment at: clang/lib/AST/ItaniumMangle.cpp:6031
+bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {
+  NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
+  return mangleSubstitution(reinterpret_cast(NNS));

urnathan wrote:
> hvdijk wrote:
> > rsmith wrote:
> > > This seems a little error-prone to me: calling this on a type NNS would 
> > > do the wrong thing (those are supposed to share a substitution number 
> > > with the type, rather than have a substitution of their own).
> > > 
> > > We could handle the various cases here and dispatch to the right forms of 
> > > `mangleSubstitution` depending on the kind of NNS, but that code would 
> > > all be unreachable / untested. So maybe we should just make this assert 
> > > that `NNS->getKind() == NestedNameSpecifier::Identifier`. (And optionally 
> > > we could give this a more specific name, eg 
> > > `mangleSubstitutionForIdentifierNNS`?)
> > I have added the assert that you suggested. I would actually have preferred 
> > for this function to be used for other NNS substitutions as well to better 
> > align with how the spec says substitutions should be handled (it's a rule 
> > of ``, not any component within) but that seemed like an 
> > unnecessarily more invasive change. If you are okay with it I would like to 
> > keep the function named just `mangleSubstitution` to keep that open as 
> > option for a possible future clean-up.
> One could name it `mangleSubstitutionForIdentifierNNS` now and rename it in 
> the future, if your unification dream comes true?  That names it for what it 
> does now.
> 
> Just a thought, not a requirement.
Sorry, that comment came after I pushed it already. I have some more things to 
look into when I have some more time (including @erichkeane's comment about the 
test), will see if it makes sense to include with that, or perhaps to just make 
that NFC change to allow it to be used more generally.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122663

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


[PATCH] D124790: [HLSL] Enable half type for hlsl.

2022-05-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Driver/Options.td:6766-6767
+def enable_16bit_types : DXCFlag<"enable-16bit-types">, 
Alias,
+  HelpText<"Enable 16bit types and disable min precision types."
+   "Available in HLSL 2018 and shader model 6.2">;





Comment at: clang/lib/Basic/LangOptions.cpp:197
 
-  // OpenCL has half keyword
-  Opts.Half = Opts.OpenCL;
+  // OpenCL and HLSL have half keyword
+  Opts.Half = Opts.OpenCL || Opts.HLSL;

Shouldn't this be looking for HLSL 2018? Or shader model 6.2?



Comment at: clang/lib/Basic/Targets/DirectX.h:61
   }
-
+  bool useFP16ConversionIntrinsics() const override { return false; }
   void getTargetDefines(const LangOptions &Opts,

Should this be tied to the `Half` language option?



Comment at: clang/lib/Sema/SemaType.cpp:1514
+// For HLSL, when not enable native half type, half will be treat as float.
+if (S.getLangOpts().HLSL && !S.getLangOpts().NativeHalfType)
+  Result = Context.FloatTy;

This change seems wrong to me -- if the half type isn't supported, how does the 
user spell the type such that we can even get here?



Comment at: clang/test/CodeGenHLSL/half.hlsl:15
+  return a+b;
+}

FWIW, this test seems to be failing precommit CI.

We should also have tests for the new driver flag and Sema tests showing that 
you can't spell `half` in unsupported HLSL modes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124790

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


[clang-tools-extra] b18abde - [pseudo] Simplify the forest dump, NFC.

2022-05-03 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-05-03T14:14:57+02:00
New Revision: b18abde8ada122408724d2a1722aa2f75e9a87ce

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

LOG: [pseudo] Simplify the forest dump, NFC.

The code was written to handle nullable grammar, and we disallow
nullable grammar, so it is not necessary to keep it around.

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

Added: 


Modified: 
clang-tools-extra/pseudo/lib/Forest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/lib/Forest.cpp 
b/clang-tools-extra/pseudo/lib/Forest.cpp
index 6948422a23a6e..073a651947ac4 100644
--- a/clang-tools-extra/pseudo/lib/Forest.cpp
+++ b/clang-tools-extra/pseudo/lib/Forest.cpp
@@ -74,16 +74,13 @@ std::string ForestNode::dumpRecursive(const Grammar &G,
 } else if (P->kind() == Sequence) {
   Children = P->elements();
   if (Abbreviated) {
-if (P->startTokenIndex() == End)
-  return;
-for (size_t I = 0; I < Children.size(); ++I)
-  if (Children[I]->startTokenIndex() == P->startTokenIndex() &&
-  EndOfElement(I) == End) {
-return Dump(
-Children[I], End,
-/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
-LineDec);
-  }
+if (Children.size() == 1) {
+  assert(Children[0]->startTokenIndex() == P->startTokenIndex() &&
+ EndOfElement(0) == End);
+  return Dump(Children[0], End,
+  
/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
+  LineDec);
+}
   }
 }
 



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


[PATCH] D124827: [pseudo] Simplify the forest dump, NFC.

2022-05-03 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb18abde8ada1: [pseudo] Simplify the forest dump, NFC. 
(authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124827

Files:
  clang-tools-extra/pseudo/lib/Forest.cpp


Index: clang-tools-extra/pseudo/lib/Forest.cpp
===
--- clang-tools-extra/pseudo/lib/Forest.cpp
+++ clang-tools-extra/pseudo/lib/Forest.cpp
@@ -74,16 +74,13 @@
 } else if (P->kind() == Sequence) {
   Children = P->elements();
   if (Abbreviated) {
-if (P->startTokenIndex() == End)
-  return;
-for (size_t I = 0; I < Children.size(); ++I)
-  if (Children[I]->startTokenIndex() == P->startTokenIndex() &&
-  EndOfElement(I) == End) {
-return Dump(
-Children[I], End,
-/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
-LineDec);
-  }
+if (Children.size() == 1) {
+  assert(Children[0]->startTokenIndex() == P->startTokenIndex() &&
+ EndOfElement(0) == End);
+  return Dump(Children[0], End,
+  
/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
+  LineDec);
+}
   }
 }
 


Index: clang-tools-extra/pseudo/lib/Forest.cpp
===
--- clang-tools-extra/pseudo/lib/Forest.cpp
+++ clang-tools-extra/pseudo/lib/Forest.cpp
@@ -74,16 +74,13 @@
 } else if (P->kind() == Sequence) {
   Children = P->elements();
   if (Abbreviated) {
-if (P->startTokenIndex() == End)
-  return;
-for (size_t I = 0; I < Children.size(); ++I)
-  if (Children[I]->startTokenIndex() == P->startTokenIndex() &&
-  EndOfElement(I) == End) {
-return Dump(
-Children[I], End,
-/*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
-LineDec);
-  }
+if (Children.size() == 1) {
+  assert(Children[0]->startTokenIndex() == P->startTokenIndex() &&
+ EndOfElement(0) == End);
+  return Dump(Children[0], End,
+  /*ElidedParent=*/ElidedParent.getValueOr(P->symbol()),
+  LineDec);
+}
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124845: StaticAnalyzer should inline overridden delete operator the same way as overridden new operator

2022-05-03 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource created this revision.
frederic-tingaud-sonarsource added a reviewer: dcoughlin.
Herald added subscribers: manas, ASDenysPetrov, martong, dkrupp, donat.nagy, 
Szelethus, a.sidorin, baloghadamsoftware.
Herald added a project: All.
frederic-tingaud-sonarsource requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Currently, when encountering an overridden new operator, the StaticAnalyzer 
will inline it when possible, while an overridden delete operator will never 
be, which leads us to false positives like the following:

  struct CustomOperators {
void *operator new(size_t count) {
  return malloc(count);
}
  
void operator delete(void *addr) {
  free(addr);
}
  };
  
  void compliant() {
auto *a = new CustomOperators();
delete a; // warning{{Potential leak of memory pointed to by 'a'}}
  }

This patch restores the symmetry between how operator new and operator delete 
are handled by also inlining the content of operator delete when possible.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124845

Files:
  clang/include/clang/Analysis/ConstructionContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/test/Analysis/cxxnewexpr-callback-inline.cpp
  clang/test/Analysis/cxxnewexpr-callback-noinline.cpp
  clang/test/Analysis/dtor.cpp

Index: clang/test/Analysis/dtor.cpp
===
--- clang/test/Analysis/dtor.cpp
+++ clang/test/Analysis/dtor.cpp
@@ -570,3 +570,32 @@
   // no-crash
 }
 } // namespace dtor_over_loc_concrete_int
+
+// Test overriden new/delete operators
+struct CustomOperators {
+  void *operator new(size_t count) {
+return malloc(count);
+  }
+
+  void operator delete(void *addr) {
+free(addr);
+  }
+
+private:
+  int i;
+};
+
+void compliant() {
+  auto *a = new CustomOperators();
+  delete a;
+}
+
+void overrideLeak() {
+  auto *a = new CustomOperators();
+} // expected-warning{{Potential leak of memory pointed to by 'a'}}
+
+void overrideDoubleDelete() {
+  auto *a = new CustomOperators();
+  delete a;
+  delete a; // expected-warning@581 {{Attempt to free released memory}}
+}
Index: clang/test/Analysis/cxxnewexpr-callback-noinline.cpp
===
--- clang/test/Analysis/cxxnewexpr-callback-noinline.cpp
+++ clang/test/Analysis/cxxnewexpr-callback-noinline.cpp
@@ -3,13 +3,16 @@
 #include "Inputs/system-header-simulator-cxx.h"
 
 namespace std {
-  void *malloc(size_t);
-}
+void *malloc(size_t);
+void free(void *);
+} // namespace std
 
 void *operator new(size_t size) { return std::malloc(size); }
+void operator delete(void *ptr) { std::free(ptr); }
 
 struct S {
   S() {}
+  ~S() {}
 };
 
 void foo();
@@ -17,13 +20,35 @@
 void test() {
   S *s = new S();
   foo();
+  delete s;
 }
 
+/*
+void test() {
+  S *s = new S();
 // CHECK:  PreCall (S::S)
 // CHECK-NEXT: PostCall (S::S)
 // CHECK-NEXT: PreStmt
 // CHECK-NEXT: PostStmt
+  foo();
 // CHECK-NEXT: PreCall (foo)
 // CHECK-NEXT: PostCall (foo)
+  delete s;
+// CHECK-NEXT: PreCall (S::~S)
+// CHECK-NEXT: PostCall (S::~S)
+// CHECK-NEXT: PreCall (operator delete)
+// CHECK-NEXT: PostCall (operator delete)
+}
+
+void operator delete(void *ptr) {
+  std::free(ptr);
+// CHECK-NEXT: PreCall (std::free)
+// CHECK-NEXT: PostCall (std::free)
+}
+
+void *operator new(size_t size) {
+  return std::malloc(size);
 // CHECK-NEXT: PreCall (std::malloc)
 // CHECK-NEXT: PostCall (std::malloc)
+}
+*/
Index: clang/test/Analysis/cxxnewexpr-callback-inline.cpp
===
--- clang/test/Analysis/cxxnewexpr-callback-inline.cpp
+++ clang/test/Analysis/cxxnewexpr-callback-inline.cpp
@@ -4,12 +4,15 @@
 
 namespace std {
   void *malloc(size_t);
+  void free(void *);
 }
 
 void *operator new(size_t size) { return std::malloc(size); }
+void operator delete(void *ptr) { std::free(ptr); }
 
 struct S {
   S() {}
+  ~S() {}
 };
 
 void foo();
@@ -17,8 +20,12 @@
 void test() {
   S *s = new S();
   foo();
+  delete s;
 }
 
+/*
+void test() {
+  S *s = new S();
 // CHECK:  PreCall (operator new)
 // CHECK-NEXT: PreCall (std::malloc)
 // CHECK-NEXT: PostCall (std::malloc)
@@ -28,5 +35,15 @@
 // CHECK-NEXT: PostCall (S::S)
 // CHECK-NEXT: PreStmt
 // CHECK-NEXT: PostStmt
+  foo();
 // CHECK-NEXT: PreCall (foo)
 // CHECK-NEXT: PostCall (foo)
+  delete s;
+// CHECK-NEXT: PreCall (S::~S)
+// CHECK-NEXT: PostCall (S::~S)
+// CHECK-NEXT: PreCall (operator delete)
+// CHECK-NEXT: PreCall (std::free)
+// CHECK-NEXT: PostCall (std::free)
+// CHECK-NEXT: PostCall (operator delete)
+}
+*/
Index: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEn

[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-05-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Assuming no further comments from reviewers, I plan to land this sometime 
tomorrow.


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

https://reviews.llvm.org/D124258

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


[PATCH] D124850: [Sema][SVE2] Move/simplify Sema testing for SVE2 ACLE builtins

2022-05-03 Thread Rosie Sumpter via Phabricator via cfe-commits
RosieSumpter created this revision.
RosieSumpter added reviewers: sdesmalen, paulwalker-arm.
Herald added subscribers: ctetreau, tschuett.
Herald added a reviewer: efriedma.
Herald added a project: All.
RosieSumpter requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Currently for SVE2 ACLE builtins, single tests are used to verify both
clang code generation (when the feature is available) and semantic
error/warning messages (when the feature is unavailable). This
patch moves the semantic testing for the target feature flag into
dedicated Sema tests.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124850

Files:
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_aba.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_abalb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_abalt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_abdlb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_abdlt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_adalp.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_adclb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_adclt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_addhnb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_addhnt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_addlb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_addlbt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_addlt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_addp.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_addwb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_addwt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_aesd.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_aese.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_aesimc.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_aesmc.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_bcax.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_bdep.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_bext.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_bgrp.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_bsl.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_bsl1n.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_bsl2n.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_cadd.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_cdot.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_cmla.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_cvtlt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_cvtnt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_cvtx.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_cvtxnt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_eor3.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_eorbt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_eortb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_hadd.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_histcnt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_histseg.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_hsub.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_hsubr.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_ldnt1.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_ldnt1sb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_ldnt1sh.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_ldnt1sw.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_ldnt1ub.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_ldnt1uh.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_ldnt1uw.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_logb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_match.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_maxnmp.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_maxp.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_minnmp.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_minp.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_mla.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_mlalb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_mlalt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_mls.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_mlslb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_mlslt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_movlb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_movlt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_mul.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_mullb.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_mullt.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_nbsl.c
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_nmatch.c
  clang/test/CodeGen/aarc

[PATCH] D124807: [clang][dataflow] Avoid assert for invalid cast to BoolValue

2022-05-03 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

Thanks for the patch!




Comment at: 
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp:1155
 
+// FIXME: Remove this test once it provides no additional test coverage.
+TEST_F(FlowConditionTest, DoesNotAssertForImplicitCastToBool) {

This  seems a worthwhile case to cover.  What about converting it to a more 
useful test, similar to the other branch tests?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124807

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


[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:8470-8473
+def err_expected_struct_pointer_argument : Error<
+  "expected pointer to struct as %ordinal0 argument to %1, found %2">;
+def err_expected_callable_argument : Error<
+  "expected a callable expression as %ordinal0 argument to %1, found %2">;

rsmith wrote:
> aaron.ballman wrote:
> > Should we combine these into:
> > ```
> > def err_builtin_dump_struct_expects : Error<
> >   "expected %select{pointer to struct|a callable expression}0 as %ordinal1 
> > argument to %2, found %3">;
> > ```
> > to reduce the number of diagnostics we have to tablegen?
> I'm indifferent. That kind of refactoring will probably decrease the chance 
> of these being reused for any other purpose, which might end up costing us 
> more diagnostics, and will need a magic number in the source code to select 
> between alternatives. Happy to do it if you think it's worthwhile, but I 
> don't have any measurements for how much each diagnostic ID costs.
Eh, let's skip it for now. I bring it up on occasion because we do run out of 
diagnostic IDs on occasion, but that's more a systemic concern.



Comment at: clang/lib/Sema/SemaChecking.cpp:572-574
+  // We don't know how to print this field. Print out its address
+  // with a format specifier that a smart tool will be able to
+  // recognize and treat specially.

rsmith wrote:
> aaron.ballman wrote:
> > Should we handle array types specifically, or should we continue to punt on 
> > those for now?
> I'd prefer to punt for now, if that's OK. I don't think this is hard to add, 
> but it's probably clearer to do it in a separate patch. There are also some 
> nontrivial questions there, eg: should we dump all elements or stop after 
> some limit? Should we dump trailing zeroes in an integer array? How should we 
> dump arrays of `char`? I'd prefer to not deal with those questions in this 
> patch :)
Absolutely fine to punt on it, because I agree there's a bunch of questions to 
answer there. I was also thinking about what to do with flexible array members 
or other trailing array objects.



Comment at: clang/lib/Sema/SemaChecking.cpp:573
+  // We don't know how to print this field. Print out its address
+  // with a format specifier that a smart tool will be able to
+  // recognize and treat specially.

rsmith wrote:
> yihanaa wrote:
> > Can we generate a warning diagnostic message when we see an unsupported 
> > type (perhaps temporarily not supported), what do you all think about?
> We could, but I'm leaning towards thinking that we shouldn't warn by default 
> at least. That would get in the way of the C++ use case where the type 
> actually is supported by the printing function; I'm not sure that we can 
> easily tell those cases apart. And it's probably not all that useful to 
> someone who just wants whatever information we can give them while debugging. 
> I'd be OK with adding a warning that's off by default, though. What would be 
> the intended use case here? Would an off-by-default warning satisfy it?
So long as we don't trigger UB, I think it's fine to not diagnose for 
unsupported types. But the UB cases do strike me as something we might want to 
warn about if we think they can be hit (specifically, these kinds of UB: 
https://eel.is/c++draft/cstdarg.syn#1).

As an example, do we properly handle dumping this case:
```
struct S {
  int &i;
  S(int &ref) : i(ref) {}
};
```
where the vararg argument is of reference type? I suppose another interesting 
question is:
```
struct S {
  int i;
};

void func() {
  S s;
  [=]() {
__builtin_dump_struct(&s, ::printf);
  };
}
```
(is S.i "an entity resulting from a lambda capture"?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-03 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:2442
+
+This builtin does not return a value.
+

rsmith wrote:
> erichkeane wrote:
> > I don't know if anyone would be using this value, but I wonder if there is 
> > value to making this a 'sum' of the results of `f`?  Less useful for the 
> > purposes of printf, but perhaps to a sprintf-type-function?  
> > 
> > Not sure if we have the use cases to support this however.
> I don't think you can use this directly with `sprintf` -- you'd need a 
> wrapper to update the write position as part of each call to `f`, and that 
> wrapper can handle accumulating the value returned from `sprintf`. In order 
> to do that, you'd want to provide an additional input argument that can be 
> modified as the dump progresses, and that can be used to return the overall 
> (desired) size too. So I don't think even the `sprintf` case provides 
> motivation for this, and it would add complexity (as well as making the 
> builtin less usable in the case where the printing function doesn't return 
> something addable).
> 
> I could see this being at least a little useful for a formatting function 
> that returns `std::string` or similar, but ... I think it's probably better 
> to let the formatting function deal with that itself through argument passing 
> instead of assuming that we can apply `+` to the results. WDYT?
I agree that we're probably better off just making the user write a wrapper 
function/functor to do so.  I was thinking about C folks, but you're right, 
they could pass a state object into their extended args.

I think we probably should just hold off on any attempts to do this until we 
find someone with a bonafide need.



Comment at: clang/lib/Sema/SemaChecking.cpp:595
+ PseudoObjectExpr::NoResult);
+TheCall->setType(Wrapper->getType());
+TheCall->setValueKind(Wrapper->getValueKind());

rsmith wrote:
> erichkeane wrote:
> > What is happening here?  I would expect the opposite to need to happen here 
> > (wrapper be set to match the call, not the other way around?).  
> This is the normal way we handle builtins with custom type checking: the 
> `SemaChecking` logic analyzes the builtin and sets the result type of the 
> call as appropriate, because the type we get from `Builtins.def` is 
> meaningless. As it happens, this is a degenerate case (compared to 
> `__builtin_reflect_struct` where this did something more interesting), 
> because the type of the `PseudoObjectExpr` is always `void` here; I can just 
> set that directly if you think that's clearer. It shouldn't matter much 
> anyway, given that the call is only used as the syntactic form of the 
> `PseudoObjectExpr`, so its type doesn't really affect anything. but following 
> the type and value kind of the `PseudoObjectExpr` seems "right" to me.
Ah, I see some other examples now, thanks for the explanation. I don't think 
setting to `void` is a good idea, in case we find a good reason to change the 
type; this ends up being just one more place we need to mess with it.



Comment at: clang/lib/Sema/SemaChecking.cpp:614
+  if (!PtrArgType->isPointerType() ||
+  !PtrArgType->getPointeeType()->isRecordType()) {
+S.Diag(PtrArgResult.get()->getBeginLoc(),

rsmith wrote:
> erichkeane wrote:
> > Is this sufficient?  Couldn't this be a pointer to a union?  Do you mean 
> > the suggestion?
> Allowing this is what the existing builtin did, and there were tests for it.
> 
> I'm not sure what the best thing to do with unions is -- especially when a 
> union appears as a struct member. Perhaps the least bad approach is to print 
> out all the union members and hope that nothing goes wrong. That'll crash in 
> some cases (eg, `union { const char *p; int n; };` when the `int` is the 
> active member), but that seems to be the nature of this builtin.
> 
> I've added a FIXME to `dumpRecordValue`.
SGTM!  We DO document a few times IIRC that we accept a 'struct' param(in fact, 
the comment on line 637 n ow says we do!), so I wanted to make sure we are 
consistent there.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[clang] 8bc29d1 - [clang][AArch64][SVE] Implement conditional operator for SVE vectors

2022-05-03 Thread David Truby via cfe-commits

Author: David Truby
Date: 2022-05-03T13:10:32Z
New Revision: 8bc29d14273b05b05d5a56e34c07948dc2c770d3

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

LOG: [clang][AArch64][SVE] Implement conditional operator for SVE vectors

This patch adds support for the conditional (ternary) operator on SVE
scalable vector types in C++, matching the behaviour for NEON vector
types. Like the conditional operator for NEON types, this is disabled in
C mode.

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

Added: 
clang/test/CodeGenCXX/aarch64-sve-vector-conditional-op.cpp
clang/test/SemaCXX/aarch64-sve-vector-conditional-op.cpp

Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/CodeGen/CGExprScalar.cpp
clang/lib/Sema/SemaExprCXX.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 114725498c982..7d33b5047a677 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11974,6 +11974,10 @@ class Sema final {
   QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
ExprResult &RHS,
SourceLocation QuestionLoc);
+
+  QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond,
+   ExprResult &LHS, ExprResult 
&RHS,
+   SourceLocation QuestionLoc);
   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
 bool ConvertArgs = true);
   QualType FindCompositePointerType(SourceLocation Loc,

diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index d3fe04d5a7915..2343c7e4afbbe 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -4642,7 +4642,8 @@ VisitAbstractConditionalOperator(const 
AbstractConditionalOperator *E) {
 return tmp5;
   }
 
-  if (condExpr->getType()->isVectorType()) {
+  if (condExpr->getType()->isVectorType() ||
+  condExpr->getType()->isVLSTBuiltinType()) {
 CGF.incrementProfileCounter(E);
 
 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 2af4a85c91c21..27ec863e7a35e 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -23,6 +23,7 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/AlignedAllocation.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/PartialDiagnostic.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TypeTraits.h"
@@ -40,6 +41,7 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/TypeSize.h"
 using namespace clang;
 using namespace sema;
 
@@ -6108,6 +6110,16 @@ static bool 
isValidVectorForConditionalCondition(ASTContext &Ctx,
   return EltTy->isIntegralType(Ctx);
 }
 
+static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx,
+ QualType CondTy) {
+  if (!CondTy->isVLSTBuiltinType())
+return false;
+  const QualType EltTy =
+  cast(CondTy.getCanonicalType())->getSveEltType(Ctx);
+  assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
+  return EltTy->isIntegralType(Ctx);
+}
+
 QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
ExprResult &RHS,
SourceLocation QuestionLoc) {
@@ -6199,6 +6211,89 @@ QualType Sema::CheckVectorConditionalTypes(ExprResult 
&Cond, ExprResult &LHS,
   return ResultType;
 }
 
+QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond,
+   ExprResult &LHS,
+   ExprResult &RHS,
+   SourceLocation QuestionLoc) 
{
+  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
+  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
+
+  QualType CondType = Cond.get()->getType();
+  const auto *CondBT = CondType->castAs();
+  QualType CondElementTy = CondBT->getSveEltType(Context);
+  llvm::ElementCount CondElementCount =
+  Context.getBuiltinVectorTypeInfo(CondBT).EC;
+
+  QualType LHSType = LHS.get()->getType();
+  const auto *LHSBT =
+  LHSType->isVLSTBuiltinType() ? LHSType->getAs() : nullptr;
+  QualType RHSType = RHS.get()->getType();
+  const auto *RHSBT =
+  RHSType->isVLSTBuiltinType() ? RHSType->getAs() : nullptr;
+
+  QualType ResultType;
+
+  if (LHSBT && RHSBT) {
+

[PATCH] D124091: [clang][AArch64][SVE] Implement conditional operator for SVE vectors

2022-05-03 Thread David Truby 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 rG8bc29d14273b: [clang][AArch64][SVE] Implement conditional 
operator for SVE vectors (authored by DavidTruby).

Changed prior to commit:
  https://reviews.llvm.org/D124091?vs=425541&id=426677#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124091

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/CodeGenCXX/aarch64-sve-vector-conditional-op.cpp
  clang/test/SemaCXX/aarch64-sve-vector-conditional-op.cpp

Index: clang/test/SemaCXX/aarch64-sve-vector-conditional-op.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/aarch64-sve-vector-conditional-op.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -verify -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -fsyntax-only %s
+
+// REQUIRES: aarch64-registered-target
+
+#include 
+
+void cond(svint8_t i8, svint16_t i16, svint32_t i32, svint64_t i64,
+  svuint8_t u8, svuint16_t u16, svuint32_t u32, svuint64_t u64,
+  svfloat16_t f16, svfloat32_t f32, svfloat64_t f64,
+  svbool_t b) {
+  (void) i8 < i8 ? i16 : i16; // expected-error{{invalid operands to binary expression}}
+  (void) i8 < i8 ? i32 : i32; // expected-error{{invalid operands to binary expression}}
+  (void) i8 < i8 ? i64 : i64; // expected-error{{invalid operands to binary expression}}
+
+  (void) i16 < i16 ? i16 : i8; // expected-error{{invalid operands to binary expression}}
+  (void) i16 < i16 ? i16 : i32; // expected-error{{invalid operands to binary expression}}
+  (void) i16 < i16 ? i16 : i64; // expected-error{{invalid operands to binary expression}}
+
+  (void) i16 < i16 ? i8 : i16; // expected-error{{invalid operands to binary expression}}
+  (void) i16 < i16 ? i32 : i16; // expected-error{{invalid operands to binary expression}}
+  (void) i16 < i16 ? i64 : i16; // expected-error{{invalid operands to binary expression}}
+}
\ No newline at end of file
Index: clang/test/CodeGenCXX/aarch64-sve-vector-conditional-op.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/aarch64-sve-vector-conditional-op.cpp
@@ -0,0 +1,224 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve \
+// RUN: -fallow-half-arguments-and-returns -disable-O0-optnone \
+// RUN:  -emit-llvm -o - %s | opt -S -sroa | FileCheck %s
+
+// REQUIRES: aarch64-registered-target
+
+#include 
+
+// CHECK-LABEL: @_Z9cond_boolu10__SVBool_tu10__SVBool_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CMP]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [[A]],  [[B]]
+// CHECK-NEXT:ret  [[VECTOR_SELECT]]
+//
+svbool_t cond_bool(svbool_t a, svbool_t b) {
+return a < b ? a : b;
+}
+
+// CHECK-LABEL: @_Z7cond_i8u10__SVInt8_tu10__SVInt8_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[CONV:%.*]] = zext  [[CMP]] to 
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CONV]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [[A]],  [[B]]
+// CHECK-NEXT:ret  [[VECTOR_SELECT]]
+//
+svint8_t cond_i8(svint8_t a, svint8_t b) {
+return a < b ? a : b;
+}
+
+// CHECK-LABEL: @_Z7cond_u8u11__SVUint8_tu11__SVUint8_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[CONV:%.*]] = zext  [[CMP]] to 
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CONV]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [[A]],  [[B]]
+// CHECK-NEXT:ret  [[VECTOR_SELECT]]
+//
+svuint8_t cond_u8(svuint8_t a, svuint8_t b) {
+return a < b ? a : b;
+}
+
+// CHECK-LABEL: @_Z8cond_i16u11__SVInt16_tu11__SVInt16_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[CONV:%.*]] = zext  [[CMP]] to 
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CONV]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [[A]],  [[B]]
+// CHECK-NEXT:ret  [[VECTOR_SELECT]]
+//
+svint16_t cond_i16(svint16_t a, svint16_t b) {
+return a < b ? a : b;
+}
+
+// CHECK-LABEL: @_Z8cond_u16u12__SVUint16_tu12__SVUint16_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[CONV:%.*]] = zext  [[CMP]] to 
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CONV]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [

[PATCH] D97625: fix check-clang-tools tests that fail due to Windows CRLF line endings

2022-05-03 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

> So I went ahead and just fixed this in 
> ac5f7be6a8688955a282becf00eebc542238a86b 
> .

As far as we can tell, this broke clang-move/move-used-helper-decls.cpp on our 
windows bot. D124563  then fixed it again. 
(So all good now, just for the record.)

https://crbug.com/1319491 was our upstream bug.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97625

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


[PATCH] D124667: [flang][driver] Add support for consuming LLVM IR/BC files

2022-05-03 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski marked 8 inline comments as done.
awarzynski added a comment.

Thanks for the review @rovka!




Comment at: flang/lib/Frontend/FrontendActions.cpp:86
+
+  // ... otherwise, generate an MLIR module from the input Fortran source
   bool res = RunPrescan() && RunParse() && RunSemanticChecks();

rovka wrote:
> Nit: Should we assert that the language is Language::Fortran at this point?
No harm in doing so 👍 !



Comment at: flang/test/Driver/emit-asm-from-llvm-bc.ll:9
+;-
+; RUN: rm -f %t.bc
+; RUN: %flang_fc1 -emit-llvm-bc %s -o %t.bc

rovka wrote:
> Have you tried %basename_t.bc instead? You might be able to skip all the 
> `rm`s then...
IIUC, the only difference between `%t.bc`and ` %basename_t.bc`  is that former 
contains a directory name and the file extension and latter does not. In either 
case, LIT won't delete it :(

I like %t a bit more as this way we make sure that the output lands in the 
right temporary directory.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124667

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


[PATCH] D124667: [flang][driver] Add support for consuming LLVM IR/BC files

2022-05-03 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 426678.
awarzynski marked 2 inline comments as done.
awarzynski added a comment.

Add an assert, make some editorial changes in comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124667

Files:
  clang/include/clang/Driver/Types.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/Types.cpp
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/FrontendOptions.cpp
  flang/test/Driver/emit-asm-from-llvm-bc.ll
  flang/test/Driver/emit-asm-from-llvm.ll
  flang/test/Driver/missing-triple.ll
  flang/test/Driver/override-triple.ll
  flang/test/lit.cfg.py

Index: flang/test/lit.cfg.py
===
--- flang/test/lit.cfg.py
+++ flang/test/lit.cfg.py
@@ -27,7 +27,8 @@
 # suffixes: A list of file extensions to treat as test files.
 config.suffixes = ['.c', '.cpp', '.f', '.F', '.ff', '.FOR', '.for', '.f77', '.f90', '.F90',
'.ff90', '.f95', '.F95', '.ff95', '.fpp', '.FPP', '.cuf'
-   '.CUF', '.f18', '.F18', '.fir', '.f03', '.F03', '.f08', '.F08']
+   '.CUF', '.f18', '.F18', '.fir', '.f03', '.F03', '.f08',
+   '.F08', '.ll']
 
 config.substitutions.append(('%PATH%', config.environment['PATH']))
 config.substitutions.append(('%llvmshlibdir', config.llvm_shlib_dir))
Index: flang/test/Driver/override-triple.ll
===
--- /dev/null
+++ flang/test/Driver/override-triple.ll
@@ -0,0 +1,25 @@
+; Verify that the module triple is overridden by the driver - even in the presence
+; of a module triple.
+; NOTE: At the time of writing, the tested behaviour was consistent with Clang
+
+;-
+; RUN COMMANDS
+;-
+; RUN: %flang_fc1 -S %s -o - 2>&1 | FileCheck %s
+; RUN: %flang -S  %s -o - 2>&1 | FileCheck %s
+
+;
+; EXPECTED OUTPUT
+;
+; CHECK: warning: overriding the module target triple with {{.*}}
+
+;--
+; INPUT
+;--
+; For the triple to be overridden by the driver, it needs to be different to the host triple.
+; Use a random string to guarantee that.
+target triple = "invalid-triple"
+
+define void @foo() {
+  ret void
+}
Index: flang/test/Driver/missing-triple.ll
===
--- /dev/null
+++ flang/test/Driver/missing-triple.ll
@@ -0,0 +1,21 @@
+; Verify that the module triple is overridden by the driver - even when the
+; module triple is missing.
+; NOTE: At the time of writing, the tested behaviour was consistent with Clang
+
+;-
+; RUN COMMANDS
+;-
+; RUN: %flang_fc1 -S %s -o - 2>&1 | FileCheck %s
+; RUN: %flang -S  %s -o - 2>&1 | FileCheck %s
+
+;
+; EXPECTED OUTPUT
+;
+; CHECK: warning: overriding the module target triple with {{.*}}
+
+;--
+; INPUT
+;--
+define void @foo() {
+  ret void
+}
Index: flang/test/Driver/emit-asm-from-llvm.ll
===
--- /dev/null
+++ flang/test/Driver/emit-asm-from-llvm.ll
@@ -0,0 +1,23 @@
+; Verify that the driver can consume LLVM IR files. The expected assembly is
+; fairly generic (verified on AArch64 and X86_64), but we may need to tweak when
+; testing on other platforms. Note that the actual output doesn't matter
+; as long as it's in Assembly format.
+
+;-
+; RUN COMMANDS
+;-
+; RUN: %flang_fc1 -S %s -o - | FileCheck %s
+; RUN: %flang -S  %s -o - | FileCheck %s
+
+;
+; EXPECTED OUTPUT
+;
+; CHECK-LABEL: foo:
+; CHECK: ret
+
+;--
+; INPUT
+;--
+define void @foo() {
+  ret void
+}
Index: flang/test/Driver/emit-asm-from-llvm-bc.ll
===
--- /dev/null
+++ flang/test/Driver/emit-asm-from-llvm-bc.ll
@@ -0,0 +1,30 @@
+; Verify that the driver can consume LLVM BC files. The expected assembly is
+; fairly generic (tested on AArch64 and X86_64), but we may need to tweak when
+; testing on other platforms. Note that the actual output doesn't matter as
+; long as it's in Assembly format.
+
+;-
+; RUN COMMANDS
+;-
+; RUN: rm -f %t.bc
+; RUN: %flang_fc1 -emit-llvm-bc %s -o %t.bc
+; RUN: %flang_fc1 -S -o - %t.bc | FileCheck %s
+; RUN: rm -f %t.bc
+
+; RUN: rm -f %t.bc
+; RUN: %flang -c -emit-llvm %s -o %t.bc
+; RUN: %flang -S -o - %t.bc | FileCheck %s
+; RUN: rm -f %t.bc
+
+;
+; EXPECTED OUTPUT
+;
+; CHECK-LABEL: foo:
+; CHECK: ret
+
+;--
+; INPUT
+;--
+define void @foo() {
+  ret void
+}
Index: flang/lib/Frontend/FrontendOptions.cpp
===
--- flang/lib/Frontend/FrontendOptions.cpp
+++ flang/lib/Frontend/FrontendOptions.cpp
@@ -35,5 +35,9 @@
   if (isFixedFormSuffix(ex

[PATCH] D121150: [pseudo][WIP] Implement a GLR parser.

2022-05-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 426679.
hokein marked 6 inline comments as done.
hokein added a comment.

address remaining comments:

- return GSS::node in the NewHeadCallback, rather the fields of GSS::Node;
- remove the unncessary NewHeadResult structure in unittest;


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121150

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
  clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
  clang-tools-extra/pseudo/lib/CMakeLists.txt
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/test/glr.cpp
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/CMakeLists.txt
  clang-tools-extra/pseudo/unittests/GLRTest.cpp

Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -0,0 +1,393 @@
+//===--- GLRTest.cpp - Test the GLR parser --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang-pseudo/GLR.h"
+#include "clang-pseudo/Grammar.h"
+#include "clang-pseudo/Token.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/TokenKinds.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace pseudo {
+namespace {
+
+using Action = LRTable::Action;
+using std::placeholders::_1;
+using std::placeholders::_2;
+using std::placeholders::_3;
+using testing::AllOf;
+
+MATCHER_P(state, StateID, "") { return arg->State == StateID; }
+MATCHER_P(parsedSymbol, FNode, "") { return arg->Payload == FNode; }
+MATCHER_P(parsedSymbolID, SID, "") { return arg->Payload->symbol() == SID; }
+
+
+// llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const NewHeadResult &R) {
+//   std::vector ParentStates;
+//   for (const auto &P : R.Parents)
+// ParentStates.push_back(llvm::formatv("{0}", P->State));
+//   OS << llvm::formatv("state {0}, parsed symbol {1}, parents {2}", R.State,
+//   R.Parsed->symbol(), llvm::join(ParentStates, " "));
+//   return OS;
+// }
+
+testing::Matcher
+parents(llvm::ArrayRef Parents) {
+  return testing::Property(&GSS::Node::parents,
+   testing::UnorderedElementsAreArray(Parents));
+}
+
+class GLRTest : public ::testing::Test {
+public:
+  void build(llvm::StringRef GrammarBNF) {
+std::vector Diags;
+G = Grammar::parseBNF(GrammarBNF, Diags);
+  }
+
+  void buildGrammar(std::vector Nonterminals,
+std::vector Rules) {
+Nonterminals.push_back("_");
+llvm::sort(Nonterminals);
+Nonterminals.erase(std::unique(Nonterminals.begin(), Nonterminals.end()),
+   Nonterminals.end());
+std::string FakeTestBNF;
+for (const auto &NT : Nonterminals)
+  FakeTestBNF += llvm::formatv("{0} := {1}\n", "_", NT);
+FakeTestBNF += llvm::join(Rules, "\n");
+build(FakeTestBNF);
+  }
+
+  SymbolID id(llvm::StringRef Name) const {
+for (unsigned I = 0; I < NumTerminals; ++I)
+  if (G->table().Terminals[I] == Name)
+return tokenSymbol(static_cast(I));
+for (SymbolID ID = 0; ID < G->table().Nonterminals.size(); ++ID)
+  if (G->table().Nonterminals[ID].Name == Name)
+return ID;
+ADD_FAILURE() << "No such symbol found: " << Name;
+return 0;
+  }
+
+  RuleID ruleFor(llvm::StringRef NonterminalName) const {
+auto RuleRange = G->table().Nonterminals[id(NonterminalName)].RuleRange;
+if (RuleRange.End - RuleRange.Start == 1)
+  return G->table().Nonterminals[id(NonterminalName)].RuleRange.Start;
+ADD_FAILURE() << "Expected a single rule for " << NonterminalName
+  << ", but it has " << RuleRange.End - RuleRange.Start
+  << " rule!\n";
+return 0;
+  }
+
+  NewHeadCallback captureNewHeads() {
+return [this](const GSS::Node *NewHead) {
+  NewHeadResults.push_back(NewHead);
+};
+  };
+
+protected:
+  std::unique_ptr G;
+  ForestArena Arena;
+  GSS GSS;
+  std::vector NewHeadResults;
+};
+
+TEST_F(GLRTest, ShiftMergingHeads) {
+  // Given a test case where we have two heads 1, 2, 3 in the GSS, the heads 1,
+  // 2 have shift actions to reach state 4, and the head 3 has a shift action to
+  // reach state 5:
+  //   0--1
+  //   └--2
+  //   └--3
+  // After the shift action, the GSS (with new heads 4, 5) is:
+  //   0---1---4
+  //   └---2---┘
+  //   └---3---5
+  auto *GSSNode0 =
+  GSS.addNode(/*State=*/0, /*ForestNode=*/nullptr, /*Parents=*/{});
+  auto *GSSNode1 =
+  GSS.a

[PATCH] D121150: [pseudo] Implement the GLR parsing algorithm.

2022-05-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/GLR.h:143
+// parsing process (glrShift, or glrReduce).
+using NewHeadCallback =
+std::function nit: this is always used synchronously, so llvm::function_ref?
we have a `captureNewHeads` method which returns this callback in unittest, 
returning llvm::function_ref is not safe -- we could make it return a 
std::function, but it would be nice to have a unified signature.



Comment at: clang-tools-extra/pseudo/unittests/GLRTest.cpp:34
+
+struct NewHeadResult {
+  LRTable::StateID State;

sammccall wrote:
> this looks so much like a GSS node: why not just use a GSS node?
oh, right. I added this because I didn't expose the GSS in the `Params` in my 
previous version, I needed to store the Parents. Right now it is not needed, we 
can use the GSS::Node directly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121150

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


[PATCH] D121150: [pseudo] Implement the GLR parsing algorithm.

2022-05-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 426680.
hokein retitled this revision from "[pseudo] Implement the GLR parsing 
algorithm.  " to "[pseudo] Implement the GLR parsing algorithm.".
hokein added a comment.

fix a dangling reference of the source text in clang-pseudo.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121150

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
  clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
  clang-tools-extra/pseudo/lib/CMakeLists.txt
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/test/glr.cpp
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/CMakeLists.txt
  clang-tools-extra/pseudo/unittests/GLRTest.cpp

Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -0,0 +1,393 @@
+//===--- GLRTest.cpp - Test the GLR parser --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang-pseudo/GLR.h"
+#include "clang-pseudo/Grammar.h"
+#include "clang-pseudo/Token.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/TokenKinds.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace pseudo {
+namespace {
+
+using Action = LRTable::Action;
+using std::placeholders::_1;
+using std::placeholders::_2;
+using std::placeholders::_3;
+using testing::AllOf;
+
+MATCHER_P(state, StateID, "") { return arg->State == StateID; }
+MATCHER_P(parsedSymbol, FNode, "") { return arg->Payload == FNode; }
+MATCHER_P(parsedSymbolID, SID, "") { return arg->Payload->symbol() == SID; }
+
+
+// llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const NewHeadResult &R) {
+//   std::vector ParentStates;
+//   for (const auto &P : R.Parents)
+// ParentStates.push_back(llvm::formatv("{0}", P->State));
+//   OS << llvm::formatv("state {0}, parsed symbol {1}, parents {2}", R.State,
+//   R.Parsed->symbol(), llvm::join(ParentStates, " "));
+//   return OS;
+// }
+
+testing::Matcher
+parents(llvm::ArrayRef Parents) {
+  return testing::Property(&GSS::Node::parents,
+   testing::UnorderedElementsAreArray(Parents));
+}
+
+class GLRTest : public ::testing::Test {
+public:
+  void build(llvm::StringRef GrammarBNF) {
+std::vector Diags;
+G = Grammar::parseBNF(GrammarBNF, Diags);
+  }
+
+  void buildGrammar(std::vector Nonterminals,
+std::vector Rules) {
+Nonterminals.push_back("_");
+llvm::sort(Nonterminals);
+Nonterminals.erase(std::unique(Nonterminals.begin(), Nonterminals.end()),
+   Nonterminals.end());
+std::string FakeTestBNF;
+for (const auto &NT : Nonterminals)
+  FakeTestBNF += llvm::formatv("{0} := {1}\n", "_", NT);
+FakeTestBNF += llvm::join(Rules, "\n");
+build(FakeTestBNF);
+  }
+
+  SymbolID id(llvm::StringRef Name) const {
+for (unsigned I = 0; I < NumTerminals; ++I)
+  if (G->table().Terminals[I] == Name)
+return tokenSymbol(static_cast(I));
+for (SymbolID ID = 0; ID < G->table().Nonterminals.size(); ++ID)
+  if (G->table().Nonterminals[ID].Name == Name)
+return ID;
+ADD_FAILURE() << "No such symbol found: " << Name;
+return 0;
+  }
+
+  RuleID ruleFor(llvm::StringRef NonterminalName) const {
+auto RuleRange = G->table().Nonterminals[id(NonterminalName)].RuleRange;
+if (RuleRange.End - RuleRange.Start == 1)
+  return G->table().Nonterminals[id(NonterminalName)].RuleRange.Start;
+ADD_FAILURE() << "Expected a single rule for " << NonterminalName
+  << ", but it has " << RuleRange.End - RuleRange.Start
+  << " rule!\n";
+return 0;
+  }
+
+  NewHeadCallback captureNewHeads() {
+return [this](const GSS::Node *NewHead) {
+  NewHeadResults.push_back(NewHead);
+};
+  };
+
+protected:
+  std::unique_ptr G;
+  ForestArena Arena;
+  GSS GSS;
+  std::vector NewHeadResults;
+};
+
+TEST_F(GLRTest, ShiftMergingHeads) {
+  // Given a test case where we have two heads 1, 2, 3 in the GSS, the heads 1,
+  // 2 have shift actions to reach state 4, and the head 3 has a shift action to
+  // reach state 5:
+  //   0--1
+  //   └--2
+  //   └--3
+  // After the shift action, the GSS (with new heads 4, 5) is:
+  //   0---1---4
+  //   └---2---┘
+  //   └---3---5
+  auto *GSSNode0 =
+  GSS.addNode(/*State=*/0, /*ForestNode=*/nullptr, /*Parents=*/{});
+  auto *GSSNode1 =
+  GSS.addNode(

[clang-tools-extra] eac22d0 - [pseudo] Implement the GLR parsing algorithm.

2022-05-03 Thread Haojian Wu via cfe-commits

Author: Sam McCall
Date: 2022-05-03T15:42:07+02:00
New Revision: eac22d0754f70df10ea0eb6f59cbd1ef012ab5a4

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

LOG: [pseudo] Implement the GLR parsing algorithm.

This patch implements a standard GLR parsing algorithm, the
core piece of the pseudoparser.

- it parses preprocessed C++ code, currently it supports correct code
  only and parse them as a translation-unit;
- it produces a forest which stores all possible trees in an efficient
  manner (only a single node being build for per (SymbolID, Token Range));
  no disambiguation yet;

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

Added: 
clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
clang-tools-extra/pseudo/lib/GLR.cpp
clang-tools-extra/pseudo/test/glr.cpp
clang-tools-extra/pseudo/unittests/GLRTest.cpp

Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
clang-tools-extra/pseudo/lib/CMakeLists.txt
clang-tools-extra/pseudo/tool/ClangPseudo.cpp
clang-tools-extra/pseudo/unittests/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
index 2b22fd564f742..39b35597ed5e3 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
@@ -157,6 +157,10 @@ class ForestArena {
 return create(ForestNode::Opaque, SID, Start, 0, {});
   }
 
+  ForestNode &createTerminal(tok::TokenKind TK, Token::Index Start) {
+return create(ForestNode::Terminal, tokenSymbol(TK), Start, 0, {});
+  }
+
   size_t nodeCount() const { return NodeCount; }
   size_t bytes() const { return Arena.getBytesAllocated() + sizeof(this); }
 

diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
new file mode 100644
index 0..e769ffc0d3c82
--- /dev/null
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
@@ -0,0 +1,164 @@
+//===--- GLR.h - Implement a GLR parsing algorithm ---*- 
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 implements a standard Generalized LR (GLR) parsing algorithm.
+//
+// The GLR parser behaves as a normal LR parser until it encounters a conflict.
+// To handle a conflict (where there are multiple actions could perform), the
+// parser will simulate nondeterminism by doing a breadth-first search
+// over all the possibilities.
+//
+// Basic mechanisims of the GLR parser:
+//  - A number of processes are operated in parallel.
+//  - Each process has its own parsing stack and behaves as a standard
+//determinism LR parser.
+//  - When a process encounters a conflict, it will be fork (one for each
+//avaiable action).
+//  - When a process encounters an error, it is abandoned.
+//  - All process are synchronized by the lookahead token: they perfrom shift
+//action at the same time, which means some processes need wait until other
+//processes have performed all reduce actions.
+//
+//===--===//
+
+#ifndef CLANG_PSEUDO_GLR_H
+#define CLANG_PSEUDO_GLR_H
+
+#include "clang-pseudo/Forest.h"
+#include "clang-pseudo/Grammar.h"
+#include "clang-pseudo/LRTable.h"
+#include "llvm/Support/Allocator.h"
+#include 
+
+namespace clang {
+namespace pseudo {
+
+// A Graph-Structured Stack efficiently represents all parse stacks of a GLR
+// parser.
+//
+// Each node stores a parse state, the last parsed ForestNode, and the parent
+// node. There may be several heads (top of stack), and the parser operates by:
+// - shift: pushing terminal symbols on top of the stack
+// - reduce: replace N symbols on top of the stack with one nonterminal
+//
+// The structure is a DAG rather than a linear stack:
+// - GLR allows multiple actions (conflicts) on the same head, producing forks
+//   where several nodes have the same parent
+// - The parser merges nodes with the same (state, ForestNode), producing joins
+//   where one node has multiple parents
+//
+// The parser is responsible for creating nodes and keeping track of the set of
+// heads. The GSS class is mostly an arena for them.
+struct GSS {
+  // A node represents a partial parse of the input up to some point.
+  //
+  // It is the equivalent of a frame in an LR parse stack.
+  // Like such a frame, it has an LR parse state and a syntax-tree node
+  // representing the last parsed symbol (a ForestNod

[PATCH] D121150: [pseudo] Implement the GLR parsing algorithm.

2022-05-03 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.
Closed by commit rGeac22d0754f7: [pseudo] Implement the GLR parsing algorithm. 
(authored by sammccall, committed by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121150

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
  clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
  clang-tools-extra/pseudo/lib/CMakeLists.txt
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/test/glr.cpp
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/CMakeLists.txt
  clang-tools-extra/pseudo/unittests/GLRTest.cpp

Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -0,0 +1,393 @@
+//===--- GLRTest.cpp - Test the GLR parser --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang-pseudo/GLR.h"
+#include "clang-pseudo/Grammar.h"
+#include "clang-pseudo/Token.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/TokenKinds.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace pseudo {
+namespace {
+
+using Action = LRTable::Action;
+using std::placeholders::_1;
+using std::placeholders::_2;
+using std::placeholders::_3;
+using testing::AllOf;
+
+MATCHER_P(state, StateID, "") { return arg->State == StateID; }
+MATCHER_P(parsedSymbol, FNode, "") { return arg->Payload == FNode; }
+MATCHER_P(parsedSymbolID, SID, "") { return arg->Payload->symbol() == SID; }
+
+
+// llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const NewHeadResult &R) {
+//   std::vector ParentStates;
+//   for (const auto &P : R.Parents)
+// ParentStates.push_back(llvm::formatv("{0}", P->State));
+//   OS << llvm::formatv("state {0}, parsed symbol {1}, parents {2}", R.State,
+//   R.Parsed->symbol(), llvm::join(ParentStates, " "));
+//   return OS;
+// }
+
+testing::Matcher
+parents(llvm::ArrayRef Parents) {
+  return testing::Property(&GSS::Node::parents,
+   testing::UnorderedElementsAreArray(Parents));
+}
+
+class GLRTest : public ::testing::Test {
+public:
+  void build(llvm::StringRef GrammarBNF) {
+std::vector Diags;
+G = Grammar::parseBNF(GrammarBNF, Diags);
+  }
+
+  void buildGrammar(std::vector Nonterminals,
+std::vector Rules) {
+Nonterminals.push_back("_");
+llvm::sort(Nonterminals);
+Nonterminals.erase(std::unique(Nonterminals.begin(), Nonterminals.end()),
+   Nonterminals.end());
+std::string FakeTestBNF;
+for (const auto &NT : Nonterminals)
+  FakeTestBNF += llvm::formatv("{0} := {1}\n", "_", NT);
+FakeTestBNF += llvm::join(Rules, "\n");
+build(FakeTestBNF);
+  }
+
+  SymbolID id(llvm::StringRef Name) const {
+for (unsigned I = 0; I < NumTerminals; ++I)
+  if (G->table().Terminals[I] == Name)
+return tokenSymbol(static_cast(I));
+for (SymbolID ID = 0; ID < G->table().Nonterminals.size(); ++ID)
+  if (G->table().Nonterminals[ID].Name == Name)
+return ID;
+ADD_FAILURE() << "No such symbol found: " << Name;
+return 0;
+  }
+
+  RuleID ruleFor(llvm::StringRef NonterminalName) const {
+auto RuleRange = G->table().Nonterminals[id(NonterminalName)].RuleRange;
+if (RuleRange.End - RuleRange.Start == 1)
+  return G->table().Nonterminals[id(NonterminalName)].RuleRange.Start;
+ADD_FAILURE() << "Expected a single rule for " << NonterminalName
+  << ", but it has " << RuleRange.End - RuleRange.Start
+  << " rule!\n";
+return 0;
+  }
+
+  NewHeadCallback captureNewHeads() {
+return [this](const GSS::Node *NewHead) {
+  NewHeadResults.push_back(NewHead);
+};
+  };
+
+protected:
+  std::unique_ptr G;
+  ForestArena Arena;
+  GSS GSS;
+  std::vector NewHeadResults;
+};
+
+TEST_F(GLRTest, ShiftMergingHeads) {
+  // Given a test case where we have two heads 1, 2, 3 in the GSS, the heads 1,
+  // 2 have shift actions to reach state 4, and the head 3 has a shift action to
+  // reach state 5:
+  //   0--1
+  //   └--2
+  //   └--3
+  // After the shift action, the GSS (with new heads 4, 5) is:
+  //   0---1---4
+  //   └---2---┘
+  //   └---3---5
+  auto *GSSNode0 =
+  GSS.addNode(/*State=*/0, /*ForestNode=*/nullptr, /*Parents=*/{});
+  auto *GSSNode1 =
+  GSS.addNode(/*State=*/0, /

[clang-tools-extra] 860eabb - Revert "[pseudo] Implement the GLR parsing algorithm."

2022-05-03 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-05-03T15:54:10+02:00
New Revision: 860eabb3953a104b2b85398c705cd32e33d86689

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

LOG: Revert "[pseudo] Implement the GLR parsing algorithm."

This breaks some buildbots (on the declaration GSS& GSS), will fix it
later.

This reverts commit eac22d0754f70df10ea0eb6f59cbd1ef012ab5a4.

Added: 


Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
clang-tools-extra/pseudo/lib/CMakeLists.txt
clang-tools-extra/pseudo/tool/ClangPseudo.cpp
clang-tools-extra/pseudo/unittests/CMakeLists.txt

Removed: 
clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
clang-tools-extra/pseudo/lib/GLR.cpp
clang-tools-extra/pseudo/test/glr.cpp
clang-tools-extra/pseudo/unittests/GLRTest.cpp



diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
index 39b35597ed5e3..2b22fd564f742 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
@@ -157,10 +157,6 @@ class ForestArena {
 return create(ForestNode::Opaque, SID, Start, 0, {});
   }
 
-  ForestNode &createTerminal(tok::TokenKind TK, Token::Index Start) {
-return create(ForestNode::Terminal, tokenSymbol(TK), Start, 0, {});
-  }
-
   size_t nodeCount() const { return NodeCount; }
   size_t bytes() const { return Arena.getBytesAllocated() + sizeof(this); }
 

diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
deleted file mode 100644
index e769ffc0d3c82..0
--- a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
+++ /dev/null
@@ -1,164 +0,0 @@
-//===--- GLR.h - Implement a GLR parsing algorithm ---*- 
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 implements a standard Generalized LR (GLR) parsing algorithm.
-//
-// The GLR parser behaves as a normal LR parser until it encounters a conflict.
-// To handle a conflict (where there are multiple actions could perform), the
-// parser will simulate nondeterminism by doing a breadth-first search
-// over all the possibilities.
-//
-// Basic mechanisims of the GLR parser:
-//  - A number of processes are operated in parallel.
-//  - Each process has its own parsing stack and behaves as a standard
-//determinism LR parser.
-//  - When a process encounters a conflict, it will be fork (one for each
-//avaiable action).
-//  - When a process encounters an error, it is abandoned.
-//  - All process are synchronized by the lookahead token: they perfrom shift
-//action at the same time, which means some processes need wait until other
-//processes have performed all reduce actions.
-//
-//===--===//
-
-#ifndef CLANG_PSEUDO_GLR_H
-#define CLANG_PSEUDO_GLR_H
-
-#include "clang-pseudo/Forest.h"
-#include "clang-pseudo/Grammar.h"
-#include "clang-pseudo/LRTable.h"
-#include "llvm/Support/Allocator.h"
-#include 
-
-namespace clang {
-namespace pseudo {
-
-// A Graph-Structured Stack efficiently represents all parse stacks of a GLR
-// parser.
-//
-// Each node stores a parse state, the last parsed ForestNode, and the parent
-// node. There may be several heads (top of stack), and the parser operates by:
-// - shift: pushing terminal symbols on top of the stack
-// - reduce: replace N symbols on top of the stack with one nonterminal
-//
-// The structure is a DAG rather than a linear stack:
-// - GLR allows multiple actions (conflicts) on the same head, producing forks
-//   where several nodes have the same parent
-// - The parser merges nodes with the same (state, ForestNode), producing joins
-//   where one node has multiple parents
-//
-// The parser is responsible for creating nodes and keeping track of the set of
-// heads. The GSS class is mostly an arena for them.
-struct GSS {
-  // A node represents a partial parse of the input up to some point.
-  //
-  // It is the equivalent of a frame in an LR parse stack.
-  // Like such a frame, it has an LR parse state and a syntax-tree node
-  // representing the last parsed symbol (a ForestNode in our case).
-  // Unlike a regular LR stack frame, it may have multiple parents.
-  //
-  // Nodes are not exactly pushed and popped on the stack: pushing is just
-  // allocating a new head node with a parent pointer to the old head. Popping
-  // is just forgetting about a nod

[PATCH] D124432: Fix issues with using clangd with C++ modules

2022-05-03 Thread Kugan Vivekanandarajah via Phabricator via cfe-commits
kuganv updated this revision to Diff 426690.

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

https://reviews.llvm.org/D124432

Files:
  clang-tools-extra/clangd/test/modules-options-compatablity-test/A.h
  clang-tools-extra/clangd/test/modules-options-compatablity-test/B.h
  
clang-tools-extra/clangd/test/modules-options-compatablity-test/compile_commands.json
  
clang-tools-extra/clangd/test/modules-options-compatablity-test/definition.jsonrpc
  
clang-tools-extra/clangd/test/modules-options-compatablity-test/module.modulemap
  clang-tools-extra/clangd/test/modules-options-compatablity-test/use.c
  clang-tools-extra/clangd/test/modules-options-compatablity.test
  clang/include/clang/Basic/LangOptions.def
  clang/lib/Serialization/ASTReader.cpp

Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -3077,6 +3077,10 @@
   return Err;
 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
   return Err;
+if (PP.getPreprocessorOpts().GeneratePreamble &&
+!PP.getPreprocessorOpts().WriteCommentListToPCH) {
+  break;
+}
 CommentsCursors.push_back(std::make_pair(C, &F));
 break;
   }
Index: clang/include/clang/Basic/LangOptions.def
===
--- clang/include/clang/Basic/LangOptions.def
+++ clang/include/clang/Basic/LangOptions.def
@@ -387,7 +387,7 @@
 
 LANGOPT(XLPragmaPack, 1, 0, "IBM XL #pragma pack handling")
 
-LANGOPT(RetainCommentsFromSystemHeaders, 1, 0, "retain documentation comments from system headers in the AST")
+COMPATIBLE_LANGOPT(RetainCommentsFromSystemHeaders, 1, 0, "retain documentation comments from system headers in the AST")
 
 LANGOPT(SanitizeAddressFieldPadding, 2, 0, "controls how aggressive is ASan "
"field padding (0: none, 1:least "
Index: clang-tools-extra/clangd/test/modules-options-compatablity.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity.test
@@ -0,0 +1,10 @@
+
+# RUN: rm -rf %t && mkdir -p %t
+# RUN: cp -r %S/modules-options-compatablity-test/* %t
+# RUN: mkdir -p %t/prebuilt
+# RUN: sed -i -e "s|DIRECTORY|%t|g" %t/definition.jsonrpc
+# RUN: sed -i -e "s|DIRECTORY|%t|g" %t/compile_commands.json
+# RUN: %clang -cc1 -emit-module -o %t/prebuilt/A.pcm -fmodules %t/module.modulemap -fmodule-name=A
+# RUN: %clang -cc1 -fretain-comments-from-system-headers -emit-module -o %t/prebuilt/B.pcm -fmodules %t/module.modulemap -fmodule-name=B -fprebuilt-module-path=%t/prebuilt
+# RUN: rm %t/*.h
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc
Index: clang-tools-extra/clangd/test/modules-options-compatablity-test/use.c
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity-test/use.c
@@ -0,0 +1,5 @@
+/* use */
+#include 
+#include 
+
+void use() { a(); }
Index: clang-tools-extra/clangd/test/modules-options-compatablity-test/module.modulemap
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity-test/module.modulemap
@@ -0,0 +1,8 @@
+/* module.modulemap */
+module A {
+  header "A.h"
+}
+module B {
+  header "B.h"
+  export *
+}
Index: clang-tools-extra/clangd/test/modules-options-compatablity-test/definition.jsonrpc
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity-test/definition.jsonrpc
@@ -0,0 +1,28 @@
+{
+  "jsonrpc": "2.0",
+"id": 0,
+"method": "initialize",
+"params": {
+  "processId": 123,
+  "rootPath": "clangd",
+  "capabilities": { "window": { "workDoneProgress": true, "implicitWorkDoneProgressCreate": true} },
+  "trace": "off"
+}
+}
+---
+{
+  "jsonrpc": "2.0",
+"method": "textDocument/didOpen",
+"params": {
+  "textDocument": {
+"uri": "file://DIRECTORY/use.c",
+"languageId": "cpp",
+"version": 1,
+"text": "#include \"B.h\"\nvoid use(){\na();\n}"
+  }
+}
+}
+---
+{"jsonrpc":"2.0","id":3,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: clang-tools-extra/clangd/test/modules-options-compatablity-test/compile_commands.json
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity-test/compile_commands.json
@@ -0,0 +1,5 @@
+[{
+  "directory": ".",
+  "command": "clang -emit-obj DIRECTORY/use.c -fno-modules-global -fmodules -fmodules-cache-path=/DOES/NOT/EXIST  -fno-builtin-module-map -fno-implicit-modules  -fimplicit-module-maps -fprebuilt-module-path=DIRECTORY/pr

[PATCH] D124715: Use QoS class Utility for ThreadPriority::Low on Mac

2022-05-03 Thread David Goldman via Phabricator via cfe-commits
dgoldman accepted this revision.
dgoldman added a comment.
This revision is now accepted and ready to land.

In D124715#3484058 , @stefanhaller 
wrote:

> Fix documentation of ThreadPriority::Low (was: Background), and move it up 
> from
> set_thread_priority to ThreadPriority.
>
> (Is it ok that there's no documentation left for set_thread_priority? I 
> couldn't
> come up with anything that's not trivial and redundant, e.g. "Sets the 
> priority
> of the current thread.")

LGTM, no need for a trivial comment, the priorities themselves are documented.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

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


[clang] 50b51b1 - Fix a typo in an OpenMP test

2022-05-03 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-03T10:01:46-04:00
New Revision: 50b51b1860acbfb775d5e2eee3310e25c635d667

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

LOG: Fix a typo in an OpenMP test

This fixes the typo and corrects the default OpenMP version being
tested.

Added: 


Modified: 
clang/test/OpenMP/predefined_macro.c

Removed: 




diff  --git a/clang/test/OpenMP/predefined_macro.c 
b/clang/test/OpenMP/predefined_macro.c
index c9722d596d4d6..330dbe34569fe 100644
--- a/clang/test/OpenMP/predefined_macro.c
+++ b/clang/test/OpenMP/predefined_macro.c
@@ -9,7 +9,7 @@
 // -fopenmp option is specified
 #ifndef _OPENMP
 #error "No _OPENMP macro is defined with -fopenmp option"
-#elsif _OPENMP != 201107
+#elif _OPENMP != 201811
 #error "_OPENMP has incorrect value"
 #endif //_OPENMP
 #else



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


[clang] 50c959b - Add explicit OpenMP 5.0 case for version macros; NFC

2022-05-03 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-03T10:01:47-04:00
New Revision: 50c959b4fa4288127026a6a908c9a6d74b6f5d11

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

LOG: Add explicit OpenMP 5.0 case for version macros; NFC

This adds an explicit case for OpenMP 5.0 as a reminder to still define
the correct macro value when the default OpenMP version changes in the
future.

Added: 


Modified: 
clang/lib/Frontend/InitPreprocessor.cpp

Removed: 




diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 592e7b0076f7b..847d3667ff37c 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -1249,6 +1249,7 @@ static void InitializePredefinedMacros(const TargetInfo 
&TI,
 case 52:
   Builder.defineMacro("_OPENMP", "202111");
   break;
+case 50:
 default:
   // Default version is OpenMP 5.0
   Builder.defineMacro("_OPENMP", "201811");



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


[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a subscriber: rsmith.
aaron.ballman added a comment.

Thank you for working on this!




Comment at: clang/include/clang/Basic/DiagnosticGroups.td:1023-1024
 
+// Typoed directive warnings
+def TypoedDirective : DiagGroup<"typoed-directive">;
+

We don't typically use "typo" in the user-facing part of diagnostics and this 
group doesn't seem likely to be reused, so I would remove it (another comment 
on this elsewhere).



Comment at: clang/include/clang/Basic/DiagnosticLexKinds.td:362-365
 
+def warn_pp_typo_directive : Warning<
+  "'#%0' directive not found, did you mean '#%1'?">,
+  InGroup;

Rather than adding a warning over the top of an existing error, I think we 
should modify `err_pp_invalid_directive` to have an optional "did you mean?" 
when we find a plausible typo to correct.

However, we do not issue that diagnostic when it's inside of a skipped 
conditional block, and that's what the crux of 
https://github.com/llvm/llvm-project/issues/51598 is about. As @rsmith pointed 
out in that issue (and I agree), compilers are free to support custom 
directives and those will validly appear inside of a conditional block that is 
skipped. We need to be careful not to diagnose those kinds of situations as an 
error. However, we still want to diagnose when the unknown directive is 
"sufficiently close" to another one which can control the conditional chain. 
e.g.,
```
#fi FOO // error unknown directive, did you mean #if?
#endfi // error unknown directive, did you mean #endif?

#if FOO
#esle // diag: unknown directive, did you mean #else?
#elfi // diag: unknown directive, did you mean #elif?
#elfidef // diag: unknown directive, did you mean #elifdef
#elinfdef // diag: unknown directive, did you mean #elifndef

#frobble // No diagnostic, not close enough to a conditional directive to 
warrant diagnosing
#eerp // No diagnostic, not close enough to a conditional directive to warrant 
diagnosing

#endif
```
Today, if `FOO` is defined to a nonzero value, you'll get diagnostics for all 
of those, but if `FOO` is not defined or is defined to 0, then there's no 
diagnostics. I think we want to consider directives that are *very likely* to 
be a typo (edit distance of 1, maybe 2?) for a conditional directive as a 
special case.

Currently, we only diagnose unknown directives as an error. I think for these 
special cased conditional directive diagnostics, we'll want to use a warning 
rather than an error in this circumstance (just in case it turns out to be a 
valid directive in a skipped conditional block). If we do go that route and 
make it a warning, I think the warning group should be `-Wunknown-directives` 
to mirror `-Wunknown-pragmas`, `-Wunknown-attributes`, etc and it should be 
defined to have the same text as the error case. e.g., 
```
def err_pp_invalid_directive : Error<
  "invalid preprocessing directive%select{|; did you mean '#%1'?}0"
>;
def warn_pp_invalid_directive : Warning<
  err_pp_invalid_directive.Text>, InGroup>;
```
WDYT?

(These were my thoughts before seeing the rest of the patch. After reading the 
patch, it looks like we have pretty similar ideas here, which is great, but 
leaving the comment anyway in case you have further opinions.)



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

You shouldn't need this file or the implementation file -- we have this 
functionality already in: 
https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/ADT/edit_distance.h
 and 
https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/ADT/StringRef.h#L240.



Comment at: clang/lib/Lex/PPDirectives.cpp:441-449
+  const SourceLocation &endLoc) {
+  const std::array candidates{
+  "if", "ifdef", "ifndef", "elif", "elifdef", "elifndef", "else", "endif"};
+
+  if (const auto sugg =
+  tooling::levdistance::findSimilarStr(candidates, Directive)) {
+CharSourceRange DirectiveRange =

Mostly just cleaning up for coding conventions, but also, no need to use a 
`std::array` and we typically don't use local top-level `const` qualification.



Comment at: clang/test/OpenMP/predefined_macro.c:7
 // RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=50 -verify -o - %s
-// expected-no-diagnostics
+// expected-warning@+5 {{'#elsif' directive not found, did you mean '#elif'?}}
 #ifdef FOPENMP

ken-matsui wrote:
> I am not sure if this typo was intended.
> 
> When I renamed `elsif` to `elif`, `#error "_OPENMP has incorrect value"` on 
> line `13` was evaluated.
> 
> Therefore, if this typo was intended, just suppressing the warning with 
> `expected-warning` would be better. However, if this typo was NOT intended, I 
> think I should make `_OPENMP` equal to `201107`. It is also poss

[PATCH] D124701: [clang] Honor __attribute__((no_builtin("foo"))) on functions

2022-05-03 Thread Stephen Long via Phabricator via cfe-commits
steplong updated this revision to Diff 426700.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124701

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/test/CodeGen/no-builtin-2.c


Index: clang/test/CodeGen/no-builtin-2.c
===
--- /dev/null
+++ clang/test/CodeGen/no-builtin-2.c
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s
+
+typedef typeof(sizeof(0)) size_t;
+
+void bar(char *s);
+void *memset(void *s, int c, size_t n);
+void *memcpy(void *d, const void *s, size_t n);
+
+// CHECK: define{{.*}} void @foo1({{.*}}) #[[NO_NOBUILTIN:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   call void @llvm.memcpy
+void foo1(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 0, n);
+memcpy(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo2({{.*}}) #[[NOBUILTIN_MEMSET:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   call void @llvm.memcpy
+void foo2(char *s, char *d, size_t n) __attribute__((no_builtin("memset")))
+{
+bar(s);
+memset(s, 1, n);
+memcpy(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo3({{.*}}) #[[NOBUILTIN_MEMSET_MEMCPY:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   {{.*}}call i8* @memcpy
+void foo3(char *s, char *d, size_t n) __attribute__((no_builtin("memset", 
"memcpy")))
+{
+bar(s);
+memset(s, 2, n);
+memcpy(d, s, n);
+}
+
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = 
{{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET]] = 
{{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET_MEMCPY]] = 
{{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -5034,6 +5034,7 @@
   const FunctionDecl *FD = cast(GD.getDecl());
 
   if (auto builtinID = FD->getBuiltinID()) {
+std::string AttributeNoBuiltin = "no-builtin-" + FD->getName().str();
 std::string FDInlineName = (FD->getName() + ".inline").str();
 // When directing calling an inline builtin, call it through it's mangled
 // name to make it clear it's not the actual builtin.
@@ -5054,8 +5055,9 @@
 
 // Replaceable builtins provide their own implementation of a builtin. If 
we
 // are in an inline builtin implementation, avoid trivial infinite
-// recursion.
-else
+// recursion. Honor __attribute__((no_builtin("foo"))) on the current
+// function.
+else if (!CGF.CurFn->getAttributes().hasFnAttr(AttributeNoBuiltin))
   return CGCallee::forBuiltin(builtinID, FD);
   }
 


Index: clang/test/CodeGen/no-builtin-2.c
===
--- /dev/null
+++ clang/test/CodeGen/no-builtin-2.c
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s
+
+typedef typeof(sizeof(0)) size_t;
+
+void bar(char *s);
+void *memset(void *s, int c, size_t n);
+void *memcpy(void *d, const void *s, size_t n);
+
+// CHECK: define{{.*}} void @foo1({{.*}}) #[[NO_NOBUILTIN:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   call void @llvm.memcpy
+void foo1(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 0, n);
+memcpy(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo2({{.*}}) #[[NOBUILTIN_MEMSET:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   call void @llvm.memcpy
+void foo2(char *s, char *d, size_t n) __attribute__((no_builtin("memset")))
+{
+bar(s);
+memset(s, 1, n);
+memcpy(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo3({{.*}}) #[[NOBUILTIN_MEMSET_MEMCPY:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   {{.*}}call i8* @memcpy
+void foo3(char *s, char *d, size_t n) __attribute__((no_builtin("memset", "memcpy")))
+{
+bar(s);
+memset(s, 2, n);
+memcpy(d, s, n);
+}
+
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -5034,6 +5034,7 @@
   const FunctionDecl *FD = cast(GD.getDecl());
 
   if (auto builtinID = FD->getBuiltinID()) {
+std::string AttributeNoBuiltin = "no-builtin-" + FD->getName().str

[PATCH] D121370: [clang-format] SortIncludes should support "@import" lines in Objective-C

2022-05-03 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk updated this revision to Diff 426701.
kwk added a comment.

Address trailing comments on include lines by ignoring slashes in
characters that lead up to the match groups.

  ^[\t\ ]*[@#][\t\ ]*(import|include)([^"/]*("[^"]+")|[^]+>)|[\t/\ 
]*([^;]+;))
  ~~~ ~~~ 

  ^ ^   ^   ^   ^
  | |   |   |   |
  Now support @ and #.Clearly support "" and <> as ell as an
  include name without enclosing 
characters.
  Allows for no mixture of "> or <" or
  empty include names. Trailing
  comments on include lines as shown in
  D124513 are ignored now by
  ignoring slashes in the characters 
that
  lead up to a match group.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121370

Files:
  clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
  clang/lib/Format/Format.cpp
  clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
  clang/unittests/Format/SortIncludesTest.cpp

Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -472,6 +472,103 @@
  /*ExpectedNumRanges=*/0));
 }
 
+TEST_F(SortIncludesTest, SupportAtImportLines) {
+  // Test from https://github.com/llvm/llvm-project/issues/38995
+  EXPECT_EQ("#import \"a.h\"\n"
+"#import \"b.h\"\n"
+"#import \"c.h\"\n"
+"#import \n"
+"@import Foundation;\n",
+sort("#import \"b.h\"\n"
+ "#import \"c.h\"\n"
+ "#import \n"
+ "@import Foundation;\n"
+ "#import \"a.h\"\n"));
+
+  // Slightly more complicated test that shows sorting in each priorities still
+  // works.
+  EXPECT_EQ("#import \"a.h\"\n"
+"#import \"b.h\"\n"
+"#import \"c.h\"\n"
+"#import \n"
+"@import Base;\n"
+"@import Foundation;\n"
+"@import base;\n"
+"@import foundation;\n",
+sort("#import \"b.h\"\n"
+ "#import \"c.h\"\n"
+ "@import Base;\n"
+ "#import \n"
+ "@import foundation;\n"
+ "@import Foundation;\n"
+ "@import base;\n"
+ "#import \"a.h\"\n"));
+
+  // Test that shows main headers in two groups are still found and sorting
+  // still works. The @import's are kept in their respective group but are
+  // put at the end of each group.
+  FmtStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
+  EXPECT_EQ("#import \"foo.hpp\"\n"
+"#import \"b.h\"\n"
+"#import \"c.h\"\n"
+"#import \n"
+"@import Base;\n"
+"@import Foundation;\n"
+"@import foundation;\n"
+"\n"
+"#import \"foo.h\"\n"
+"#include \"foobar\"\n"
+"#import \n"
+"@import ;\n"
+"@import ;\n",
+sort("#import \"b.h\"\n"
+ "@import Foundation;\n"
+ "@import foundation;\n"
+ "#import \"c.h\"\n"
+ "#import \n"
+ "@import Base;\n"
+ "#import \"foo.hpp\"\n"
+ "\n"
+ "@import ;\n"
+ "#import \n"
+ "@import ;\n"
+ "#include \"foobar\"\n"
+ "#import \"foo.h\"\n",
+ "foo.c", 2));
+
+  // Regrouping and putting @import's in the very last group
+  FmtStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
+  EXPECT_EQ("#import \"foo.hpp\"\n"
+"\n"
+"#import \"b.h\"\n"
+"#import \"c.h\"\n"
+"#import \"foo.h\"\n"
+"#include \"foobar\"\n"
+"\n"
+"#import \n"
+"#import \n"
+"\n"
+"@import ;\n"
+"@import Base;\n"
+"@import Foundation;\n"
+"@import ;\n"
+"@import foundation;\n",
+sort("#import \"b.h\"\n"
+ "@import Foundation;\n"
+ "@import foundation;\n"
+ "#import \"c.h\"\n"
+ "#import \n"
+ "@import Base;\n"
+ "#import \"foo.hpp\"\n"
+ "\n"
+ "@import ;\n"
+ "#import 

[PATCH] D124702: [MSVC] Add support for pragma function

2022-05-03 Thread Stephen Long via Phabricator via cfe-commits
steplong updated this revision to Diff 426702.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124702

Files:
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CodeGen/pragma-ms-function-intrinsic.c

Index: clang/test/CodeGen/pragma-ms-function-intrinsic.c
===
--- /dev/null
+++ clang/test/CodeGen/pragma-ms-function-intrinsic.c
@@ -0,0 +1,78 @@
+// RUN: %clang_cc1 -emit-llvm -fms-extensions -o - %s | FileCheck %s
+
+typedef typeof(sizeof(0)) size_t;
+
+void bar(char *s);
+void *memset(void *s, int c, size_t n);
+void *memcpy(void *d, const void *s, size_t n);
+
+// CHECK: define{{.*}} void @foo1({{.*}}) #[[NO_NOBUILTIN:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   call void @llvm.memcpy
+void foo1(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 0, n);
+memcpy(d, s, n);
+}
+
+#pragma function(strlen, memset)
+
+// CHECK: define{{.*}} void @foo2({{.*}}) #[[NOBUILTIN_MEMSET:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   call void @llvm.memcpy
+void foo2(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 1, n);
+memcpy(d, s, n);
+}
+
+#pragma function(memcpy)
+
+// CHECK: define{{.*}} void @foo3({{.*}}) #[[NOBUILTIN_MEMSET_MEMCPY:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   {{.*}}call i8* @memcpy
+void foo3(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 2, n);
+memcpy(d, s, n);
+}
+
+#pragma intrinsic(memset, strlen)
+
+// CHECK: define{{.*}} void @foo4({{.*}}) #[[NOBUILTIN_MEMCPY:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   {{.*}}call i8* @memcpy
+void foo4(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 3, n);
+memcpy(d, s, n);
+}
+
+#pragma intrinsic(memcpy)
+
+// CHECK: define{{.*}} void @foo5({{.*}}) #[[NO_NOBUILTIN]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   call void @llvm.memcpy
+void foo5(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 4, n);
+memcpy(d, s, n);
+}
+
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NOBUILTIN_MEMSET]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}}
+// CHECK-NOT: attributes #[[NOBUILTIN_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -10218,10 +10218,12 @@
   // marking the function.
   AddCFAuditedAttribute(NewFD);
 
-  // If this is a function definition, check if we have to apply optnone due to
-  // a pragma.
-  if(D.isFunctionDefinition())
+  // If this is a function definition, check if we have to apply any
+  // attributes (i.e. optnone and no_builtin) due to a pragma.
+  if(D.isFunctionDefinition()) {
 AddRangeBasedOptnone(NewFD);
+AddRangeBasedNoBuiltin(NewFD);
+  }
 
   // If this is the first declaration of an extern C variable, update
   // the map of such variables.
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -1065,6 +1065,19 @@
 OptimizeOffPragmaLocation = PragmaLoc;
 }
 
+void Sema::ActOnPragmaMSIntrinsic(const std::vector &Intrinsics) {
+  for (auto &Intrinsic : Intrinsics) {
+MSFunctionNoBuiltins.erase(std::remove(MSFunctionNoBuiltins.begin(),
+   MSFunctionNoBuiltins.end(),
+   Intrinsic));
+  }
+}
+
+void Sema::ActOnPragmaMSFunction(const std::vector &NoBuiltins) {
+  MSFunctionNoBuiltins.insert(MSFunctionNoBuiltins.end(),
+  NoBuiltins.begin(), NoBuiltins.end());
+}
+
 void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
   // In the future, check other pragmas if they're implemented (e.g. pragma
   // optimize 0 will probably map to this functionality too).
@@ -1086,6 +1099,13 @@
 FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
 }
 
+void Sema::AddRangeBasedNoBuiltin(FunctionDecl *FD) {
+  if (!MSFunctionNoBuiltins.empty()) {
+FD->addAttr(NoBuiltinAttr::CreateImplicit(Context,
+MSFunctionNoBuil

[PATCH] D121370: [clang-format] SortIncludes should support "@import" lines in Objective-C

2022-05-03 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk added a comment.

@krasimir could you please test this patch on your side? I've reopened it and 
tested it with the following file that contains both `//` and `/* ... */` 
trailing comments on include lines followed by `foo` and alike. The includes 
use `<...>` and `"..."` notation to locate files.

*test.h*

  #include 
  
  #include "util/bar.h"
  #include "util/foo/foo.h"  // foo
  #include "util/bar/bar.h"  // bar
  #include "utilzbar0.h"  // bar0
  #include   // foo3
  #include   // bar3
  #include   // foo2
  #include   // bar2
  #include "util/bar.h"
  #include "util/foo/foo.h"  /* foo */
  #include "util/bar/bar.h"  /* bar */
  #include "utilzbar0.h"  /* bar0 */
  #include   /* foo3 */
  #include   /* bar3 */
  #include   /* foo2 */
  #include   /* bar2 */

Run test with `ninja clang-format && bin/clang-format -style=google test.h`:

  #include   // bar2
  #include   /* bar2 */
  #include   // bar3
  #include   /* bar3 */
  #include   // foo2
  #include   /* foo2 */
  #include   // foo3
  #include   /* foo3 */
  
  #include 
  
  #include "util/bar.h"
  #include "util/bar/bar.h"  // bar
  #include "util/bar/bar.h"  /* bar */
  #include "util/foo/foo.h"  // foo
  #include "util/foo/foo.h"  /* foo */
  #include "utilzbar0.h" // bar0
  #include "utilzbar0.h" /* bar0 */

To me, this looks precisely how it should look like. What do you think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121370

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


[PATCH] D124715: Use QoS class Utility for ThreadPriority::Low on Mac

2022-05-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

> With this priority, the thread is
> confined to efficiency cores only, which makes background indexing take 
> forever

(How) does this interact with battery vs mains power on laptops?
It seems like there's a common scenario where:

- the user is on a relatively slow laptop, running off battery
- the codebase is large, and indexing is unlikely to finish within an editing 
session

In this case, it seems like only using efficiency cores is what you'd want, and 
that people are likely to be upset if clangd 15 keeps their performance cores 
running at all times.

Reading the docs 

 it seems like background is the intended QoS for this type of work ("such as 
indexing"..."minutes or hours").

(Sorry to bring this up at code review time, I wasn't thinking about laptops 
when we discussed on the bug)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

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


[clang] 64816e6 - [AArch64] Support for Ampere1 core

2022-05-03 Thread David Green via cfe-commits

Author: Philipp Tomsich
Date: 2022-05-03T15:54:02+01:00
New Revision: 64816e68f4419a9e14c23be8aa96fa412bed7e12

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

LOG: [AArch64] Support for Ampere1 core

Add support for the Ampere Computing Ampere1 core.
Ampere1 implements the AArch64 state and is compatible with ARMv8.6-A.

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

Added: 
llvm/lib/Target/AArch64/AArch64SchedAmpere1.td
llvm/lib/Target/AArch64/AArch64SchedPredAmpere.td

Modified: 
clang/test/Misc/target-invalid-cpu-note.c
llvm/include/llvm/Support/AArch64TargetParser.def
llvm/lib/Target/AArch64/AArch64.td
llvm/lib/Target/AArch64/AArch64SchedPredicates.td
llvm/lib/Target/AArch64/AArch64Subtarget.cpp
llvm/lib/Target/AArch64/AArch64Subtarget.h
llvm/test/CodeGen/AArch64/cpus.ll
llvm/test/CodeGen/AArch64/neon-dot-product.ll
llvm/test/CodeGen/AArch64/remat.ll
llvm/test/MC/AArch64/armv8.2a-dotprod.s
llvm/test/MC/AArch64/armv8.3a-rcpc.s
llvm/test/MC/Disassembler/AArch64/armv8.3a-rcpc.txt
llvm/unittests/Support/TargetParserTest.cpp

Removed: 




diff  --git a/clang/test/Misc/target-invalid-cpu-note.c 
b/clang/test/Misc/target-invalid-cpu-note.c
index b240eb1428f78..7c7e7e326cf15 100644
--- a/clang/test/Misc/target-invalid-cpu-note.c
+++ b/clang/test/Misc/target-invalid-cpu-note.c
@@ -5,11 +5,11 @@
 
 // RUN: not %clang_cc1 -triple arm64--- -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix AARCH64
 // AARCH64: error: unknown target CPU 'not-a-cpu'
-// AARCH64-NEXT: note: valid target CPU values are: cortex-a34, cortex-a35, 
cortex-a53, cortex-a55, cortex-a510, cortex-a57, cortex-a65, cortex-a65ae, 
cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, 
cortex-a78, cortex-a78c, cortex-a710, cortex-r82, cortex-x1, cortex-x1c, 
cortex-x2, neoverse-e1, neoverse-n1, neoverse-n2, neoverse-512tvb, neoverse-v1, 
cyclone, apple-a7, apple-a8, apple-a9, apple-a10, apple-a11, apple-a12, 
apple-a13, apple-a14, apple-m1, apple-s4, apple-s5, exynos-m3, exynos-m4, 
exynos-m5, falkor, saphira, kryo, thunderx2t99, thunderx3t110, thunderx, 
thunderxt88, thunderxt81, thunderxt83, tsv110, a64fx, carmel{{$}}
+// AARCH64-NEXT: note: valid target CPU values are: cortex-a34, cortex-a35, 
cortex-a53, cortex-a55, cortex-a510, cortex-a57, cortex-a65, cortex-a65ae, 
cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, 
cortex-a78, cortex-a78c, cortex-a710, cortex-r82, cortex-x1, cortex-x1c, 
cortex-x2, neoverse-e1, neoverse-n1, neoverse-n2, neoverse-512tvb, neoverse-v1, 
cyclone, apple-a7, apple-a8, apple-a9, apple-a10, apple-a11, apple-a12, 
apple-a13, apple-a14, apple-m1, apple-s4, apple-s5, exynos-m3, exynos-m4, 
exynos-m5, falkor, saphira, kryo, thunderx2t99, thunderx3t110, thunderx, 
thunderxt88, thunderxt81, thunderxt83, tsv110, a64fx, carmel, ampere1{{$}}
 
 // RUN: not %clang_cc1 -triple arm64--- -tune-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix TUNE_AARCH64
 // TUNE_AARCH64: error: unknown target CPU 'not-a-cpu'
-// TUNE_AARCH64-NEXT: note: valid target CPU values are: cortex-a34, 
cortex-a35, cortex-a53, cortex-a55, cortex-a510, cortex-a57, cortex-a65, 
cortex-a65ae, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, 
cortex-a77, cortex-a78, cortex-a78c, cortex-a710, cortex-r82, cortex-x1, 
cortex-x1c, cortex-x2, neoverse-e1, neoverse-n1, neoverse-n2, neoverse-512tvb, 
neoverse-v1, cyclone, apple-a7, apple-a8, apple-a9, apple-a10, apple-a11, 
apple-a12, apple-a13, apple-a14, apple-m1, apple-s4, apple-s5, exynos-m3, 
exynos-m4, exynos-m5, falkor, saphira, kryo, thunderx2t99, thunderx3t110, 
thunderx, thunderxt88, thunderxt81, thunderxt83, tsv110, a64fx, carmel{{$}}
+// TUNE_AARCH64-NEXT: note: valid target CPU values are: cortex-a34, 
cortex-a35, cortex-a53, cortex-a55, cortex-a510, cortex-a57, cortex-a65, 
cortex-a65ae, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, 
cortex-a77, cortex-a78, cortex-a78c, cortex-a710, cortex-r82, cortex-x1, 
cortex-x1c, cortex-x2, neoverse-e1, neoverse-n1, neoverse-n2, neoverse-512tvb, 
neoverse-v1, cyclone, apple-a7, apple-a8, apple-a9, apple-a10, apple-a11, 
apple-a12, apple-a13, apple-a14, apple-m1, apple-s4, apple-s5, exynos-m3, 
exynos-m4, exynos-m5, falkor, saphira, kryo, thunderx2t99, thunderx3t110, 
thunderx, thunderxt88, thunderxt81, thunderxt83, tsv110, a64fx, carmel, 
ampere1{{$}}
 
 // RUN: not %clang_cc1 -triple i386--- -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix X86
 // X86: error: unknown target CPU 'not-a-cpu'

diff  --git a/llvm/include/llvm/Support/AArch64TargetParser.def 
b/llvm/include/llvm/Support/AArch64TargetParser.def
index 44b73fa2f0b64..bae6

[PATCH] D117112: [AArch64] Support for Ampere1 core

2022-05-03 Thread Dave Green 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 rG64816e68f441: [AArch64] Support for Ampere1 core (authored 
by philipp.tomsich, committed by dmgreen).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117112

Files:
  clang/test/Misc/target-invalid-cpu-note.c
  llvm/include/llvm/Support/AArch64TargetParser.def
  llvm/lib/Target/AArch64/AArch64.td
  llvm/lib/Target/AArch64/AArch64SchedAmpere1.td
  llvm/lib/Target/AArch64/AArch64SchedPredAmpere.td
  llvm/lib/Target/AArch64/AArch64SchedPredicates.td
  llvm/lib/Target/AArch64/AArch64Subtarget.cpp
  llvm/lib/Target/AArch64/AArch64Subtarget.h
  llvm/test/CodeGen/AArch64/cpus.ll
  llvm/test/CodeGen/AArch64/neon-dot-product.ll
  llvm/test/CodeGen/AArch64/remat.ll
  llvm/test/MC/AArch64/armv8.2a-dotprod.s
  llvm/test/MC/AArch64/armv8.3a-rcpc.s
  llvm/test/MC/Disassembler/AArch64/armv8.3a-rcpc.txt
  llvm/unittests/Support/TargetParserTest.cpp

Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -1195,6 +1195,14 @@
  AArch64::AEK_SVE2 | AArch64::AEK_SVE2BITPERM |
  AArch64::AEK_BF16 | AArch64::AEK_I8MM,
  "8.5-A"),
+ARMCPUTestParams("ampere1", "armv8.6-a", "crypto-neon-fp-armv8",
+ AArch64::AEK_CRC  | AArch64::AEK_FP   | AArch64::AEK_FP16   |
+ AArch64::AEK_SIMD | AArch64::AEK_RAS  | AArch64::AEK_LSE |
+ AArch64::AEK_RDM  | AArch64::AEK_RCPC | AArch64::AEK_DOTPROD |
+ AArch64::AEK_SM4  | AArch64::AEK_SHA3 | AArch64::AEK_BF16|
+ AArch64::AEK_SHA2 | AArch64::AEK_AES  | AArch64::AEK_I8MM|
+ AArch64::AEK_MTE  | AArch64::AEK_SSBS | AArch64::AEK_SB,
+ "8.6-A"),
 ARMCPUTestParams(
 "neoverse-512tvb", "armv8.4-a", "crypto-neon-fp-armv8",
 AArch64::AEK_RAS | AArch64::AEK_SVE | AArch64::AEK_SSBS |
@@ -1256,7 +1264,7 @@
  AArch64::AEK_LSE | AArch64::AEK_RDM,
  "8.2-A")));
 
-static constexpr unsigned NumAArch64CPUArchs = 53;
+static constexpr unsigned NumAArch64CPUArchs = 54;
 
 TEST(TargetParserTest, testAArch64CPUArchList) {
   SmallVector List;
Index: llvm/test/MC/Disassembler/AArch64/armv8.3a-rcpc.txt
===
--- llvm/test/MC/Disassembler/AArch64/armv8.3a-rcpc.txt
+++ llvm/test/MC/Disassembler/AArch64/armv8.3a-rcpc.txt
@@ -12,6 +12,7 @@
 # RUN: llvm-mc -triple aarch64-none-linux-gnu -mcpu=neoverse-e1 --disassemble < %s | FileCheck %s
 # RUN: llvm-mc -triple aarch64-none-linux-gnu -mcpu=neoverse-n1 --disassemble < %s | FileCheck %s
 # RUN: llvm-mc -triple aarch64-none-linux-gnu -mcpu=neoverse-n2 --disassemble < %s | FileCheck %s
+# RUN: llvm-mc -triple aarch64-none-linux-gnu -mcpu=ampere1 --disassemble < %s | FileCheck %s
 
 # CHECK: ldaprb w0, [x0]
 # CHECK: ldaprh w0, [x0]
Index: llvm/test/MC/AArch64/armv8.3a-rcpc.s
===
--- llvm/test/MC/AArch64/armv8.3a-rcpc.s
+++ llvm/test/MC/AArch64/armv8.3a-rcpc.s
@@ -6,6 +6,7 @@
 // RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mcpu=neoverse-e1 < %s 2>&1 | FileCheck %s
 // RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mcpu=neoverse-n1 < %s 2>&1 | FileCheck %s
 // RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mcpu=neoverse-n2 < %s 2>&1 | FileCheck %s
+// RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mcpu=ampere1 < %s 2>&1 | FileCheck %s
 // RUN: llvm-mc -triple aarch64-none-linux-gnu -show-encoding -mattr=+v8.2a -mattr=+rcpc < %s 2>&1 | FileCheck %s
 // RUN: not llvm-mc -triple aarch64-none-linux-gnu -mattr=+v8.2a < %s 2> %t
 // RUN: FileCheck --check-prefix=CHECK-REQ %s < %t
Index: llvm/test/MC/AArch64/armv8.2a-dotprod.s
===
--- llvm/test/MC/AArch64/armv8.2a-dotprod.s
+++ llvm/test/MC/AArch64/armv8.2a-dotprod.s
@@ -13,6 +13,7 @@
 // RUN: llvm-mc -triple aarch64 -mcpu=tsv110 -show-encoding < %s | FileCheck %s --check-prefix=CHECK-DOTPROD
 // RUN: llvm-mc -triple aarch64 -mcpu=cortex-r82 -show-encoding < %s | FileCheck %s --check-prefix=CHECK-DOTPROD
 // RUN: llvm-mc -triple aarch64 -mattr=+v8r -show-encoding < %s | FileCheck %s --check-prefix=CHECK-DOTPROD
+// RUN: llvm-mc -triple aarch64 -mcpu=ampere1 -show-encoding < %s | FileCheck %s --check-prefix=CHECK-DOTPROD
 
 // RUN: not llvm-mc -triple aarch64 -mattr=+v8.2a -show-encoding < %s 2> %t
 // RUN: FileCheck --check-prefix=CHECK-NO-DOTP

[PATCH] D124807: [clang][dataflow] Avoid assert for invalid cast to BoolValue

2022-05-03 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua updated this revision to Diff 426711.
li.zhe.hua added a comment.

Update test to treat the PointerToBool conversion as an opaque boolean 
expression, and test it as such.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124807

Files:
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -1152,4 +1152,39 @@
   });
 }
 
+// FIXME: Remove this test once it provides no additional test coverage.
+TEST_F(FlowConditionTest, DoesNotAssertForImplicitCastToBool) {
+  std::string Code = R"(
+void target(int *Ptr) {
+  bool Foo = false;
+  if (Ptr) {
+Foo = true;
+/*[[p1]]*/
+  }
+
+  (void)0;
+  /*[[p2]]*/
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p2", _), Pair("p1", _)));
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const Environment &Env1 = Results[1].second.Env;
+auto &FooVal1 =
+*cast(Env1.getValue(*FooDecl, SkipPast::Reference));
+EXPECT_TRUE(Env1.flowConditionImplies(FooVal1));
+
+const Environment &Env2 = Results[0].second.Env;
+auto &FooVal2 =
+*cast(Env2.getValue(*FooDecl, SkipPast::Reference));
+EXPECT_FALSE(Env2.flowConditionImplies(FooVal2));
+  });
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -17,6 +17,7 @@
 #include 
 
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/IgnoreExpr.h"
 #include "clang/AST/OperationKinds.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
@@ -68,6 +69,28 @@
   return BlockPos - Pred.succ_begin();
 }
 
+/// Skips past any parentheses and implicit casts for `E`, except if they would
+/// perform a type conversion to bool.
+///
+/// FIXME: Its hard to tell if this is a principled solution or workaround to an
+/// issue. Re-evaluate the necessity for this function after we model pointers
+/// and integers in the framework.
+static const Expr *ignoreParenImpCastsExceptToBool(const Expr *E) {
+  const Expr *LastE = nullptr;
+  while (E != LastE) {
+LastE = E;
+E = IgnoreParensSingleStep(const_cast(E));
+
+bool WasBool = E->getType()->isBooleanType();
+auto *Unwrapped = IgnoreImplicitCastsExtraSingleStep(const_cast(E));
+if (WasBool && !Unwrapped->getType()->isBooleanType())
+  return E;
+
+E = Unwrapped;
+  }
+  return E;
+}
+
 /// Extends the flow condition of an environment based on a terminator
 /// statement.
 class TerminatorVisitor : public ConstStmtVisitor {
@@ -77,26 +100,26 @@
   : StmtToEnv(StmtToEnv), Env(Env), BlockSuccIdx(BlockSuccIdx) {}
 
   void VisitIfStmt(const IfStmt *S) {
-auto *Cond = S->getCond()->IgnoreParenImpCasts();
+auto *Cond = ignoreParenImpCastsExceptToBool(S->getCond());
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
 
   void VisitWhileStmt(const WhileStmt *S) {
-auto *Cond = S->getCond()->IgnoreParenImpCasts();
+auto *Cond = ignoreParenImpCastsExceptToBool(S->getCond());
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
 
   void VisitBinaryOperator(const BinaryOperator *S) {
 assert(S->getOpcode() == BO_LAnd || S->getOpcode() == BO_LOr);
-auto *LHS = S->getLHS()->IgnoreParenImpCasts();
+auto *LHS = ignoreParenImpCastsExceptToBool(S->getLHS());
 assert(LHS != nullptr);
 extendFlowCondition(*LHS);
   }
 
   void VisitConditionalOperator(const ConditionalOperator *S) {
-auto *Cond = S->getCond()->IgnoreParenImpCasts();
+auto *Cond = ignoreParenImpCastsExceptToBool(S->getCond());
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-03 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 426715.
martong added a comment.

- Add a simpler test case


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/ProgramState.cpp
  clang/test/Analysis/infeasible-sink.c

Index: clang/test/Analysis/infeasible-sink.c
===
--- /dev/null
+++ clang/test/Analysis/infeasible-sink.c
@@ -0,0 +1,80 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test that if it turns out that the parent state is infeasible then
+// both children States (more precisely the ExplodedNodes) are marked as a
+// Sink.
+// We rely on existing defects of the underlying constraint solver. However,
+// in the future we might strengthen the solver to discover the infeasibility
+// right when we create the parent state. At that point some of these tests
+// will fail, and either we shall find another solver weakness to have the test
+// case functioning, or we shall simply remove that.
+
+void clang_analyzer_warnIfReached();
+void clang_analyzer_eval(int);
+
+void test1(int x) {
+  if (x * x != 4)
+return;
+  if (x < 0 || x > 1)
+return;
+
+  // { x^2 == 4 and x:[0,1] }
+  // This state is already infeasible.
+
+  // Perfectly constraining 'x' will trigger constant folding,
+  // when we realize we were already infeasible.
+  // The same happens for the 'else' branch.
+  if (x == 0) {
+clang_analyzer_warnIfReached(); // no-warning
+  } else {
+clang_analyzer_warnIfReached(); // no-warning
+  }
+  clang_analyzer_warnIfReached(); // no-warning
+  (void)x;
+}
+
+int a, b, c, d, e;
+void test2() {
+
+  if (a == 0)
+return;
+
+  if (e != c)
+return;
+
+  d = e - c;
+  b = d;
+  a -= d;
+
+  if (a != 0)
+return;
+
+  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+
+  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
+  // The parent state is already infeasible, look at this contradiction:
+  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
+  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
+  // Crashes with expensive checks.
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning, OK
+return;
+  }
+  // Should not be reachable.
+  clang_analyzer_warnIfReached(); // expected-wrning{{REACHABLE}}
+  */
+
+  // The parent state is already infeasible, but we realize that only if b is
+  // constrained.
+  clang_analyzer_eval(b > 0);  // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(b <= 0); // expected-warning{{UNKNOWN}}
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning
+return;
+  }
+  clang_analyzer_warnIfReached(); // no-warning
+}
Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -55,7 +55,7 @@
 
 ProgramState::ProgramState(const ProgramState &RHS)
 : stateMgr(RHS.stateMgr), Env(RHS.Env), store(RHS.store), GDM(RHS.GDM),
-  refCount(0) {
+  Infeasible(RHS.Infeasible), refCount(0) {
   stateMgr->getStoreManager().incrementReferenceCount(store);
 }
 
@@ -429,6 +429,12 @@
   return getStateManager().getPersistentState(NewSt);
 }
 
+ProgramStateRef ProgramState::cloneAsInfeasible() const {
+  ProgramState NewSt(*this);
+  NewSt.Infeasible = true;
+  return getStateManager().getPersistentState(NewSt);
+}
+
 void ProgramState::setStore(const StoreRef &newStore) {
   Store newStoreStore = newStore.getStore();
   if (newStoreStore)
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -41,3 +41,32 @@
 return ConditionTruthVal(true);
   return {};
 }
+
+ConstraintManager::ProgramStatePair
+ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
+  ProgramStateRef StTrue = assume(State, Cond, true);
+
+  if (!StTrue) {
+ProgramStateRef StFalse = assume(State, Cond, false);
+if (!StFalse) { // both infeasible
+  ProgramStateRef StInfeasible = State->cloneAsInfeasible();
+  assert(StInfeasible->isInfeasible());
+  // Checkers might rely on the API contract that both returned states
+  // cannot be null. Thus, we return StInfeasible for both branches because
+  // it mi

[PATCH] D122663: Mark identifier prefixes as substitutable

2022-05-03 Thread Nathan Sidwell via Phabricator via cfe-commits
urnathan added inline comments.



Comment at: clang/lib/AST/ItaniumMangle.cpp:6031
+bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {
+  NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
+  return mangleSubstitution(reinterpret_cast(NNS));

hvdijk wrote:
> urnathan wrote:
> > hvdijk wrote:
> > > rsmith wrote:
> > > > This seems a little error-prone to me: calling this on a type NNS would 
> > > > do the wrong thing (those are supposed to share a substitution number 
> > > > with the type, rather than have a substitution of their own).
> > > > 
> > > > We could handle the various cases here and dispatch to the right forms 
> > > > of `mangleSubstitution` depending on the kind of NNS, but that code 
> > > > would all be unreachable / untested. So maybe we should just make this 
> > > > assert that `NNS->getKind() == NestedNameSpecifier::Identifier`. (And 
> > > > optionally we could give this a more specific name, eg 
> > > > `mangleSubstitutionForIdentifierNNS`?)
> > > I have added the assert that you suggested. I would actually have 
> > > preferred for this function to be used for other NNS substitutions as 
> > > well to better align with how the spec says substitutions should be 
> > > handled (it's a rule of ``, not any component within) but that 
> > > seemed like an unnecessarily more invasive change. If you are okay with 
> > > it I would like to keep the function named just `mangleSubstitution` to 
> > > keep that open as option for a possible future clean-up.
> > One could name it `mangleSubstitutionForIdentifierNNS` now and rename it in 
> > the future, if your unification dream comes true?  That names it for what 
> > it does now.
> > 
> > Just a thought, not a requirement.
> Sorry, that comment came after I pushed it already. I have some more things 
> to look into when I have some more time (including @erichkeane's comment 
> about the test), will see if it makes sense to include with that, or perhaps 
> to just make that NFC change to allow it to be used more generally.
no worries, I failed to notice it'd already landed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122663

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


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-03 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp:51
+ProgramStateRef StFalse = assume(State, Cond, false);
+if (!StFalse) { // both infeasible
+  ProgramStateRef Infeasible = State->cloneAsInfeasible();

martong wrote:
> steakhal wrote:
> > Should we mark this `LLVM_UNLIKELY(cond)`?
> > I would expect this function to be quite hot, and infeasible states rare.
> > 
> > Could we measure this one?
> Yes, it could be.
> 
> Let me come back with some measurement results soon. I am going to use llvm 
> statistics macros to measure this, but that makes sense on top of D124758
This is what I use for the measurement, stay tuned for the results.
```
diff --git a/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
index ef98ed7d36e9..82097d67ec0f 100644
--- a/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -16,10 +16,16 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/Statistic.h"

 using namespace clang;
 using namespace ento;

+#define DEBUG_TYPE "CoreEngine"
+
+STATISTIC(NumInfeasible, "The # of infeasible states");
+STATISTIC(NumFeasible, "The # of feasible states");
+
 ConstraintManager::~ConstraintManager() = default;

 static DefinedSVal getLocFromSymbol(const ProgramStateRef &State,
@@ -51,16 +57,20 @@ ConstraintManager::assumeDual(ProgramStateRef State, 
DefinedSVal Cond) {
 if (!StFalse) { // both infeasible
   ProgramStateRef Infeasible = State->cloneAsInfeasible();
   assert(Infeasible->isInfeasible());
+  ++NumInfeasible;
   return ProgramStatePair(Infeasible, Infeasible);
 }
+++NumFeasible;
 return ProgramStatePair(nullptr, StFalse);
   }

   ProgramStateRef StFalse = assumeInternal(State, Cond, false);
   if (!StFalse) {
+++NumFeasible;
 return ProgramStatePair(StTrue, nullptr);
   }

+  ++NumFeasible;
   return ProgramStatePair(StTrue, StFalse);
 }
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D123009: [Sema] Enum conversion warning when one signed and other unsigned.

2022-05-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thanks for the updates! I think this is getting somewhat close, but I'd like to 
see some additional test cases to ensure we're not regressing behavior we care 
about (I think we may be losing warnings about sign conversion).

  // Signed enums
  enum SE1 { N1 = -1 };
  enum SE2 { N2 = -2 };
  // Unsigned unums
  enum UE1 { P1 };
  enum UE2 { P2 };
  
  int f1(enum UE1 E) {
return E; // warning about sign conversion
  }
  
  int f2(enum UE1 E) {
return E; // warning about sign conversion
  }
  
  int f3(enum SE1 E) {
return E; // shouldn't warn
  }
  
  int f4(enum SE1 E) {
return E; // shouldn't warn
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123009

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


[PATCH] D124432: Fix issues with using clangd with C++ modules

2022-05-03 Thread Kugan Vivekanandarajah via Phabricator via cfe-commits
kuganv updated this revision to Diff 426724.

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

https://reviews.llvm.org/D124432

Files:
  clang-tools-extra/clangd/test/modules-options-compatablity-test/A.h
  clang-tools-extra/clangd/test/modules-options-compatablity-test/B.h
  
clang-tools-extra/clangd/test/modules-options-compatablity-test/compile_commands.json
  
clang-tools-extra/clangd/test/modules-options-compatablity-test/definition.jsonrpc
  
clang-tools-extra/clangd/test/modules-options-compatablity-test/module.modulemap
  clang-tools-extra/clangd/test/modules-options-compatablity-test/use.c
  clang-tools-extra/clangd/test/modules-options-compatablity.test
  clang/include/clang/Basic/LangOptions.def
  clang/lib/Serialization/ASTReader.cpp

Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -3077,6 +3077,10 @@
   return Err;
 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
   return Err;
+if (PP.getPreprocessorOpts().GeneratePreamble &&
+!PP.getPreprocessorOpts().WriteCommentListToPCH) {
+  break;
+}
 CommentsCursors.push_back(std::make_pair(C, &F));
 break;
   }
Index: clang/include/clang/Basic/LangOptions.def
===
--- clang/include/clang/Basic/LangOptions.def
+++ clang/include/clang/Basic/LangOptions.def
@@ -387,7 +387,7 @@
 
 LANGOPT(XLPragmaPack, 1, 0, "IBM XL #pragma pack handling")
 
-LANGOPT(RetainCommentsFromSystemHeaders, 1, 0, "retain documentation comments from system headers in the AST")
+COMPATIBLE_LANGOPT(RetainCommentsFromSystemHeaders, 1, 0, "retain documentation comments from system headers in the AST")
 
 LANGOPT(SanitizeAddressFieldPadding, 2, 0, "controls how aggressive is ASan "
"field padding (0: none, 1:least "
Index: clang-tools-extra/clangd/test/modules-options-compatablity.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity.test
@@ -0,0 +1,10 @@
+
+# RUN: rm -rf %t && mkdir -p %t
+# RUN: cp -r %S/modules-options-compatablity-test/* %t
+# RUN: mkdir -p %t/prebuilt
+# RUN: sed -i -e "s|DIRECTORY|%t|g" %t/definition.jsonrpc
+# RUN: sed -i -e "s|DIRECTORY|%t|g" %t/compile_commands.json
+# RUN: %clang -cc1 -emit-module -o %t/prebuilt/A.pcm -fmodules %t/module.modulemap -fmodule-name=A
+# RUN: %clang -cc1 -fretain-comments-from-system-headers -emit-module -o %t/prebuilt/B.pcm -fmodules %t/module.modulemap -fmodule-name=B -fprebuilt-module-path=%t/prebuilt
+# RUN: rm %t/*.h
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc
Index: clang-tools-extra/clangd/test/modules-options-compatablity-test/use.c
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity-test/use.c
@@ -0,0 +1,5 @@
+/* use */
+#include 
+#include 
+
+void use() { a(); }
Index: clang-tools-extra/clangd/test/modules-options-compatablity-test/module.modulemap
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity-test/module.modulemap
@@ -0,0 +1,8 @@
+/* module.modulemap */
+module A {
+  header "A.h"
+}
+module B {
+  header "B.h"
+  export *
+}
Index: clang-tools-extra/clangd/test/modules-options-compatablity-test/definition.jsonrpc
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity-test/definition.jsonrpc
@@ -0,0 +1,28 @@
+{
+  "jsonrpc": "2.0",
+"id": 0,
+"method": "initialize",
+"params": {
+  "processId": 123,
+  "rootPath": "clangd",
+  "capabilities": { "window": { "workDoneProgress": true, "implicitWorkDoneProgressCreate": true} },
+  "trace": "off"
+}
+}
+---
+{
+  "jsonrpc": "2.0",
+"method": "textDocument/didOpen",
+"params": {
+  "textDocument": {
+"uri": "file://DIRECTORY/use.c",
+"languageId": "cpp",
+"version": 1,
+"text": "#include \"B.h\"\nvoid use(){\na();\n}"
+  }
+}
+}
+---
+{"jsonrpc":"2.0","id":3,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: clang-tools-extra/clangd/test/modules-options-compatablity-test/compile_commands.json
===
--- /dev/null
+++ clang-tools-extra/clangd/test/modules-options-compatablity-test/compile_commands.json
@@ -0,0 +1,8 @@
+[{
+  "directory" : ".",
+  "command" : "clang -emit-obj DIRECTORY/use.c -fno-modules-global -fmodules "
+  "-fmodules-cache-path=/DOES/NOT/EXIST  -fno-builtin-module-map "
+  "-fno-implicit-modules  -fimplicit-module-ma

[PATCH] D124724: [Clang][OpenMP] Add the support for floating-point variables for specific atomic clauses

2022-05-03 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 updated this revision to Diff 426725.
tianshilei1992 added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124724

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/atomic_capture_codegen.cpp
  clang/test/OpenMP/atomic_update_codegen.cpp
  clang/test/OpenMP/for_reduction_codegen.cpp
  clang/test/OpenMP/parallel_reduction_codegen.cpp
  clang/test/OpenMP/reduction_implicit_map.cpp
  clang/test/OpenMP/sections_reduction_codegen.cpp

Index: clang/test/OpenMP/sections_reduction_codegen.cpp
===
--- clang/test/OpenMP/sections_reduction_codegen.cpp
+++ clang/test/OpenMP/sections_reduction_codegen.cpp
@@ -268,11 +268,9 @@
 // CHECK1-NEXT:[[T_VAR15:%.*]] = alloca float, align 4
 // CHECK1-NEXT:[[DOTOMP_REDUCTION_RED_LIST:%.*]] = alloca [4 x i8*], align 8
 // CHECK1-NEXT:[[REF_TMP:%.*]] = alloca [[STRUCT_S]], align 4
+// CHECK1-NEXT:[[REF_TMP16:%.*]] = alloca [[STRUCT_S]], align 4
 // CHECK1-NEXT:[[ATOMIC_TEMP:%.*]] = alloca float, align 4
 // CHECK1-NEXT:[[TMP:%.*]] = alloca float, align 4
-// CHECK1-NEXT:[[REF_TMP17:%.*]] = alloca [[STRUCT_S]], align 4
-// CHECK1-NEXT:[[ATOMIC_TEMP27:%.*]] = alloca float, align 4
-// CHECK1-NEXT:[[_TMP28:%.*]] = alloca float, align 4
 // CHECK1-NEXT:store i32* [[DOTGLOBAL_TID_]], i32** [[DOTGLOBAL_TID__ADDR]], align 8
 // CHECK1-NEXT:store i32* [[DOTBOUND_TID_]], i32** [[DOTBOUND_TID__ADDR]], align 8
 // CHECK1-NEXT:store float* [[T_VAR]], float** [[T_VAR_ADDR]], align 8
@@ -401,77 +399,59 @@
 // CHECK1-NEXT:br label [[DOTOMP_REDUCTION_DEFAULT]]
 // CHECK1:   .omp.reduction.case2:
 // CHECK1-NEXT:[[TMP43:%.*]] = load float, float* [[T_VAR2]], align 4
-// CHECK1-NEXT:[[TMP44:%.*]] = bitcast float* [[TMP0]] to i32*
-// CHECK1-NEXT:[[ATOMIC_LOAD:%.*]] = load atomic i32, i32* [[TMP44]] monotonic, align 4
+// CHECK1-NEXT:[[TMP44:%.*]] = atomicrmw fadd float* [[TMP0]], float [[TMP43]] monotonic, align 4
+// CHECK1-NEXT:call void @__kmpc_critical(%struct.ident_t* @[[GLOB3]], i32 [[TMP7]], [8 x i32]* @.gomp_critical_user_.atomic_reduction.var)
+// CHECK1-NEXT:[[CALL15:%.*]] = call noundef nonnull align 4 dereferenceable(4) %struct.S* @_ZN1SIfEanERKS0_(%struct.S* noundef nonnull align 4 dereferenceable(4) [[TMP1]], %struct.S* noundef nonnull align 4 dereferenceable(4) [[VAR3]])
+// CHECK1-NEXT:[[TMP45:%.*]] = bitcast %struct.S* [[TMP1]] to i8*
+// CHECK1-NEXT:[[TMP46:%.*]] = bitcast %struct.S* [[CALL15]] to i8*
+// CHECK1-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP45]], i8* align 4 [[TMP46]], i64 4, i1 false)
+// CHECK1-NEXT:call void @__kmpc_end_critical(%struct.ident_t* @[[GLOB3]], i32 [[TMP7]], [8 x i32]* @.gomp_critical_user_.atomic_reduction.var)
+// CHECK1-NEXT:call void @__kmpc_critical(%struct.ident_t* @[[GLOB3]], i32 [[TMP7]], [8 x i32]* @.gomp_critical_user_.atomic_reduction.var)
+// CHECK1-NEXT:[[CALL17:%.*]] = call noundef float @_ZN1SIfEcvfEv(%struct.S* noundef nonnull align 4 dereferenceable(4) [[TMP2]])
+// CHECK1-NEXT:[[TOBOOL18:%.*]] = fcmp une float [[CALL17]], 0.00e+00
+// CHECK1-NEXT:br i1 [[TOBOOL18]], label [[LAND_RHS19:%.*]], label [[LAND_END22:%.*]]
+// CHECK1:   land.rhs19:
+// CHECK1-NEXT:[[CALL20:%.*]] = call noundef float @_ZN1SIfEcvfEv(%struct.S* noundef nonnull align 4 dereferenceable(4) [[VAR14]])
+// CHECK1-NEXT:[[TOBOOL21:%.*]] = fcmp une float [[CALL20]], 0.00e+00
+// CHECK1-NEXT:br label [[LAND_END22]]
+// CHECK1:   land.end22:
+// CHECK1-NEXT:[[TMP47:%.*]] = phi i1 [ false, [[DOTOMP_REDUCTION_CASE2]] ], [ [[TOBOOL21]], [[LAND_RHS19]] ]
+// CHECK1-NEXT:[[CONV23:%.*]] = uitofp i1 [[TMP47]] to float
+// CHECK1-NEXT:call void @_ZN1SIfEC1Ef(%struct.S* noundef nonnull align 4 dereferenceable(4) [[REF_TMP16]], float noundef [[CONV23]])
+// CHECK1-NEXT:[[TMP48:%.*]] = bitcast %struct.S* [[TMP2]] to i8*
+// CHECK1-NEXT:[[TMP49:%.*]] = bitcast %struct.S* [[REF_TMP16]] to i8*
+// CHECK1-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP48]], i8* align 4 [[TMP49]], i64 4, i1 false)
+// CHECK1-NEXT:call void @_ZN1SIfED1Ev(%struct.S* noundef nonnull align 4 dereferenceable(4) [[REF_TMP16]]) #[[ATTR4]]
+// CHECK1-NEXT:call void @__kmpc_end_critical(%struct.ident_t* @[[GLOB3]], i32 [[TMP7]], [8 x i32]* @.gomp_critical_user_.atomic_reduction.var)
+// CHECK1-NEXT:[[TMP50:%.*]] = load float, float* [[T_VAR15]], align 4
+// CHECK1-NEXT:[[TMP51:%.*]] = bitcast float* [[TMP3]] to i32*
+// CHECK1-NEXT:[[ATOMIC_LOAD:%.*]] = load atomic i32, i32* [[TMP51]] monotonic, align 4
 // CHECK1-NEXT:br label [[ATOMIC_CONT:%.*]]
 // CHECK1:   atomic_cont:
-// CHECK1-NEXT:[[TMP45:%.*]] = phi i32 [ [[ATOMIC_LOAD]], [[DOTOMP_REDUCTION_CASE2]] ], [ [[TMP53:%.*]], [[ATOMIC_CONT]] ]
-

[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-03 Thread Gabor Marton via Phabricator via cfe-commits
martong marked an inline comment as done.
martong added inline comments.



Comment at: clang/test/Analysis/sink-infeasible.c:37-48
+  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
+  // The parent state is already infeasible, look at this contradiction:
+  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
+  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
+  // Crashes with expensive checks.
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning, OK

steakhal wrote:
> martong wrote:
> > steakhal wrote:
> > > You could use a non-default check prefix.
> > No I can't, because this test code in the comment is meaningful only in the 
> > baseline, I cannot run both clang versions from lit.
> > 
> > So, actually there is no RUN line for these, it is here only to demonstrate 
> > what happens in the baseline.
> Okay, why don't we drop these if these are only applicable to the baseline?
> Should we really introduce 'stale' comments?
Ok, I can remove them if you insist, but I thought it might make it easier to 
understand what is changed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[clang] 9c1085c - [Clang][OpenMP] Add the support for floating-point variables for specific atomic clauses

2022-05-03 Thread Shilei Tian via cfe-commits

Author: Shilei Tian
Date: 2022-05-03T11:30:54-04:00
New Revision: 9c1085c7e20bdd7c4a487f50313ebeeb2b6683b8

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

LOG: [Clang][OpenMP] Add the support for floating-point variables for specific 
atomic clauses

Currently when using `atomic update` with floating-point variables, if
the operation is add or sub, `cmpxchg`, instead of `atomicrmw` is emitted, as
shown in [1].  In fact, about three years ago, llvm-svn: 351850 added the
support for FP operations. This patch adds the support in OpenMP as well.

[1] https://godbolt.org/z/M7b4ba9na

Reviewed By: jdoerfert

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

Added: 


Modified: 
clang/lib/CodeGen/CGStmtOpenMP.cpp
clang/test/OpenMP/atomic_capture_codegen.cpp
clang/test/OpenMP/atomic_update_codegen.cpp
clang/test/OpenMP/for_reduction_codegen.cpp
clang/test/OpenMP/parallel_reduction_codegen.cpp
clang/test/OpenMP/reduction_implicit_map.cpp
clang/test/OpenMP/sections_reduction_codegen.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp 
b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index fc8156a78d6a7..5e75e8884bb49 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -5838,25 +5838,38 @@ static std::pair 
emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
   // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 
'x'
   // expression is simple and atomic is allowed for the given type for the
   // target platform.
-  if (BO == BO_Comma || !Update.isScalar() ||
-  !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
+  if (BO == BO_Comma || !Update.isScalar() || !X.isSimple() ||
   (!isa(Update.getScalarVal()) &&
(Update.getScalarVal()->getType() !=
 X.getAddress(CGF).getElementType())) ||
-  !X.getAddress(CGF).getElementType()->isIntegerTy() ||
   !Context.getTargetInfo().hasBuiltinAtomic(
   Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment(
 return std::make_pair(false, RValue::get(nullptr));
 
+  auto &&CheckAtomicSupport = [&CGF](llvm::Type *T, BinaryOperatorKind BO) {
+if (T->isIntegerTy())
+  return true;
+
+if (T->isFloatingPointTy() && (BO == BO_Add || BO == BO_Sub))
+  return llvm::isPowerOf2_64(CGF.CGM.getDataLayout().getTypeStoreSize(T));
+
+return false;
+  };
+
+  if (!CheckAtomicSupport(Update.getScalarVal()->getType(), BO) ||
+  !CheckAtomicSupport(X.getAddress(CGF).getElementType(), BO))
+return std::make_pair(false, RValue::get(nullptr));
+
+  bool IsInteger = X.getAddress(CGF).getElementType()->isIntegerTy();
   llvm::AtomicRMWInst::BinOp RMWOp;
   switch (BO) {
   case BO_Add:
-RMWOp = llvm::AtomicRMWInst::Add;
+RMWOp = IsInteger ? llvm::AtomicRMWInst::Add : llvm::AtomicRMWInst::FAdd;
 break;
   case BO_Sub:
 if (!IsXLHSInRHSPart)
   return std::make_pair(false, RValue::get(nullptr));
-RMWOp = llvm::AtomicRMWInst::Sub;
+RMWOp = IsInteger ? llvm::AtomicRMWInst::Sub : llvm::AtomicRMWInst::FSub;
 break;
   case BO_And:
 RMWOp = llvm::AtomicRMWInst::And;
@@ -5914,9 +5927,13 @@ static std::pair 
emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
   }
   llvm::Value *UpdateVal = Update.getScalarVal();
   if (auto *IC = dyn_cast(UpdateVal)) {
-UpdateVal = CGF.Builder.CreateIntCast(
-IC, X.getAddress(CGF).getElementType(),
-X.getType()->hasSignedIntegerRepresentation());
+if (IsInteger)
+  UpdateVal = CGF.Builder.CreateIntCast(
+  IC, X.getAddress(CGF).getElementType(),
+  X.getType()->hasSignedIntegerRepresentation());
+else
+  UpdateVal = CGF.Builder.CreateCast(llvm::Instruction::CastOps::UIToFP, 
IC,
+ X.getAddress(CGF).getElementType());
   }
   llvm::Value *Res =
   CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO);

diff  --git a/clang/test/OpenMP/atomic_capture_codegen.cpp 
b/clang/test/OpenMP/atomic_capture_codegen.cpp
index c5f45a39232c0..95509df9ba935 100644
--- a/clang/test/OpenMP/atomic_capture_codegen.cpp
+++ b/clang/test/OpenMP/atomic_capture_codegen.cpp
@@ -216,20 +216,8 @@ int main(void) {
 #pragma omp atomic capture
   llv = ullx |= ullv;
 // CHECK: [[EXPR:%.+]] = load float, float* @{{.+}},
-// CHECK: [[X:%.+]] = load atomic i32, i32*  bitcast (float* [[X_ADDR:@.+]] to 
i32*) monotonic, align 4
-// CHECK: br label %[[CONT:.+]]
-// CHECK: [[CONT]]
-// CHECK: [[EXPECTED:%.+]] = phi i32 [ [[X]], %{{.+}} ], [ [[OLD_X:%.+]], 
%[[CONT]] ]
-// CHECK: [[TEMP_I:%.+]] = bitcast float* [[TEMP:%.+]] to i32*
-// CHECK: [[OLD:%.+]] = bitcast i32 [[EXPECTED]] to float
+// CHECK: [[OLD:%.+]] = atomicrmw fadd float* @{{.+}}, float 

[PATCH] D124724: [Clang][OpenMP] Add the support for floating-point variables for specific atomic clauses

2022-05-03 Thread Shilei Tian 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 rG9c1085c7e20b: [Clang][OpenMP] Add the support for 
floating-point variables for specific… (authored by tianshilei1992).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124724

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/atomic_capture_codegen.cpp
  clang/test/OpenMP/atomic_update_codegen.cpp
  clang/test/OpenMP/for_reduction_codegen.cpp
  clang/test/OpenMP/parallel_reduction_codegen.cpp
  clang/test/OpenMP/reduction_implicit_map.cpp
  clang/test/OpenMP/sections_reduction_codegen.cpp

Index: clang/test/OpenMP/sections_reduction_codegen.cpp
===
--- clang/test/OpenMP/sections_reduction_codegen.cpp
+++ clang/test/OpenMP/sections_reduction_codegen.cpp
@@ -268,11 +268,9 @@
 // CHECK1-NEXT:[[T_VAR15:%.*]] = alloca float, align 4
 // CHECK1-NEXT:[[DOTOMP_REDUCTION_RED_LIST:%.*]] = alloca [4 x i8*], align 8
 // CHECK1-NEXT:[[REF_TMP:%.*]] = alloca [[STRUCT_S]], align 4
+// CHECK1-NEXT:[[REF_TMP16:%.*]] = alloca [[STRUCT_S]], align 4
 // CHECK1-NEXT:[[ATOMIC_TEMP:%.*]] = alloca float, align 4
 // CHECK1-NEXT:[[TMP:%.*]] = alloca float, align 4
-// CHECK1-NEXT:[[REF_TMP17:%.*]] = alloca [[STRUCT_S]], align 4
-// CHECK1-NEXT:[[ATOMIC_TEMP27:%.*]] = alloca float, align 4
-// CHECK1-NEXT:[[_TMP28:%.*]] = alloca float, align 4
 // CHECK1-NEXT:store i32* [[DOTGLOBAL_TID_]], i32** [[DOTGLOBAL_TID__ADDR]], align 8
 // CHECK1-NEXT:store i32* [[DOTBOUND_TID_]], i32** [[DOTBOUND_TID__ADDR]], align 8
 // CHECK1-NEXT:store float* [[T_VAR]], float** [[T_VAR_ADDR]], align 8
@@ -401,77 +399,59 @@
 // CHECK1-NEXT:br label [[DOTOMP_REDUCTION_DEFAULT]]
 // CHECK1:   .omp.reduction.case2:
 // CHECK1-NEXT:[[TMP43:%.*]] = load float, float* [[T_VAR2]], align 4
-// CHECK1-NEXT:[[TMP44:%.*]] = bitcast float* [[TMP0]] to i32*
-// CHECK1-NEXT:[[ATOMIC_LOAD:%.*]] = load atomic i32, i32* [[TMP44]] monotonic, align 4
-// CHECK1-NEXT:br label [[ATOMIC_CONT:%.*]]
-// CHECK1:   atomic_cont:
-// CHECK1-NEXT:[[TMP45:%.*]] = phi i32 [ [[ATOMIC_LOAD]], [[DOTOMP_REDUCTION_CASE2]] ], [ [[TMP53:%.*]], [[ATOMIC_CONT]] ]
-// CHECK1-NEXT:[[TMP46:%.*]] = bitcast float* [[ATOMIC_TEMP]] to i32*
-// CHECK1-NEXT:[[TMP47:%.*]] = bitcast i32 [[TMP45]] to float
-// CHECK1-NEXT:store float [[TMP47]], float* [[TMP]], align 4
-// CHECK1-NEXT:[[TMP48:%.*]] = load float, float* [[TMP]], align 4
-// CHECK1-NEXT:[[TMP49:%.*]] = load float, float* [[T_VAR2]], align 4
-// CHECK1-NEXT:[[ADD15:%.*]] = fadd float [[TMP48]], [[TMP49]]
-// CHECK1-NEXT:store float [[ADD15]], float* [[ATOMIC_TEMP]], align 4
-// CHECK1-NEXT:[[TMP50:%.*]] = load i32, i32* [[TMP46]], align 4
-// CHECK1-NEXT:[[TMP51:%.*]] = bitcast float* [[TMP0]] to i32*
-// CHECK1-NEXT:[[TMP52:%.*]] = cmpxchg i32* [[TMP51]], i32 [[TMP45]], i32 [[TMP50]] monotonic monotonic, align 4
-// CHECK1-NEXT:[[TMP53]] = extractvalue { i32, i1 } [[TMP52]], 0
-// CHECK1-NEXT:[[TMP54:%.*]] = extractvalue { i32, i1 } [[TMP52]], 1
-// CHECK1-NEXT:br i1 [[TMP54]], label [[ATOMIC_EXIT:%.*]], label [[ATOMIC_CONT]]
-// CHECK1:   atomic_exit:
+// CHECK1-NEXT:[[TMP44:%.*]] = atomicrmw fadd float* [[TMP0]], float [[TMP43]] monotonic, align 4
 // CHECK1-NEXT:call void @__kmpc_critical(%struct.ident_t* @[[GLOB3]], i32 [[TMP7]], [8 x i32]* @.gomp_critical_user_.atomic_reduction.var)
-// CHECK1-NEXT:[[CALL16:%.*]] = call noundef nonnull align 4 dereferenceable(4) %struct.S* @_ZN1SIfEanERKS0_(%struct.S* noundef nonnull align 4 dereferenceable(4) [[TMP1]], %struct.S* noundef nonnull align 4 dereferenceable(4) [[VAR3]])
-// CHECK1-NEXT:[[TMP55:%.*]] = bitcast %struct.S* [[TMP1]] to i8*
-// CHECK1-NEXT:[[TMP56:%.*]] = bitcast %struct.S* [[CALL16]] to i8*
-// CHECK1-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP55]], i8* align 4 [[TMP56]], i64 4, i1 false)
+// CHECK1-NEXT:[[CALL15:%.*]] = call noundef nonnull align 4 dereferenceable(4) %struct.S* @_ZN1SIfEanERKS0_(%struct.S* noundef nonnull align 4 dereferenceable(4) [[TMP1]], %struct.S* noundef nonnull align 4 dereferenceable(4) [[VAR3]])
+// CHECK1-NEXT:[[TMP45:%.*]] = bitcast %struct.S* [[TMP1]] to i8*
+// CHECK1-NEXT:[[TMP46:%.*]] = bitcast %struct.S* [[CALL15]] to i8*
+// CHECK1-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP45]], i8* align 4 [[TMP46]], i64 4, i1 false)
 // CHECK1-NEXT:call void @__kmpc_end_critical(%struct.ident_t* @[[GLOB3]], i32 [[TMP7]], [8 x i32]* @.gomp_critical_user_.atomic_reduction.var)
 // CHECK1-NEXT:call void @__kmpc_critical(%struct.ident_t* @[[GLOB3]], i32 [[TMP7]], [8 x i32]* @.gomp_critical_user_.atomic_reduction.var)
-// CHECK1-NEXT:[[CAL

[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-03 Thread Gabor Marton via Phabricator via cfe-commits
martong marked an inline comment as done.
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp:51
+ProgramStateRef StFalse = assume(State, Cond, false);
+if (!StFalse) { // both infeasible
+  ProgramStateRef Infeasible = State->cloneAsInfeasible();

martong wrote:
> martong wrote:
> > steakhal wrote:
> > > Should we mark this `LLVM_UNLIKELY(cond)`?
> > > I would expect this function to be quite hot, and infeasible states rare.
> > > 
> > > Could we measure this one?
> > Yes, it could be.
> > 
> > Let me come back with some measurement results soon. I am going to use llvm 
> > statistics macros to measure this, but that makes sense on top of D124758
> This is what I use for the measurement, stay tuned for the results.
> ```
> diff --git a/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp 
> b/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
> index ef98ed7d36e9..82097d67ec0f 100644
> --- a/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
> +++ b/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
> @@ -16,10 +16,16 @@
>  #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
>  #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
>  #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
> +#include "llvm/ADT/Statistic.h"
> 
>  using namespace clang;
>  using namespace ento;
> 
> +#define DEBUG_TYPE "CoreEngine"
> +
> +STATISTIC(NumInfeasible, "The # of infeasible states");
> +STATISTIC(NumFeasible, "The # of feasible states");
> +
>  ConstraintManager::~ConstraintManager() = default;
> 
>  static DefinedSVal getLocFromSymbol(const ProgramStateRef &State,
> @@ -51,16 +57,20 @@ ConstraintManager::assumeDual(ProgramStateRef State, 
> DefinedSVal Cond) {
>  if (!StFalse) { // both infeasible
>ProgramStateRef Infeasible = State->cloneAsInfeasible();
>assert(Infeasible->isInfeasible());
> +  ++NumInfeasible;
>return ProgramStatePair(Infeasible, Infeasible);
>  }
> +++NumFeasible;
>  return ProgramStatePair(nullptr, StFalse);
>}
> 
>ProgramStateRef StFalse = assumeInternal(State, Cond, false);
>if (!StFalse) {
> +++NumFeasible;
>  return ProgramStatePair(StTrue, nullptr);
>}
> 
> +  ++NumFeasible;
>return ProgramStatePair(StTrue, StFalse);
>  }
> ```
Ups, the purpose of the measure is to determine if UNLIKELY is justified, so 
this diff seems better, restarted the measurement with it.
```
--- a/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -16,10 +16,16 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/Statistic.h"

 using namespace clang;
 using namespace ento;

+#define DEBUG_TYPE "CoreEngine"
+
+STATISTIC(NumInfeasible, "The # of infeasible states");
+STATISTIC(NumFeasible, "The # of feasible states");
+
 ConstraintManager::~ConstraintManager() = default;

 static DefinedSVal getLocFromSymbol(const ProgramStateRef &State,
@@ -51,8 +57,10 @@ ConstraintManager::assumeDual(ProgramStateRef State, 
DefinedSVal Cond) {
 if (!StFalse) { // both infeasible
   ProgramStateRef Infeasible = State->cloneAsInfeasible();
   assert(Infeasible->isInfeasible());
+  ++NumInfeasible;
   return ProgramStatePair(Infeasible, Infeasible);
 }
+++NumFeasible;
 return ProgramStatePair(nullptr, StFalse);
   }

```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D124807: [clang][dataflow] Avoid assert for invalid cast to BoolValue

2022-05-03 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:78
+/// and integers in the framework.
+static const Expr *ignoreParenImpCastsExceptToBool(const Expr *E) {
+  const Expr *LastE = nullptr;

I don't recall why we need to ignore implicit casts here. Can't we ignore 
parens and rely on the built-in transfer function, possibly adding handling of 
some missing casts there? 
https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/Transfer.cpp#L192


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124807

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


[PATCH] D123831: [clang][extract-api] Use relative includes

2022-05-03 Thread Daniel Grumberg via Phabricator via cfe-commits
dang accepted this revision.
dang added a comment.
This revision is now accepted and ready to land.

Minor comment LGTM otherwise




Comment at: clang/lib/ExtractAPI/ExtractAPIConsumer.cpp:203
+// Try to reduce the include name the same way we tried to include it.
+if (auto IncludeName = getRelativeIncludeName(CI, FileName))
+  if (llvm::find(KnownFiles, *IncludeName) != KnownFiles.end()) {

Should we be tracking if the include was quoted or not? In principle, that 
could mean a different redirect in header search and therefore potentially 
mapping to different content.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123831

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


[PATCH] D121370: [clang-format] SortIncludes should support "@import" lines in Objective-C

2022-05-03 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk planned changes to this revision.
kwk added a comment.

Some thing that doesn't work at the moment is ordering an include like this:

  #include /*some include*/ "wontwork.h"

I wonder if it worked before. Let's see. Yes it worked. Grrr. I guess I need to 
do more...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121370

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


[PATCH] D123952: [FPEnv] Allow CompoundStmt to keep FP options

2022-05-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thanks for working on this! One thing that's not clear to me is what bugs this 
is solving -- the test coverage only shows a change to textual AST dumping 
behavior. Is this otherwise expected to be an NFC change, or should there be 
some codegen tests that show a difference in behavior?




Comment at: clang/include/clang/AST/Stmt.h:134
+/// floating-point features.
+unsigned HasFPFeatures : 1;
+

I don't think this is a bad approach, but it does further reduce the number of 
statements we support in a compound statement.

There's a part of me that wonders if the approach is to introduce a new AST 
node for a stateful compound statement; I suspect if we dig around, we'll find 
other pragmas that want to behave similar to floating-point feature pragmas 
(the idea of a pragma scoped to a block is not really new). Having something 
more general means we're less likely to keep stealing bits here.



Comment at: clang/include/clang/Sema/ScopeInfo.h:77-78
 
-  CompoundScopeInfo(bool IsStmtExpr) : IsStmtExpr(IsStmtExpr) {}
+  /// FP options at the beginning of the compound statement, prior to
+  /// any pragma.
+  FPOptions FPFeatures;

So these are the initial FPOptions inherited by the scope from its surrounding 
context? And it's never updated by a pragma?



Comment at: clang/lib/AST/TextNodeDumper.cpp:2372-2376
+void TextNodeDumper::VisitCompoundStmt(const CompoundStmt *S) {
+  VisitStmt(S);
+  if (S->hasStoredFPFeatures())
+printFPOptions(S->getStoredFPFeatures());
+}

Should we have a similar change for the JSON node dumper?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123952

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


[clang] 2deebc0 - [RFC] Add and sort decl to maintain order instead of inserting in order

2022-05-03 Thread Ivan Murashko via cfe-commits

Author: Kugan Vivekanandarajah
Date: 2022-05-03T17:06:22+01:00
New Revision: 2deebc0048f92811dc92c7e41d357683b84febf7

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

LOG: [RFC] Add and sort decl to maintain order instead of inserting in order

ASTWriter::associateDeclWithFile shows a lot in clangd perf profile due to 
O(n^2) behaviour in insertion of DeclIDs in SortedFileDeclIDs. Instead of doing 
that, this patch just appends it to the DeclIDs vector and sorts them at the 
end.

Reviewed By: akyrtzi

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

Added: 


Modified: 
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 189d1a914ec31..228bd9aa08db4 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -3114,6 +3114,7 @@ void ASTWriter::WriteFileDeclIDsMap() {
   for (auto &FileDeclEntry : SortedFileDeclIDs) {
 DeclIDInFileInfo &Info = *FileDeclEntry.second;
 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
+llvm::stable_sort(Info.DeclIDs);
 for (auto &LocDeclEntry : Info.DeclIDs)
   FileGroupedDeclIDs.push_back(LocDeclEntry.second);
   }
@@ -5462,16 +5463,7 @@ void ASTWriter::associateDeclWithFile(const Decl *D, 
DeclID ID) {
 
   std::pair LocDecl(Offset, ID);
   LocDeclIDsTy &Decls = Info->DeclIDs;
-
-  if (Decls.empty() || Decls.back().first <= Offset) {
-Decls.push_back(LocDecl);
-return;
-  }
-
-  LocDeclIDsTy::iterator I =
-  llvm::upper_bound(Decls, LocDecl, llvm::less_first());
-
-  Decls.insert(I, LocDecl);
+  Decls.push_back(LocDecl);
 }
 
 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {



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


[PATCH] D124840: [RFC] Add and sort decl to maintain order instead of inserting in order

2022-05-03 Thread Ivan Murashko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2deebc0048f9: [RFC] Add and sort decl to maintain order 
instead of inserting in order (authored by kuganv, committed by ivanmurashko).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124840

Files:
  clang/lib/Serialization/ASTWriter.cpp


Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -3114,6 +3114,7 @@
   for (auto &FileDeclEntry : SortedFileDeclIDs) {
 DeclIDInFileInfo &Info = *FileDeclEntry.second;
 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
+llvm::stable_sort(Info.DeclIDs);
 for (auto &LocDeclEntry : Info.DeclIDs)
   FileGroupedDeclIDs.push_back(LocDeclEntry.second);
   }
@@ -5462,16 +5463,7 @@
 
   std::pair LocDecl(Offset, ID);
   LocDeclIDsTy &Decls = Info->DeclIDs;
-
-  if (Decls.empty() || Decls.back().first <= Offset) {
-Decls.push_back(LocDecl);
-return;
-  }
-
-  LocDeclIDsTy::iterator I =
-  llvm::upper_bound(Decls, LocDecl, llvm::less_first());
-
-  Decls.insert(I, LocDecl);
+  Decls.push_back(LocDecl);
 }
 
 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {


Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -3114,6 +3114,7 @@
   for (auto &FileDeclEntry : SortedFileDeclIDs) {
 DeclIDInFileInfo &Info = *FileDeclEntry.second;
 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
+llvm::stable_sort(Info.DeclIDs);
 for (auto &LocDeclEntry : Info.DeclIDs)
   FileGroupedDeclIDs.push_back(LocDeclEntry.second);
   }
@@ -5462,16 +5463,7 @@
 
   std::pair LocDecl(Offset, ID);
   LocDeclIDsTy &Decls = Info->DeclIDs;
-
-  if (Decls.empty() || Decls.back().first <= Offset) {
-Decls.push_back(LocDecl);
-return;
-  }
-
-  LocDeclIDsTy::iterator I =
-  llvm::upper_bound(Decls, LocDecl, llvm::less_first());
-
-  Decls.insert(I, LocDecl);
+  Decls.push_back(LocDecl);
 }
 
 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124669: [flang][driver] Add support for -save-temps

2022-05-03 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 426739.
awarzynski added a comment.

Add a test, restore white-space in Options.td


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124669

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/Types.def
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/fno-integrated-as.f90
  flang/test/Driver/save-temps.f90

Index: flang/test/Driver/save-temps.f90
===
--- /dev/null
+++ flang/test/Driver/save-temps.f90
@@ -0,0 +1,53 @@
+! Tests for the `-save-temps` flag. As `flang` does not implement `-fc1as` (i.e. a driver for the intergrated assembly), we need to
+! use `-fno-integrated-as` here.
+
+!--
+! Basic case: `-save-temps`
+!--
+! RUN: %flang -save-temps -fno-integrated-as %s -### 2>&1 | FileCheck %s
+! CHECK: "-o" "save-temps.i"
+! CHECK-NEXT: "-o" "save-temps.bc"
+! CHECK-NEXT: "-o" "save-temps.s"
+! CHECK-NEXT: "-o" "save-temps.o"
+! CHECK-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=cwd`
+!--
+! This should work the same as -save-temps above
+
+! RUN: %flang -save-temps=cwd -fno-integrated-as  %s -### 2>&1 | FileCheck %s -check-prefix=CWD
+! CWD: "-o" "save-temps.i"
+! CWD-NEXT: "-o" "save-temps.bc"
+! CWD-NEXT: "-o" "save-temps.s"
+! CWD-NEXT: "-o" "save-temps.o"
+! CWD-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=obj`
+!--
+! Check that temp files are saved in the same directory as the output file
+! regardless of whether -o is specified.
+
+! RUN: %flang -save-temps=obj -fno-integrated-as -o obj/dir/a.out %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ
+! CHECK-OBJ: "-o" "obj/dir/save-temps.i"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.bc"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.s"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.o"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/a.out"
+
+! RUN: %flang -save-temps=obj -fno-integrated-as %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ-NOO
+! CHECK-OBJ-NOO: "-o" "save-temps.i"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.bc"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.s"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.o"
+! CHECK-OBJ-NOO-NEXT: "-o" "a.out"
+
+!--
+! `-S` without `-save-temps`
+!--
+! Check for a single `flang -fc1` invocation when NOT using -save-temps.
+! RUN: %flang -S %s -### 2>&1 | FileCheck %s -check-prefix=NO-TEMPS
+! NO-TEMPS: "-fc1"
+! NO-TEMPS-SAME: "-S"
+! NO-TEMPS-SAME: "-o" "save-temps.s"
Index: flang/test/Driver/fno-integrated-as.f90
===
--- /dev/null
+++ flang/test/Driver/fno-integrated-as.f90
@@ -0,0 +1,18 @@
+! Tests for the `-fno-integrated-as` flag.
+
+!--
+! With `-fno-integrated-as`
+!--
+! Verify that there _is_ a seperate line with an assembler invocation
+! RUN: %flang -c -fno-integrated-as %s -### 2>&1 | FileCheck %s
+! CHECK-LABEL: "-fc1"
+! CHECK-SAME: "-o" "[[assembly_file:.*]].s"
+! CHECK-NEXT: "-o" "fno-integrated-as.o" "[[assembly_file:.*]].s"
+
+!-
+! Without `-fno-integrated-as`
+!-
+! Verify that there _is no_ seperate line with an assembler invocation
+! RUN: %flang -c %s -### 2>&1 | FileCheck %s -check-prefix=DEFAULT
+! DEFAULT-LABEL: "-fc1"
+! DEFAULT-SAME: "-o" "fno-integrated-as.o" "[[assembly_file:.*]].s"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -42,6 +42,7 @@
 ! HELP-NEXT: -flogical-abbreviations Enable logical abbreviations
 ! HELP-NEXT: -fno-automatic Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE
 ! HELP-NEXT: -fno-color-diagnostics  Disable colors in diagnostics
+! HELP-NEXT: -fno-integrated-as  Disable the integrated assembler
 ! HELP-NEXT: -fopenacc  Enable OpenACC
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
@@ -56,6 +57,8 @@
 ! HELP-NEXT: -print-effective-triple Print the effective target triple
 ! HELP-NEXT: -print-target-triplePrint the normalized target triple
 ! HELP-NEXT: -P Disable linemarker output in -E mode
+! HELP-NEXT: -save-temps=Save intermediate compilation results.
+! HELP-NEXT: -save-tempsSave intermediate compilation results
 ! HELP-NEXT: -std=   Language standard to compile for
 ! HELP-NEXT: -S Only run preprocess and compilation steps
 ! HELP-NEXT: --target=   Generate code for the given target
Inde

[PATCH] D121370: [clang-format] SortIncludes should support "@import" lines in Objective-C

2022-05-03 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk added a comment.

I found another problem with both regular expressions (pre mine and mine): They 
cannot find

  /* a comment before */ #include 

Is this a known problem @MyDeveloperDay @owenpan @krasimir ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121370

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


[PATCH] D123009: [Sema] Enum conversion warning when one signed and other unsigned.

2022-05-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Also, before we land this, you should add a release note to 
clang/docs/ReleaseNotes.rst about the bugfix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123009

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


[PATCH] D124669: [flang][driver] Add support for -save-temps

2022-05-03 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 426747.
awarzynski added a comment.

Fix failing test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124669

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/Types.def
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/fno-integrated-as.f90
  flang/test/Driver/save-temps.f90

Index: flang/test/Driver/save-temps.f90
===
--- /dev/null
+++ flang/test/Driver/save-temps.f90
@@ -0,0 +1,53 @@
+! Tests for the `-save-temps` flag. As `flang` does not implement `-fc1as` (i.e. a driver for the intergrated assembly), we need to
+! use `-fno-integrated-as` here.
+
+!--
+! Basic case: `-save-temps`
+!--
+! RUN: %flang -save-temps -fno-integrated-as %s -### 2>&1 | FileCheck %s
+! CHECK: "-o" "save-temps.i"
+! CHECK-NEXT: "-o" "save-temps.bc"
+! CHECK-NEXT: "-o" "save-temps.s"
+! CHECK-NEXT: "-o" "save-temps.o"
+! CHECK-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=cwd`
+!--
+! This should work the same as -save-temps above
+
+! RUN: %flang -save-temps=cwd -fno-integrated-as  %s -### 2>&1 | FileCheck %s -check-prefix=CWD
+! CWD: "-o" "save-temps.i"
+! CWD-NEXT: "-o" "save-temps.bc"
+! CWD-NEXT: "-o" "save-temps.s"
+! CWD-NEXT: "-o" "save-temps.o"
+! CWD-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=obj`
+!--
+! Check that temp files are saved in the same directory as the output file
+! regardless of whether -o is specified.
+
+! RUN: %flang -save-temps=obj -fno-integrated-as -o obj/dir/a.out %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ
+! CHECK-OBJ: "-o" "obj/dir/save-temps.i"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.bc"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.s"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.o"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/a.out"
+
+! RUN: %flang -save-temps=obj -fno-integrated-as %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ-NOO
+! CHECK-OBJ-NOO: "-o" "save-temps.i"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.bc"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.s"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.o"
+! CHECK-OBJ-NOO-NEXT: "-o" "a.out"
+
+!--
+! `-S` without `-save-temps`
+!--
+! Check for a single `flang -fc1` invocation when NOT using -save-temps.
+! RUN: %flang -S %s -### 2>&1 | FileCheck %s -check-prefix=NO-TEMPS
+! NO-TEMPS: "-fc1"
+! NO-TEMPS-SAME: "-S"
+! NO-TEMPS-SAME: "-o" "save-temps.s"
Index: flang/test/Driver/fno-integrated-as.f90
===
--- /dev/null
+++ flang/test/Driver/fno-integrated-as.f90
@@ -0,0 +1,18 @@
+! Tests for the `-fno-integrated-as` flag.
+
+!--
+! With `-fno-integrated-as`
+!--
+! Verify that there _is_ a seperate line with an assembler invocation
+! RUN: %flang -c -fno-integrated-as %s -### 2>&1 | FileCheck %s
+! CHECK-LABEL: "-fc1"
+! CHECK-SAME: "-o" "[[assembly_file:.*]].s"
+! CHECK-NEXT: "-o" "fno-integrated-as.o" "[[assembly_file:.*]].s"
+
+!-
+! Without `-fno-integrated-as`
+!-
+! Verify that there _is no_ seperate line with an assembler invocation
+! RUN: %flang -c %s -### 2>&1 | FileCheck %s -check-prefix=DEFAULT
+! DEFAULT-LABEL: "-fc1"
+! DEFAULT-SAME: "-o" "fno-integrated-as.o" "{{.*}}fno-integrated-as.f90"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -42,6 +42,7 @@
 ! HELP-NEXT: -flogical-abbreviations Enable logical abbreviations
 ! HELP-NEXT: -fno-automatic Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE
 ! HELP-NEXT: -fno-color-diagnostics  Disable colors in diagnostics
+! HELP-NEXT: -fno-integrated-as  Disable the integrated assembler
 ! HELP-NEXT: -fopenacc  Enable OpenACC
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
@@ -56,6 +57,8 @@
 ! HELP-NEXT: -print-effective-triple Print the effective target triple
 ! HELP-NEXT: -print-target-triplePrint the normalized target triple
 ! HELP-NEXT: -P Disable linemarker output in -E mode
+! HELP-NEXT: -save-temps=Save intermediate compilation results.
+! HELP-NEXT: -save-tempsSave intermediate compilation results
 ! HELP-NEXT: -std=   Language standard to compile for
 ! HELP-NEXT: -S Only run preprocess and compilation steps
 ! HELP-NEXT: --target=   Generate code for the given target
Index: flang/test/Driver/dri

[PATCH] D124860: [clang][AArch64][SVE] Implicit conversions for vector-scalar operations

2022-05-03 Thread David Truby via Phabricator via cfe-commits
DavidTruby created this revision.
Herald added subscribers: ctetreau, psnobl, kristof.beyls, tschuett.
Herald added a reviewer: efriedma.
Herald added a project: All.
DavidTruby requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch allows the same implicit conversions for vector-scalar
operations in SVE that are allowed for NEON.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124860

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGen/aarch64-sve-vector-arith-ops.c
  clang/test/Sema/aarch64-sve-vector-arith-ops.c
  clang/test/Sema/sizeless-1.c
  clang/test/SemaCXX/sizeless-1.cpp

Index: clang/test/SemaCXX/sizeless-1.cpp
===
--- clang/test/SemaCXX/sizeless-1.cpp
+++ clang/test/SemaCXX/sizeless-1.cpp
@@ -213,23 +213,6 @@
   local_int8 &&init_int8;  // expected-error {{invalid operands to binary expression}} expected-error {{not contextually convertible}}
   local_int8 || init_int8; // expected-error {{invalid operands to binary expression}} expected-error {{not contextually convertible}}
 
-  local_int8 + 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 - 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 * 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 / 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 % 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 & 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 | 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 ^ 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 < 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 <= 0; // expected-error {{invalid operands to binary expression}}
-  local_int8 == 0; // expected-error {{invalid operands to binary expression}}
-  local_int8 != 0; // expected-error {{invalid operands to binary expression}}
-  local_int8 >= 0; // expected-error {{invalid operands to binary expression}}
-  local_int8 > 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 && 0; // expected-error {{invalid operands to binary expression}} expected-error {{not contextually convertible}}
-  local_int8 || 0; // expected-error {{invalid operands to binary expression}} expected-error {{not contextually convertible}}
-
   if (local_int8) { // expected-error {{not contextually convertible to 'bool'}}
   }
   while (local_int8) { // expected-error {{not contextually convertible to 'bool'}}
Index: clang/test/Sema/sizeless-1.c
===
--- clang/test/Sema/sizeless-1.c
+++ clang/test/Sema/sizeless-1.c
@@ -201,23 +201,6 @@
   local_int8 &&init_int8;  // expected-error {{invalid operands to binary expression}}
   local_int8 || init_int8; // expected-error {{invalid operands to binary expression}}
 
-  local_int8 + 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 - 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 * 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 / 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 % 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 & 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 | 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 ^ 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 < 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 <= 0; // expected-error {{invalid operands to binary expression}}
-  local_int8 == 0; // expected-error {{invalid operands to binary expression}}
-  local_int8 != 0; // expected-error {{invalid operands to binary expression}}
-  local_int8 >= 0; // expected-error {{invalid operands to binary expression}}
-  local_int8 > 0;  // expected-error {{invalid operands to binary expression}}
-  local_int8 && 0; // expected-error {{invalid operands to binary expression}}
-  local_int8 || 0; // expected-error {{invalid operands to binary expression}}
-
   if (local_int8) { // expected-error {{statement requires expression of scalar type}}
   }
   while (local_int8) { // expected-error {{statement requires expression of scalar type}}
Index: clang/test/Sema/aarch64-sve-vector-arith-ops.c
===
--- clang/test/Sema/aarch64-sve-vector-arith-ops.c
+++ clang/test/Sema/aarch64-sve-vector-arith-ops.c
@@ -20,12 +20,6 @@
   (void)(i8 + f16); // expected-error{{invalid operands to binary expression}}
   (void)(i8 + f32); // expected-error{{invalid operands to binary expression}}
   (void)(i8 + f64); // expected-error{{invalid operan

[PATCH] D124807: [clang][dataflow] Avoid assert for invalid cast to BoolValue

2022-05-03 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:78
+/// and integers in the framework.
+static const Expr *ignoreParenImpCastsExceptToBool(const Expr *E) {
+  const Expr *LastE = nullptr;

sgatev wrote:
> I don't recall why we need to ignore implicit casts here. Can't we ignore 
> parens and rely on the built-in transfer function, possibly adding handling 
> of some missing casts there? 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/Transfer.cpp#L192
If we only ignore parens, a test in the optional checker tests begins to fail, 
specifically `UncheckedOptionalAccessTest.ValueOrComparison`. The missing 
"cast" is an `ExprWithCleanups`. I didn't know how to deal with that, so this 
patch just working around the assert.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124807

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


[PATCH] D120495: [clang][dataflow] Add transfer functions for structured bindings

2022-05-03 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:80
+///
+/// FIXME: Consider adding support for structured bindings to the CFG builder.
+class DecompositionVisitor : public ConstStmtVisitor {

sgatev wrote:
> xazax.hun wrote:
> > Did you look into how hard would it be to add structured bindings to the 
> > CFG builder? If the effort is comparable to this patch (and not 
> > significantly bigger), it might be better to do that work instead of 
> > spending effort on some temporary workaround. What do you think?
> Circling back to this after a while. I believe we explored changing the CFG 
> briefly, but don't have a fully fleshed out proposal for it. I recently 
> noticed 
> https://discourse.llvm.org/t/implement-support-for-c-17-structured-bindings-in-the-clang-static-analyzer/60588.
>  It seems that part of the project is exploring necessary changes to the CFG. 
> What do you think about submitting this patch with local pattern matching and 
> revisiting that once the GSoC project completes?
Officially, there is no candidate accepted for that project yet, so there is no 
guarantee that we will have someone working on this. That being said, the CSA 
devs started to discuss what would be the best way to represent structured 
bindings in the CFG, and it is possible that for many of the cases we do not 
actually need to change the CFG, because the AST nodes have rich information. 
But of course, none of this is final, but we do not need to block this patch on 
that. So I'm fine adding this for now.

The AST for the supported case looks like:
```
   `-DeclStmt 0x5599ad9de6b0 
  `-DecompositionDecl 0x5599ad9de310  col:13 used 'A &' cinit
|-DeclRefExpr 0x5599ad9de388  'A' lvalue Var 0x5599ad9ddb80 
'Baz' 'A'
|-BindingDecl 0x5599ad9de280  col:14 BoundFooRef 'int'
| `-MemberExpr 0x5599ad9de630  'int' lvalue .Foo 0x5599ad9dd970
|   `-DeclRefExpr 0x5599ad9de610  'A':'A' lvalue Decomposition 
0x5599ad9de310 '' 'A &'
`-BindingDecl 0x5599ad9de2c8  col:27 BoundBarRef 'int'
  `-MemberExpr 0x5599ad9de680  'int' lvalue .Bar 0x5599ad9dd9d8
`-DeclRefExpr 0x5599ad9de660  'A':'A' lvalue Decomposition 
0x5599ad9de310 '' 'A &'
``` 

So each `BindingDecl` is like:
```
`-BindingDecl 0x5599ad9de2c8  col:27 BoundBarRef 'int'
  `-MemberExpr 0x5599ad9de680  'int' lvalue .Bar 0x5599ad9dd9d8
`-DeclRefExpr 0x5599ad9de660  'A':'A' lvalue Decomposition 
0x5599ad9de310 '' 'A &'
```

Is there a case where the `BindingDecl` would have a different shape? If we do 
not expect that happening, I feel like an `StmtVisitor` is a bit of an overkill 
for this and we could handle the supported case more directly. What do you 
think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120495

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


[PATCH] D124666: In MSVC compatibility mode, handle unqualified templated base class initialization

2022-05-03 Thread Reid Kleckner via Phabricator via cfe-commits
rnk requested changes to this revision.
rnk added inline comments.
This revision now requires changes to proceed.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:4310-4311
 
   // If no results were found, try to correct typos.
   TypoCorrection Corr;
   MemInitializerValidatorCCC CCC(ClassDecl);

We have to make sure our MS compatibility logic fires *before* we try to 
correct typos. It's currently a big issue that we don't. You can try adjusting 
your test case by adding a similarly named class like `Baze` and see if you 
still get the desired behavior.

See this old issue from 2014:
https://github.com/llvm/llvm-project/issues/20623


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

https://reviews.llvm.org/D124666

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


[PATCH] D124807: [clang][dataflow] Avoid assert for invalid cast to BoolValue

2022-05-03 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:78
+/// and integers in the framework.
+static const Expr *ignoreParenImpCastsExceptToBool(const Expr *E) {
+  const Expr *LastE = nullptr;

li.zhe.hua wrote:
> sgatev wrote:
> > I don't recall why we need to ignore implicit casts here. Can't we ignore 
> > parens and rely on the built-in transfer function, possibly adding handling 
> > of some missing casts there? 
> > https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/Transfer.cpp#L192
> If we only ignore parens, a test in the optional checker tests begins to 
> fail, specifically `UncheckedOptionalAccessTest.ValueOrComparison`. The 
> missing "cast" is an `ExprWithCleanups`. I didn't know how to deal with that, 
> so this patch just working around the assert.
In general, I prefer to handle as much as possible with transfer functions and 
skip as little as possible in the AST. We might skip `ExprWithCleanups` nodes 
today, but we will need them tomorrow to properly model where certain 
destructors are being invoked. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124807

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


[PATCH] D124790: [HLSL] Enable half type for hlsl.

2022-05-03 Thread Xiang Li via Phabricator via cfe-commits
python3kgae marked 3 inline comments as done.
python3kgae added inline comments.



Comment at: clang/lib/Basic/LangOptions.cpp:197
 
-  // OpenCL has half keyword
-  Opts.Half = Opts.OpenCL;
+  // OpenCL and HLSL have half keyword
+  Opts.Half = Opts.OpenCL || Opts.HLSL;

aaron.ballman wrote:
> Shouldn't this be looking for HLSL 2018? Or shader model 6.2?
half keyword is always available.
Without enable_16bit_types, half will be like using half=float.
With enable_16bit_types, half will be real half.

The check for HLSL 2018 and shader model 6.2 will be in another PR, still WIP. 
I'll add FIXME about it.



Comment at: clang/lib/Basic/Targets/DirectX.h:61
   }
-
+  bool useFP16ConversionIntrinsics() const override { return false; }
   void getTargetDefines(const LangOptions &Opts,

aaron.ballman wrote:
> Should this be tied to the `Half` language option?
We don't want to conversion FP16, with or without enable_16bit_types.
With enable_16bit_types, it is half, don't need conversion.
Without enable_16bit_types, it will be a float, don't need conversion either.



Comment at: clang/lib/Sema/SemaType.cpp:1514
+// For HLSL, when not enable native half type, half will be treat as float.
+if (S.getLangOpts().HLSL && !S.getLangOpts().NativeHalfType)
+  Result = Context.FloatTy;

aaron.ballman wrote:
> This change seems wrong to me -- if the half type isn't supported, how does 
> the user spell the type such that we can even get here?
Half keyword is always available for hlsl.
When enable_16bit_types, NativeHalfType will be true, half will be a real half.
When not enable_16bit_types, NativeHalfType will be false, half will be float.




Comment at: clang/test/CodeGenHLSL/half.hlsl:15
+  return a+b;
+}

aaron.ballman wrote:
> FWIW, this test seems to be failing precommit CI.
> 
> We should also have tests for the new driver flag and Sema tests showing that 
> you can't spell `half` in unsupported HLSL modes.
I think the issue is this test require build DirectX backend target.
I'll change it to work without DirectX backend target.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124790

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


[PATCH] D119147: [AIX][clang][driver] Check the command string to the linker for exportlist opts and

2022-05-03 Thread Steven Wan via Phabricator via cfe-commits
stevewan accepted this revision.
stevewan added a comment.
This revision is now accepted and ready to land.

LGTM other than some nits.




Comment at: clang/lib/Driver/Job.cpp:361
+
+  if (!RedirectFiles.empty()) {
+std::vector> RedirectFilesOptional;





Comment at: clang/test/Driver/aix-ld.c:675-676
+// CHECK-LD32-SHARED-EXPORTS-NOT: "{{.*}}llvm-nm"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "-X"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "32"
+// CHECK-LD32-SHARED-EXPORTS: "{{.*}}ld{{(.exe)?}}"

And please keep this consistent across the tests.



Comment at: clang/test/Driver/aix-ld.c:776-777
+// CHECK-LD64-SHARED-EXPORTS-NOT: "{{.*}}llvm-nm"
+// CHECK-LD64-SHARED-EXPORTS-NOT: "-X"
+// CHECK-LD64-SHARED-EXPORTS-NOT: "64"
+// CHECK-LD64-SHARED-EXPORTS: "{{.*}}ld{{(.exe)?}}"

Ditto.



Comment at: clang/test/Driver/aix-ld.c:826-827
+// CHECK-LD64-SHARED-EXPORTS-ALT-NOT: "{{.*}}llvm-nm"
+// CHECK-LD64-SHARED-EXPORTS-ALT-NOT: "-X"
+// CHECK-LD64-SHARED-EXPORTS-ALT-NOT: "64"
+// CHECK-LD64-SHARED-EXPORTS-ALT: "{{.*}}ld{{(.exe)?}}"

Ditto.



Comment at: clang/test/Driver/aix-ld.c:903-904
+// CHECK-LD64-SHARED-EXPALL-NOT: "{{.*}}llvm-nm"
+// CHECK-LD64-SHARED-EXPALL-NOT: "-X"
+// CHECK-LD64-SHARED-EXPALL-NOT: "64"
+// CHECK-LD64-SHARED-EXPALL: "{{.*}}ld{{(.exe)?}}"

Ditto.



Comment at: clang/test/Driver/aix-ld.c:981-982
+// CHECK-LD64-SHARED-EXPFULL-NOT: "{{.*}}llvm-nm"
+// CHECK-LD64-SHARED-EXPFULL-NOT: "-X"
+// CHECK-LD64-SHARED-EXPFULL-NOT: "64"
+// CHECK-LD64-SHARED-EXPFULL: "{{.*}}ld{{(.exe)?}}"

Ditto.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119147

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


[PATCH] D124666: In MSVC compatibility mode, handle unqualified templated base class initialization

2022-05-03 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource updated this revision to Diff 426759.
frederic-tingaud-sonarsource added a comment.

Added two similar names in the tests, to try to trick the typo correction.


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

https://reviews.llvm.org/D124666

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaTemplate/ms-unqualified-base-class.cpp

Index: clang/test/SemaTemplate/ms-unqualified-base-class.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/ms-unqualified-base-class.cpp
@@ -0,0 +1,85 @@
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify=before,expected %s
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fdelayed-template-parsing -fsyntax-only -verify=before,expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=after,expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fdelayed-template-parsing -fsyntax-only -verify=after,expected %s
+
+template 
+class Base {
+};
+
+template 
+class Based {}; // Trying to trick the typo detection
+
+template 
+class Derived : public Base {
+public:
+  // after-error@+1 {{member initializer 'Base' does not name a non-static data member or base class}}
+  Derived() : Base() {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+private:
+  int Baze; // Trying to trick the typo detection
+};
+
+template  struct AggregateBase {
+  T i;
+};
+
+template 
+struct AggregateDerived : public AggregateBase {
+  int i;
+
+  // after-error@+1 {{member initializer 'AggregateBase' does not name a non-static data member or base class}}
+  AggregateDerived(T j) : AggregateBase{4}, i{j} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+  int f() {
+return i + AggregateBase::i; // expected-warning {{use of undeclared identifier 'AggregateBase'; unqualified lookup into dependent bases of class template 'AggregateDerived' is a Microsoft extension}}
+  }
+};
+
+template  struct MultiTypesBase {
+};
+
+template 
+struct MultiTypesDerived : public MultiTypesBase {
+  // after-error@+1 {{member initializer 'MultiTypesBase' does not name a non-static data member or base class}}
+  MultiTypesDerived() : MultiTypesBase{} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template  struct IntegerBase {
+};
+
+template 
+struct IntegerDerived : public IntegerBase {
+  // after-error@+1 {{member initializer 'IntegerBase' does not name a non-static data member or base class}}
+  IntegerDerived() : IntegerBase{} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template  struct ConformingBase {
+  T i;
+};
+
+template 
+struct ConformingDerived : public ConformingBase {
+  int i;
+
+  ConformingDerived(T j) : ConformingBase{4}, i{j} {}
+  int f() {
+return i + ConformingBase::i;
+  }
+};
+
+int main() {
+  int I;
+  Derived t;
+
+  AggregateDerived AD{2};
+  AD.AggregateBase::i = 3;
+  I = AD.f();
+
+  MultiTypesDerived MTD;
+
+  IntegerDerived<4> ID;
+
+  ConformingDerived CD{2};
+  I = CD.f();
+
+  return I;
+}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -4345,6 +4345,15 @@
 }
   }
 
+  if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
+auto UnqualifiedBase = R.getAsSingle();
+if (UnqualifiedBase) {
+  Diag(IdLoc, diag::ext_unqualified_base_class)
+  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
+  BaseType = UnqualifiedBase->getInjectedClassNameSpecialization();
+}
+  }
+
   if (!TyD && BaseType.isNull()) {
 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
   << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5508,6 +5508,9 @@
 def ext_found_later_in_class : ExtWarn<
   "use of member %0 before its declaration is a Microsoft extension">,
   InGroup;
+def ext_unqualified_base_class : ExtWarn<
+  "unqualified base initializer of class templates is a Microsoft extension">,
+  InGroup;
 def note_dependent_member_use : Note<
   "must qualify identifier to find this declaration in dependent base class">;
 def err_not_found_by_two_phase_lookup : Error<"call to function %0 that is neither "
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

2022-05-03 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added inline comments.



Comment at: clang/lib/Lex/PPDirectives.cpp:1356
+
+PP.Diag(FlagTok, diag::ext_pp_gnu_line_directive);
   } else if (FlagVal == 2) {

aaron.ballman wrote:
> ken-matsui wrote:
> > aaron.ballman wrote:
> > > ken-matsui wrote:
> > > > aaron.ballman wrote:
> > > > > I speculate that this change is wrong.
> > > > > 
> > > > > The goal here is to diagnose any time there's a GNU line marker and 
> > > > > now we're only trigging the diagnostic when the line marker's value 
> > > > > is 1; that misses diagnostics when the marker value is something else.
> > > > > 
> > > > > That's why I suggested warning each place we return `false` from this 
> > > > > function -- those are the situations when the line marker is 
> > > > > syntactically correct and we're going to make use of it in the 
> > > > > caller. (We don't want to warn about use of a line marker when we're 
> > > > > going to generate an error anyway.)
> > > > @aaron.ballman 
> > > > 
> > > > Thank you!
> > > > 
> > > > Just to confirm, do I need to remove the call of `Diag` after 
> > > > `GetLineValue` and put `Diag`s into all branches of returning `false` 
> > > > in this function?
> > > > If so, I think putting `Diag` after the call of this function would be 
> > > > better.
> > > > If so, I think putting Diag after the call of this function would be 
> > > > better.
> > > 
> > > You are correct and I agree, good suggestion!
> > @aaron.ballman 
> > Thank you for your response!
> > 
> > I've updated the code as mentioned, but a bunch of other tests with the 
> > `-pedantic` option failed as the following warnings:
> > 
> > ```
> >  TEST 'Clang :: CXX/expr/expr.const/p2-0x.cpp' FAILED 
> > 
> > Script:
> > --
> > : 'RUN: at line 1';   /tmp/llvm/llvm-project/build/bin/clang -cc1 
> > -internal-isystem /tmp/llvm/llvm-project/build/lib/clang/15.0.0/include 
> > -nostdsysteminc -fsyntax-only -std=c++11 -pedantic -verify=expected,cxx11 
> > -fcxx-exceptions 
> > /tmp/llvm/llvm-project/clang/test/CXX/expr/expr.const/p2-0x.cpp 
> > -fconstexpr-depth 128 -triple i686-pc-linux-gnu
> > : 'RUN: at line 2';   /tmp/llvm/llvm-project/build/bin/clang -cc1 
> > -internal-isystem /tmp/llvm/llvm-project/build/lib/clang/15.0.0/include 
> > -nostdsysteminc -fsyntax-only -std=c++2a -pedantic -verify=expected,cxx20 
> > -fcxx-exceptions 
> > /tmp/llvm/llvm-project/clang/test/CXX/expr/expr.const/p2-0x.cpp 
> > -fconstexpr-depth 128 -triple i686-pc-linux-gnu
> > --
> > Exit Code: 1
> > 
> > Command Output (stderr):
> > --
> > error: 'warning' diagnostics seen but not expected: 
> >   Line 0: this style of line directive is a GNU extension
> >   Line 0: this style of line directive is a GNU extension
> > 2 errors generated.
> > 
> > ...
> > ```
> > 
> > I personally think it would be preferable if the only change of tests would 
> > be `line-directive.c`.
> > So, how about reducing `Diag` calls until the warning doesn't spill over 
> > into other tests?
> > I personally think it would be preferable if the only change of tests would 
> > be line-directive.c.
> > So, how about reducing Diag calls until the warning doesn't spill over into 
> > other tests?
> 
> No, this is expected. We're adding a diagnostic where there wasn't one 
> previously, so some files are going to get caught by that. You can either add 
> the `// expected-warning {{}}` comments to those lines, or if the test has a 
> lot of those lines but isn't really specific to line markers (it just happens 
> to use them to test other functionality) you can disable the diagnostic for 
> that test with `-Wno-gnu-line-marker`.
Ah, I see. I'm going to work on it. Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D124211: Add __builtin_kcfi_call_unchecked

2022-05-03 Thread Sami Tolvanen via Phabricator via cfe-commits
samitolvanen abandoned this revision.
samitolvanen added a comment.

OK, I confirmed that we won't need this after all. I'll abandon this patch and 
revisit if it becomes necessary in future.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124211

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


[PATCH] D124736: [CodeGen] Use ABI alignment for placement new

2022-05-03 Thread Daniel Bertalan via Phabricator via cfe-commits
BertalanD added a comment.

In D124736#3485128 , @rjmccall wrote:

> It should probably be the ABI alignment in all cases; I think the preferred 
> alignment is just supposed to be used to opportunistically over-align things 
> like e.g. local variables, which doesn't seem relevant for the ABI code 
> involving a call to `operator new`.

Right, that makes sense. I'll update this patch tomorrow. Thanks for the review 
:)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124736

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


  1   2   >