[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-09 Thread via cfe-commits

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

LGTM, thanks!

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


[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread via cfe-commits

llvmbot wrote:

/pull-request llvm/llvm-project#91705

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


[clang] [Clang] Implement __reference_converts_from_temporary (PR #91199)

2024-05-09 Thread via cfe-commits

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


[clang] 2dbe89d - [Clang] Implement __reference_converts_from_temporary (#91199)

2024-05-09 Thread via cfe-commits

Author: cor3ntin
Date: 2024-05-10T08:50:44+02:00
New Revision: 2dbe89d15046bedcc36a5de1242e20aa91a5e598

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

LOG: [Clang] Implement __reference_converts_from_temporary (#91199)

This completes the required language support for P2255R2.

Added: 


Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/TokenKinds.def
clang/lib/Lex/PPMacroExpansion.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Parse/ParseExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/test/SemaCXX/type-traits.cpp
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 3627a780886a0..a09c409f8f91a 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1662,8 +1662,11 @@ The following type trait primitives are supported by 
Clang. Those traits marked
   ``T`` from ``U`` is ill-formed.
   Deprecated, use ``__reference_constructs_from_temporary``.
 * ``__reference_constructs_from_temporary(T, U)`` (C++)
-  Returns true if a reference ``T`` can be constructed from a temporary of type
+  Returns true if a reference ``T`` can be direct-initialized from a temporary 
of type
   a non-cv-qualified ``U``.
+* ``__reference_converts_from_temporary(T, U)`` (C++)
+Returns true if a reference ``T`` can be copy-initialized from a temporary 
of type
+a non-cv-qualified ``U``.
 * ``__underlying_type`` (C++, GNU, Microsoft)
 
 In addition, the following expression traits are supported:

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4547636318a74..eef627ff2e31f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -182,6 +182,9 @@ C++23 Feature Support
 
 - Implemented `P2448R2: Relaxing some constexpr restrictions 
`_.
 
+- Added a ``__reference_converts_from_temporary`` builtin, completing the 
necessary compiler support for
+  `P2255R2: Type trait to determine if a reference binds to a temporary 
`_.
+
 C++2c Feature Support
 ^
 

diff  --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index a27fbed358a60..56c4b17f769d7 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -537,6 +537,7 @@ TYPE_TRAIT_1(__is_referenceable, IsReferenceable, KEYCXX)
 TYPE_TRAIT_1(__can_pass_in_regs, CanPassInRegs, KEYCXX)
 TYPE_TRAIT_2(__reference_binds_to_temporary, ReferenceBindsToTemporary, KEYCXX)
 TYPE_TRAIT_2(__reference_constructs_from_temporary, 
ReferenceConstructsFromTemporary, KEYCXX)
+TYPE_TRAIT_2(__reference_converts_from_temporary, 
ReferenceConvertsFromTemporary, KEYCXX)
 
 // Embarcadero Expression Traits
 EXPRESSION_TRAIT(__is_lvalue_expr, IsLValueExpr, KEYCXX)

diff  --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index a5f22f01682d2..a478e0badb0c7 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -1714,8 +1714,6 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
   return llvm::StringSwitch(II->getName())
   .Case("__array_rank", true)
   .Case("__array_extent", true)
-  .Case("__reference_binds_to_temporary", true)
-  .Case("__reference_constructs_from_temporary", true)
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) .Case("__" #Trait, true)
 #include "clang/Basic/TransformTypeTraits.def"
   .Default(false);

diff  --git a/clang/lib/Parse/ParseDeclCXX.cpp 
b/clang/lib/Parse/ParseDeclCXX.cpp
index 8e0e868248293..96c9708c3711b 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -1779,9 +1779,8 @@ void Parser::ParseClassSpecifier(tok::TokenKind 
TagTokKind,
   tok::kw___is_union,
   tok::kw___is_unsigned,
   tok::kw___is_void,
-  tok::kw___is_volatile,
-  tok::kw___reference_binds_to_temporary,
-  tok::kw___reference_constructs_from_temporary))
+  tok::kw___is_volatile
+  ))
 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
 // name of struct templates, but some are keywords in GCC >= 4.3
 // and Clang. Therefore, when we see the token sequence "struct

diff  --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 5f5f9a79c8c40..0551b8314f9f6 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -1166,7 +1166,6 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
   REVERTIBLE_TYPE_TRAIT(__is_void);
   REVERTIBLE_TYPE_TRAIT(__is_volatile);

[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread Phoebe Wang via cfe-commits

phoebewang wrote:

/cherry-pick 
https://github.com/llvm/llvm-project/commit/87f3407856e61a73798af4e41b28bc33b5bf4ce6

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


[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread Phoebe Wang via cfe-commits

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


[clang] [llvm] [MC,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)

2024-05-09 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/91280

>From a0cfafb82db825512b0ca44778fa9d4bb435563d Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Mon, 6 May 2024 15:37:50 -0700
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.5-bogner
---
 clang/include/clang/Basic/CodeGenOptions.def  |   1 +
 .../clang/Basic/DiagnosticDriverKinds.td  |   3 +
 clang/include/clang/Driver/Options.td |   3 +
 clang/lib/CodeGen/BackendUtil.cpp |   1 +
 clang/lib/Driver/ToolChains/Clang.cpp |  18 ++
 clang/lib/Driver/ToolChains/CommonArgs.cpp|  21 ++
 clang/test/Driver/crel.c  |  24 +++
 clang/test/Misc/cc1as-crel.s  |   6 +
 clang/tools/driver/cc1as_main.cpp |   6 +
 .../include/llvm/BinaryFormat/DynamicTags.def |   2 +
 llvm/include/llvm/BinaryFormat/ELF.h  |   1 +
 llvm/include/llvm/MC/MCTargetOptions.h|   3 +
 .../llvm/MC/MCTargetOptionsCommandFlags.h |   1 +
 llvm/include/llvm/Object/ELF.h|   5 +
 llvm/include/llvm/Object/ELFObjectFile.h  |  70 ++-
 llvm/include/llvm/Object/ELFTypes.h   |  25 +++
 llvm/lib/MC/ELFObjectWriter.cpp   | 110 ---
 llvm/lib/MC/MCTargetOptionsCommandFlags.cpp   |   6 +
 llvm/lib/Object/ELF.cpp   |  63 ++
 llvm/lib/ObjectYAML/ELFEmitter.cpp|  60 +-
 llvm/lib/ObjectYAML/ELFYAML.cpp   |   2 +
 llvm/test/MC/ELF/crel-32.s|  16 ++
 llvm/test/MC/ELF/crel.s   | 100 ++
 llvm/test/tools/llvm-readobj/ELF/crel.test| 180 ++
 .../tools/llvm-readobj/ELF/dynamic-reloc.test |  31 ++-
 .../llvm-readobj/ELF/relocation-errors.test   |  19 +-
 .../yaml2obj/ELF/dynamic-relocations.yaml |   5 +-
 .../yaml2obj/ELF/reloc-sec-entry-size.yaml|   5 +
 .../tools/yaml2obj/ELF/relocation-crel.yaml   |  63 ++
 .../ELF/relocation-missing-symbol.yaml|   3 +-
 .../tools/yaml2obj/ELF/relocation-type.yaml   |   4 +-
 llvm/tools/llvm-readobj/ELFDumper.cpp |  81 +++-
 32 files changed, 883 insertions(+), 55 deletions(-)
 create mode 100644 clang/test/Driver/crel.c
 create mode 100644 clang/test/Misc/cc1as-crel.s
 create mode 100644 llvm/test/MC/ELF/crel-32.s
 create mode 100644 llvm/test/MC/ELF/crel.s
 create mode 100644 llvm/test/tools/llvm-readobj/ELF/crel.test
 create mode 100644 llvm/test/tools/yaml2obj/ELF/relocation-crel.yaml

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 340b08dd7e2a3..3229f77eef1fc 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -36,6 +36,7 @@ VALUE_CODEGENOPT(Name, Bits, Default)
 #endif
 
 CODEGENOPT(DisableIntegratedAS, 1, 0) ///< -no-integrated-as
+CODEGENOPT(Crel, 1, 0) ///< -Wa,--crel
 CODEGENOPT(RelaxELFRelocations, 1, 1) ///< -Wa,-mrelax-relocations={yes,no}
 CODEGENOPT(AsmVerbose, 1, 0) ///< -dA, -fverbose-asm.
 CODEGENOPT(PreserveAsmComments, 1, 1) ///< -dA, -fno-preserve-as-comments.
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 9781fcaa4ff5e..e9cea8967c133 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -809,6 +809,9 @@ def warn_drv_missing_multilib : Warning<
 def note_drv_available_multilibs : Note<
   "available multilibs are:%0">;
 
+def err_drv_experimental_crel : Error<
+  "-Wa,--experimental-crel must be specified to use -Wa,--crel. CREL is 
experimental and takes a non-standard section type code">;
+
 def warn_android_unversioned_fallback : Warning<
   "Using unversioned Android target directory %0 for target %1. Unversioned"
   " directories will not be used in Clang 19. Provide a versioned directory"
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c9f7c4e5f718b..55f0c9aff6a49 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6958,6 +6958,9 @@ def massembler_no_warn : Flag<["-"], 
"massembler-no-warn">,
 def massembler_fatal_warnings : Flag<["-"], "massembler-fatal-warnings">,
   HelpText<"Make assembler warnings fatal">,
   MarshallingInfoFlag>;
+def crel : Flag<["--"], "crel">,
+  HelpText<"Enable CREL relocation format (ELF only)">,
+  MarshallingInfoFlag>;
 def mrelax_relocations_no : Flag<["-"], "mrelax-relocations=no">,
 HelpText<"Disable x86 relax relocations">,
 MarshallingInfoNegativeFlag>;
diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 22c3f8642ad8e..ed37085d69ac5 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil

[clang] [llvm] [MC,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)

2024-05-09 Thread Fangrui Song via cfe-commits


@@ -1142,6 +1193,13 @@ ELFObjectFile::getRela(DataRefImpl Rela) const {
   return *Ret;
 }
 
+template 

MaskRay wrote:

Changes to this file are for llvm-objdump support. The use patterns ensure that 
`Crels` will be populated.

I've added the assert to https://github.com/MaskRay/llvm-project/tree/demo-crel 

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


[clang] [llvm] [MC,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)

2024-05-09 Thread Fangrui Song via cfe-commits


@@ -292,6 +293,9 @@ template  class ELFObjectFile : public 
ELFObjectFileBase {
   const Elf_Shdr *DotSymtabSec = nullptr; // Symbol table section.
   const Elf_Shdr *DotSymtabShndxSec = nullptr; // SHT_SYMTAB_SHNDX section.
 
+  // Hold CREL relocations for SectionRef::relocations().
+  mutable SmallVector, 0> Crels;

MaskRay wrote:

To the best of my knowledge, ELFObjectFile is not used by multi-threading. The 
`mutable` member is not nice, which is to comply with the interface requirement 
by `llvm-objdump -r/-R`.

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


[clang] [llvm] [MC,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)

2024-05-09 Thread Fangrui Song via cfe-commits


@@ -446,6 +450,7 @@ template  class ELFObjectFile : public 
ELFObjectFileBase {
 
   const Elf_Rel *getRel(DataRefImpl Rel) const;
   const Elf_Rela *getRela(DataRefImpl Rela) const;
+  Elf_Crel getCrel(DataRefImpl Rel) const;

MaskRay wrote:

renamed

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


[clang] [llvm] [MC,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)

2024-05-09 Thread Fangrui Song via cfe-commits


@@ -321,6 +321,11 @@ class ELFFile {
 
   std::vector decode_relrs(Elf_Relr_Range relrs) const;
 
+  uint64_t crelHeader(ArrayRef Content) const;
+  using RelsOrRelas = std::pair, std::vector>;

MaskRay wrote:

Yes, `std::pair<` instead of an exclusive or is for convenience.

This is a type alias in a class (ELFFile) used by llvm-readobj. lld/ELF doesn't 
use this class, and the name collision should be fine.

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


[clang] [llvm] [MC,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)

2024-05-09 Thread Fangrui Song via cfe-commits


@@ -1117,9 +1166,11 @@ void ELFObjectFile::getRelocationTypeName(
 template 
 Expected
 ELFObjectFile::getRelocationAddend(DataRefImpl Rel) const {
-  if (getRelSection(Rel)->sh_type != ELF::SHT_RELA)
-return createError("Section is not SHT_RELA");
-  return (int64_t)getRela(Rel)->r_addend;
+  if (getRelSection(Rel)->sh_type == ELF::SHT_RELA)
+return (int64_t)getRela(Rel)->r_addend;
+  if (getRelSection(Rel)->sh_type == ELF::SHT_CREL)

MaskRay wrote:

I have reverted this file. Sorry for leaving it in the initial patch.

This code is used by `.getAddend()` in the files (not core binary utilities).

* llvm/lib/Object/RelocationResolver.cpp
* llvm/lib/XRay/InstrumentationMap.cpp
* llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp

Since they are all for static relocations, we can assume `r_addend`.
However, I agree that having an error checking would be nice.


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


[clang] [lld] [llvm] [RISCV] Support .note.gnu.property for enable Zicfiss and Zicfilp extension (PR #77414)

2024-05-09 Thread via cfe-commits

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


[clang] [lld] [llvm] [RISCV] Support .note.gnu.property for enable Zicfiss and Zicfilp extension (PR #77414)

2024-05-09 Thread via cfe-commits

SuHo-llrr wrote:

@yetingk 
I have updated to the latest version. If you have any suggestions, please let 
me know.






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


[clang] [lld] [llvm] [RISCV] Support .note.gnu.property for enable Zicfiss and Zicfilp extension (PR #77414)

2024-05-09 Thread via cfe-commits

https://github.com/SuHo-llrr updated 
https://github.com/llvm/llvm-project/pull/77414

>From 61aaf8df2fbd0abfa4dfcd807f3366ce67f5603d Mon Sep 17 00:00:00 2001
From: SuHsien Ho 
Date: Thu, 23 Nov 2023 14:36:43 +0800
Subject: [PATCH 1/5] [RISCV][ELF] Add RISCV GNU property label

---
 llvm/include/llvm/BinaryFormat/ELF.h | 7 +++
 1 file changed, 7 insertions(+)

diff --git a/llvm/include/llvm/BinaryFormat/ELF.h 
b/llvm/include/llvm/BinaryFormat/ELF.h
index f296acc2ca4bb..c8da286fc9588 100644
--- a/llvm/include/llvm/BinaryFormat/ELF.h
+++ b/llvm/include/llvm/BinaryFormat/ELF.h
@@ -1737,6 +1737,7 @@ enum : unsigned {
   GNU_PROPERTY_AARCH64_FEATURE_1_AND = 0xc000,
   GNU_PROPERTY_AARCH64_FEATURE_PAUTH = 0xc001,
   GNU_PROPERTY_X86_FEATURE_1_AND = 0xc002,
+  GNU_PROPERTY_RISCV_FEATURE_1_AND = 0xc000,
 
   GNU_PROPERTY_X86_UINT32_OR_LO = 0xc0008000,
   GNU_PROPERTY_X86_FEATURE_2_NEEDED = GNU_PROPERTY_X86_UINT32_OR_LO + 1,
@@ -1796,6 +1797,12 @@ enum : unsigned {
   GNU_PROPERTY_X86_ISA_1_V4 = 1 << 3,
 };
 
+// riscv processor feature bits.
+enum : unsigned {
+  GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_SIMPLE = 1 << 0,
+  GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS = 1 << 1,
+};
+
 // FreeBSD note types.
 enum {
   NT_FREEBSD_ABI_TAG = 1,

>From 40b81f066e9a7c1789e4c0c1e92715a0569a77eb Mon Sep 17 00:00:00 2001
From: SuHsien Ho 
Date: Thu, 23 Nov 2023 14:38:34 +0800
Subject: [PATCH 2/5] [RISCV][ELF] Emit .gnu.note.property for
 Zicfiss/Zicfilip(CFI extension)

---
 .../RISCV/MCTargetDesc/RISCVELFStreamer.cpp   | 42 +++
 .../RISCV/MCTargetDesc/RISCVELFStreamer.h |  1 +
 .../MCTargetDesc/RISCVTargetStreamer.cpp  |  2 +
 .../RISCV/MCTargetDesc/RISCVTargetStreamer.h  |  4 ++
 4 files changed, 49 insertions(+)

diff --git a/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.cpp 
b/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.cpp
index ae7ce476fff22..7164a191bd41f 100644
--- a/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.cpp
+++ b/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.cpp
@@ -85,6 +85,35 @@ void RISCVTargetELFStreamer::finishAttributeSection() {
   ELF::SHT_RISCV_ATTRIBUTES, AttributeSection);
 }
 
+void RISCVTargetELFStreamer::emitNoteSection(unsigned Flags) {
+  if (Flags == 0)
+return;
+
+  MCStreamer &OutStreamer = getStreamer();
+  MCContext &Context = OutStreamer.getContext();
+  MCSectionELF *Nt = Context.getELFSection(".note.gnu.property", ELF::SHT_NOTE,
+   ELF::SHF_ALLOC);
+  MCSection *Cur = OutStreamer.getCurrentSectionOnly();
+  OutStreamer.switchSection(Nt);
+
+  // Emit the note header.
+  OutStreamer.emitValueToAlignment(Align(8));
+  OutStreamer.emitIntValue(4, 4); // data size for note name
+  OutStreamer.emitIntValue(4 * 4, 4); // data size
+  OutStreamer.emitIntValue(ELF::NT_GNU_PROPERTY_TYPE_0, 4); // note type
+  OutStreamer.emitBytes(StringRef("GNU", 4));   // note name
+
+  // Emit the CFI(ZICFILP/ZICFISS) properties.
+  OutStreamer.emitIntValue(ELF::GNU_PROPERTY_RISCV_FEATURE_1_AND,
+   4);// and property
+  OutStreamer.emitIntValue(4, 4); // data size
+  OutStreamer.emitIntValue(Flags, 4); // data
+  OutStreamer.emitIntValue(0, 4); // pad
+
+  OutStreamer.endSection(Nt);
+  OutStreamer.switchSection(Cur);
+}
+
 void RISCVTargetELFStreamer::finish() {
   RISCVTargetStreamer::finish();
   MCAssembler &MCA = getStreamer().getAssembler();
@@ -118,6 +147,19 @@ void RISCVTargetELFStreamer::finish() {
   }
 
   MCA.setELFHeaderEFlags(EFlags);
+
+  unsigned GNUNoteFlags = 0;
+
+  // check ZICFILP or ZICFISS with features
+  // TODO should we check with codegen enable ex. -mllvm
+  // -riscv-hardware-shadow-stack=true ?
+  if (hasZICFILP())
+GNUNoteFlags |= ELF::GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_SIMPLE;
+
+  if (hasZICFISS())
+GNUNoteFlags |= ELF::GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS;
+
+  emitNoteSection(GNUNoteFlags);
 }
 
 void RISCVTargetELFStreamer::reset() {
diff --git a/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.h 
b/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.h
index 212d731889f1a..06ee170500c59 100644
--- a/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.h
+++ b/llvm/lib/Target/RISCV/MCTargetDesc/RISCVELFStreamer.h
@@ -70,6 +70,7 @@ class RISCVTargetELFStreamer : public RISCVTargetStreamer {
   void emitDirectiveVariantCC(MCSymbol &Symbol) override;
 
   void finish() override;
+  void emitNoteSection(unsigned Flags);
 };
 
 MCELFStreamer *createRISCVELFStreamer(MCContext &C,
diff --git a/llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.cpp 
b/llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.cpp
index 0f92e9ed6a64d..9f142b4d25463 100644
--- a/llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.cpp
+++ b/llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.cpp
@@ -52,6 +52,8 @@ void RISCVTargetStreamer::setFlagsFromFeatures(const 
MCSubtargetInfo &STI) {
   HasRVC = S

[clang] 135d92f - [Driver] Use StringRef::operator== instead of StringRef::equals (NFC) (#91698)

2024-05-09 Thread via cfe-commits

Author: Kazu Hirata
Date: 2024-05-09T23:12:08-07:00
New Revision: 135d92f903161e66ff82ab846acfbc5015ef3096

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

LOG: [Driver] Use StringRef::operator== instead of StringRef::equals (NFC) 
(#91698)

I'm planning to remove StringRef::equals in favor of
StringRef::operator==.

- StringRef::operator==/!= outnumber StringRef::equals by a factor of
  13 under clang/ in terms of their usage.

- The elimination of StringRef::equals brings StringRef closer to
  std::string_view, which has operator== but not equals.

- S == "foo" is more readable than S.equals("foo"), especially for
  !Long.Expression.equals("str") vs Long.Expression != "str".

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/AIX.cpp
clang/lib/Driver/ToolChains/AMDGPU.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Driver/ToolChains/Flang.cpp

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 114320f5d3146..7b36d8e5084cf 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -564,9 +564,9 @@ static llvm::Triple computeTargetTriple(const Driver &D,
   StringRef ObjectMode = *ObjectModeValue;
   llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
 
-  if (ObjectMode.equals("64")) {
+  if (ObjectMode == "64") {
 AT = Target.get64BitArchVariant().getArch();
-  } else if (ObjectMode.equals("32")) {
+  } else if (ObjectMode == "32") {
 AT = Target.get32BitArchVariant().getArch();
   } else {
 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
@@ -6694,7 +6694,7 @@ llvm::StringRef clang::driver::getDriverMode(StringRef 
ProgName,
   return Opt.consume_front(OptName) ? Opt : "";
 }
 
-bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); 
}
+bool driver::IsClangCL(StringRef DriverMode) { return DriverMode == "cl"; }
 
 llvm::Error driver::expandResponseFiles(SmallVectorImpl &Args,
 bool ClangCLMode,

diff  --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index aab98506adb96..85825e1ea65b1 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -481,8 +481,8 @@ static void addTocDataOptions(const llvm::opt::ArgList 
&Args,
 
   // Currently only supported for small code model.
   if (TOCDataGloballyinEffect &&
-  (Args.getLastArgValue(options::OPT_mcmodel_EQ).equals("large") ||
-   Args.getLastArgValue(options::OPT_mcmodel_EQ).equals("medium"))) {
+  (Args.getLastArgValue(options::OPT_mcmodel_EQ) == "large" ||
+   Args.getLastArgValue(options::OPT_mcmodel_EQ) == "medium")) {
 D.Diag(clang::diag::warn_drv_unsupported_tocdata);
 return;
   }

diff  --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 07965b487ea79..9ffea57b005de 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -732,7 +732,7 @@ AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, 
StringRef BoundArch,
 
   checkTargetID(*DAL);
 
-  if (!Args.getLastArgValue(options::OPT_x).equals("cl"))
+  if (Args.getLastArgValue(options::OPT_x) != "cl")
 return DAL;
 
   // Phase 1 (.cl -> .bc)

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 775dc24e1..449eb9b2a965a 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1526,7 +1526,7 @@ static void CollectARMPACBTIOptions(const ToolChain &TC, 
const ArgList &Args,
 
   CmdArgs.push_back(
   Args.MakeArgString(Twine("-msign-return-address=") + Scope));
-  if (!Scope.equals("none"))
+  if (Scope != "none")
 CmdArgs.push_back(
 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
   if (BranchProtectionPAuthLR)
@@ -1719,10 +1719,9 @@ void Clang::AddAArch64TargetArgs(const ArgList &Args,
   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
 StringRef Val = A->getValue();
 const Driver &D = getToolChain().getDriver();
-if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
-Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
-Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
-Val.equals("2048+")) {
+if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
+Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
+Val == "1024+" || Val == "2048+") {
   unsigned Bits = 0;
   if (!Val.consume_back("+")) {
 bool Invalid = Val.getAsInteger(10, 

[clang] [Driver] Use StringRef::operator== instead of StringRef::equals (NFC) (PR #91698)

2024-05-09 Thread Kazu Hirata via cfe-commits

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


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

2024-05-09 Thread NAKAMURA Takumi via cfe-commits


@@ -190,18 +190,30 @@ class SourceMappingRegion {
 
   bool isBranch() const { return FalseCount.has_value(); }
 
+  bool isMCDCBranch() const {
+const auto *BranchParams = 
std::get_if(&MCDCParams);
+assert(BranchParams == nullptr || BranchParams->ID >= 0);

chapuni wrote:

I've removed the assertion. (I will commit other changes in BranchParams and 
DecisionParams later)

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


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

2024-05-09 Thread NAKAMURA Takumi via cfe-commits


@@ -1128,9 +1122,11 @@ void CodeGenPGO::emitMCDCParameters(CGBuilderTy 
&Builder) {
   // Emit intrinsic representing MCDC bitmap parameters at function entry.
   // This is used by the instrumentation pass, but it isn't actually lowered to
   // anything.
-  llvm::Value *Args[3] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
-  Builder.getInt64(FunctionHash),
-  Builder.getInt32(RegionMCDCState->BitmapBytes)};
+  llvm::Value *Args[3] = {
+  llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
+  Builder.getInt64(FunctionHash),
+  Builder.getInt32(llvm::alignTo(RegionMCDCState->BitmapBits, CHAR_BIT) /
+   CHAR_BIT)};

chapuni wrote:

Modified 3rd arg of `mcdc.parameters` as bitcnt.

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


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

2024-05-09 Thread NAKAMURA Takumi via cfe-commits


@@ -2050,23 +2069,74 @@ struct CounterCoverageMappingBuilder
  subtractCounters(ParentCount, TrueCount));
   }
 
-  void createDecision(const BinaryOperator *E) {
+  void createOrCancelDecision(const BinaryOperator *E, unsigned Since) {
 unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(E);
 if (NumConds == 0)
   return;
 
+// Extract [ID, Conds] to construct the graph.
+llvm::SmallVector CondIDs(NumConds);
+for (const auto &SR : ArrayRef(SourceRegions).slice(Since)) {
+  if (SR.isMCDCBranch()) {

chapuni wrote:

I think `make_filter_range` is less suitable here.

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


[clang] [flang] [flang] Add nsw flag to do-variable increment with a new option (PR #91579)

2024-05-09 Thread Yusuke MINATO via cfe-commits

https://github.com/yus3710-fj updated 
https://github.com/llvm/llvm-project/pull/91579

>From f51cfbe1e50c7a1aa902c684f12a20d0fac39c21 Mon Sep 17 00:00:00 2001
From: Yusuke MINATO 
Date: Wed, 24 Apr 2024 14:42:21 +0900
Subject: [PATCH 1/2] [flang] Add nsw flag to do-variable increment with a new
 option

This patch adds nsw flag to the increment of do-variables when
a new option is enabled.
NOTE 11.10 in the Fortran 2018 standard says they never overflow.

See also the discussion in 74709 and
discourse post.
---
 clang/include/clang/Driver/Options.td |   4 +
 clang/lib/Driver/ToolChains/Flang.cpp |   1 +
 flang/include/flang/Lower/LoweringOptions.def |   4 +
 .../flang/Optimizer/Transforms/Passes.h   |   4 +-
 .../flang/Optimizer/Transforms/Passes.td  |   5 +-
 flang/include/flang/Tools/CLOptions.inc   |  13 +-
 flang/include/flang/Tools/CrossToolHelpers.h  |   1 +
 flang/lib/Frontend/CompilerInvocation.cpp |   6 +
 flang/lib/Frontend/FrontendActions.cpp|   3 +
 flang/lib/Lower/Bridge.cpp|  12 +-
 flang/lib/Lower/IO.cpp|   9 +-
 .../Transforms/ControlFlowConverter.cpp   |  44 +++-
 flang/test/Driver/frontend-forwarding.f90 |   2 +
 flang/test/Fir/loop01.fir | 211 ++
 flang/test/Lower/array-substring.f90  |  40 
 flang/test/Lower/do_loop.f90  |  42 
 flang/test/Lower/do_loop_unstructured.f90 | 189 +++-
 flang/test/Lower/infinite_loop.f90|  34 +++
 flang/test/Lower/io-implied-do-fixes.f90  |  51 -
 flang/tools/bbc/bbc.cpp   |   7 +
 20 files changed, 659 insertions(+), 23 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 1429528975853..0d032076f7163 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6539,6 +6539,10 @@ def flang_deprecated_no_hlfir : Flag<["-"], 
"flang-deprecated-no-hlfir">,
   Flags<[HelpHidden]>, Visibility<[FlangOption, FC1Option]>,
   HelpText<"Do not use HLFIR lowering (deprecated)">;
 
+def flang_experimental_integer_overflow : Flag<["-"], 
"flang-experimental-integer-overflow">,
+  Flags<[HelpHidden]>, Visibility<[FlangOption, FC1Option]>,
+  HelpText<"Add nsw flag to internal operations such as do-variable increment 
(experimental)">;
+
 
//===--===//
 // FLangOption + CoreOption + NoXarchOption
 
//===--===//
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 436a9c418a5f9..0ae489a823078 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -139,6 +139,7 @@ void Flang::addCodegenOptions(const ArgList &Args,
 
   Args.addAllArgs(CmdArgs, {options::OPT_flang_experimental_hlfir,
 options::OPT_flang_deprecated_no_hlfir,
+options::OPT_flang_experimental_integer_overflow,
 options::OPT_fno_ppc_native_vec_elem_order,
 options::OPT_fppc_native_vec_elem_order});
 }
diff --git a/flang/include/flang/Lower/LoweringOptions.def 
b/flang/include/flang/Lower/LoweringOptions.def
index be080a4d29d73..839d2b46249b0 100644
--- a/flang/include/flang/Lower/LoweringOptions.def
+++ b/flang/include/flang/Lower/LoweringOptions.def
@@ -34,5 +34,9 @@ ENUM_LOWERINGOPT(NoPPCNativeVecElemOrder, unsigned, 1, 0)
 /// On by default.
 ENUM_LOWERINGOPT(Underscoring, unsigned, 1, 1)
 
+/// If true, add nsw flags to arithmetic operations for integer.
+/// Off by default.
+ENUM_LOWERINGOPT(NoSignedWrap, unsigned, 1, 0)
+
 #undef LOWERINGOPT
 #undef ENUM_LOWERINGOPT
diff --git a/flang/include/flang/Optimizer/Transforms/Passes.h 
b/flang/include/flang/Optimizer/Transforms/Passes.h
index 470ed8a125ac4..496201a04e29c 100644
--- a/flang/include/flang/Optimizer/Transforms/Passes.h
+++ b/flang/include/flang/Optimizer/Transforms/Passes.h
@@ -54,6 +54,7 @@ namespace fir {
 std::unique_ptr createAffineDemotionPass();
 std::unique_ptr
 createArrayValueCopyPass(fir::ArrayValueCopyOptions options = {});
+std::unique_ptr createCFGConversionPassWithNSW();
 std::unique_ptr createExternalNameConversionPass();
 std::unique_ptr
 createExternalNameConversionPass(bool appendUnderscore);
@@ -89,7 +90,8 @@ createFunctionAttrPass(FunctionAttrTypes &functionAttr, bool 
noInfsFPMath,
bool noSignedZerosFPMath, bool unsafeFPMath);
 
 void populateCfgConversionRewrites(mlir::RewritePatternSet &patterns,
-   bool forceLoopToExecuteOnce = false);
+   bool forceLoopToExecuteOnce = false,
+   bool setNSW = false);
 
 // declarative passes
 #define GEN_PASS_REGISTRATION
diff --git a/

[clang] [flang] [flang] Add nsw flag to do-variable increment with a new option (PR #91579)

2024-05-09 Thread Yusuke MINATO via cfe-commits

yus3710-fj wrote:

Windows build failed with the following message.

> fatal error C1060: compiler is out of heap space

I'll try re-running CI with an empty commit because it might have been happend 
by accident.


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


[clang] [Driver] Use StringRef::operator== instead of StringRef::equals (NFC) (PR #91698)

2024-05-09 Thread Fangrui Song via cfe-commits

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


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


[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread Phoebe Wang via cfe-commits

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


[clang] [AArch64] add some more tests for FMV (PR #91490)

2024-05-09 Thread Vladimir Vereschaka via cfe-commits

vvereschaka wrote:

@tmatheson-arm 
broken builder
* https://lab.llvm.org/buildbot/#/builders/119/builds/18102
* https://lab.llvm.org/buildbot/#/builders/60/builds/17123

would you take care of it or revert the changes?

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


[clang] Enable unguarded availability diagnostic on instantiated template functions (PR #91699)

2024-05-09 Thread Helena Kotas via cfe-commits

https://github.com/hekota created 
https://github.com/llvm/llvm-project/pull/91699

None

>From 6220a5f61f92c3161772fd7c2be9d387169f8e03 Mon Sep 17 00:00:00 2001
From: Helena Kotas 
Date: Thu, 9 May 2024 22:14:05 -0700
Subject: [PATCH] Enable unguarded availability diagnostic on instantiated
 template functions

---
 clang/lib/Sema/SemaAvailability.cpp  |  5 -
 clang/test/SemaObjC/unguarded-availability.m | 11 +++
 2 files changed, 7 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Sema/SemaAvailability.cpp 
b/clang/lib/Sema/SemaAvailability.cpp
index 846a31a796730..5b0f34d1aa3aa 100644
--- a/clang/lib/Sema/SemaAvailability.cpp
+++ b/clang/lib/Sema/SemaAvailability.cpp
@@ -928,11 +928,6 @@ void Sema::DiagnoseUnguardedAvailabilityViolations(Decl 
*D) {
   Stmt *Body = nullptr;
 
   if (auto *FD = D->getAsFunction()) {
-// FIXME: We only examine the pattern decl for availability violations now,
-// but we should also examine instantiated templates.
-if (FD->isTemplateInstantiation())
-  return;
-
 Body = FD->getBody();
 
 if (auto *CD = dyn_cast(FD))
diff --git a/clang/test/SemaObjC/unguarded-availability.m 
b/clang/test/SemaObjC/unguarded-availability.m
index d0e23eabcb598..3a38c3b40c4d6 100644
--- a/clang/test/SemaObjC/unguarded-availability.m
+++ b/clang/test/SemaObjC/unguarded-availability.m
@@ -177,16 +177,19 @@ void justAtAvailable(void) {
 
 #ifdef OBJCPP
 
-int f(char) AVAILABLE_10_12;
+int f(char) AVAILABLE_10_12; // #f_char_def
 int f(int);
 
 template  int use_f() {
-  // FIXME: We should warn here!
-  return f(T());
+  // expected-warning@#f_call {{'f' is only available on macOS 10.12 or newer}}
+  // expected-note@#f_char_inst {{in instantiation of function template 
specialization 'use_f' requested here}}
+  // expected-note@#f_char_def {{'f' has been marked as being introduced in 
macOS 10.12 here, but the deployment target is macOS 10.9}}
+  // expected-note@#f_call {{enclose 'f' in an @available check to silence 
this warning}}
+  return f(T()); // #f_call
 }
 
 int a = use_f();
-int b = use_f();
+int b = use_f(); // #f_char_inst
 
 template  int use_at_available() {
   if (@available(macos 10.12, *))

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


[clang] [Driver] Use StringRef::operator== instead of StringRef::equals (NFC) (PR #91698)

2024-05-09 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-amdgpu
@llvm/pr-subscribers-clang-driver

@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes

I'm planning to remove StringRef::equals in favor of
StringRef::operator==.

- StringRef::operator==/!= outnumber StringRef::equals by a factor of
  13 under clang/ in terms of their usage.

- The elimination of StringRef::equals brings StringRef closer to
  std::string_view, which has operator== but not equals.

- S == "foo" is more readable than S.equals("foo"), especially for
  !Long.Expression.equals("str") vs Long.Expression != "str".

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


6 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+3-3) 
- (modified) clang/lib/Driver/ToolChains/AIX.cpp (+2-2) 
- (modified) clang/lib/Driver/ToolChains/AMDGPU.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+32-34) 
- (modified) clang/lib/Driver/ToolChains/CommonArgs.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChains/Flang.cpp (+6-7) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 114320f5d3146..7b36d8e5084cf 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -564,9 +564,9 @@ static llvm::Triple computeTargetTriple(const Driver &D,
   StringRef ObjectMode = *ObjectModeValue;
   llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
 
-  if (ObjectMode.equals("64")) {
+  if (ObjectMode == "64") {
 AT = Target.get64BitArchVariant().getArch();
-  } else if (ObjectMode.equals("32")) {
+  } else if (ObjectMode == "32") {
 AT = Target.get32BitArchVariant().getArch();
   } else {
 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
@@ -6694,7 +6694,7 @@ llvm::StringRef clang::driver::getDriverMode(StringRef 
ProgName,
   return Opt.consume_front(OptName) ? Opt : "";
 }
 
-bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); 
}
+bool driver::IsClangCL(StringRef DriverMode) { return DriverMode == "cl"; }
 
 llvm::Error driver::expandResponseFiles(SmallVectorImpl &Args,
 bool ClangCLMode,
diff --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index aab98506adb96..85825e1ea65b1 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -481,8 +481,8 @@ static void addTocDataOptions(const llvm::opt::ArgList 
&Args,
 
   // Currently only supported for small code model.
   if (TOCDataGloballyinEffect &&
-  (Args.getLastArgValue(options::OPT_mcmodel_EQ).equals("large") ||
-   Args.getLastArgValue(options::OPT_mcmodel_EQ).equals("medium"))) {
+  (Args.getLastArgValue(options::OPT_mcmodel_EQ) == "large" ||
+   Args.getLastArgValue(options::OPT_mcmodel_EQ) == "medium")) {
 D.Diag(clang::diag::warn_drv_unsupported_tocdata);
 return;
   }
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 07965b487ea79..9ffea57b005de 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -732,7 +732,7 @@ AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, 
StringRef BoundArch,
 
   checkTargetID(*DAL);
 
-  if (!Args.getLastArgValue(options::OPT_x).equals("cl"))
+  if (Args.getLastArgValue(options::OPT_x) != "cl")
 return DAL;
 
   // Phase 1 (.cl -> .bc)
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 775dc24e1..449eb9b2a965a 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1526,7 +1526,7 @@ static void CollectARMPACBTIOptions(const ToolChain &TC, 
const ArgList &Args,
 
   CmdArgs.push_back(
   Args.MakeArgString(Twine("-msign-return-address=") + Scope));
-  if (!Scope.equals("none"))
+  if (Scope != "none")
 CmdArgs.push_back(
 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
   if (BranchProtectionPAuthLR)
@@ -1719,10 +1719,9 @@ void Clang::AddAArch64TargetArgs(const ArgList &Args,
   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
 StringRef Val = A->getValue();
 const Driver &D = getToolChain().getDriver();
-if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
-Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
-Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
-Val.equals("2048+")) {
+if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
+Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
+Val == "1024+" || Val == "2048+") {
   unsigned Bits = 0;
   if (!Val.consume_back("+")) {
 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
@@ -1736,7 +1735,7 @@ void Clang::AddAArch64TargetArgs(const ArgList &Args,
   CmdArgs.push_back(
   Args

[clang] [Driver] Use StringRef::operator== instead of StringRef::equals (NFC) (PR #91698)

2024-05-09 Thread Kazu Hirata via cfe-commits

https://github.com/kazutakahirata created 
https://github.com/llvm/llvm-project/pull/91698

I'm planning to remove StringRef::equals in favor of
StringRef::operator==.

- StringRef::operator==/!= outnumber StringRef::equals by a factor of
  13 under clang/ in terms of their usage.

- The elimination of StringRef::equals brings StringRef closer to
  std::string_view, which has operator== but not equals.

- S == "foo" is more readable than S.equals("foo"), especially for
  !Long.Expression.equals("str") vs Long.Expression != "str".

>From 5a5154a06a8df048b0edc0d6413c28c565de0867 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Thu, 9 May 2024 00:51:45 -0700
Subject: [PATCH] [Driver] Use StringRef::operator== instead of
 StringRef::equals (NFC)

I'm planning to remove StringRef::equals in favor of
StringRef::operator==.

- StringRef::operator==/!= outnumber StringRef::equals by a factor of
  13 under clang/ in terms of their usage.

- The elimination of StringRef::equals brings StringRef closer to
  std::string_view, which has operator== but not equals.

- S == "foo" is more readable than S.equals("foo"), especially for
  !Long.Expression.equals("str") vs Long.Expression != "str".
---
 clang/lib/Driver/Driver.cpp|  6 +-
 clang/lib/Driver/ToolChains/AIX.cpp|  4 +-
 clang/lib/Driver/ToolChains/AMDGPU.cpp |  2 +-
 clang/lib/Driver/ToolChains/Clang.cpp  | 66 +++---
 clang/lib/Driver/ToolChains/CommonArgs.cpp |  2 +-
 clang/lib/Driver/ToolChains/Flang.cpp  | 13 ++---
 6 files changed, 45 insertions(+), 48 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 114320f5d3146..7b36d8e5084cf 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -564,9 +564,9 @@ static llvm::Triple computeTargetTriple(const Driver &D,
   StringRef ObjectMode = *ObjectModeValue;
   llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
 
-  if (ObjectMode.equals("64")) {
+  if (ObjectMode == "64") {
 AT = Target.get64BitArchVariant().getArch();
-  } else if (ObjectMode.equals("32")) {
+  } else if (ObjectMode == "32") {
 AT = Target.get32BitArchVariant().getArch();
   } else {
 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
@@ -6694,7 +6694,7 @@ llvm::StringRef clang::driver::getDriverMode(StringRef 
ProgName,
   return Opt.consume_front(OptName) ? Opt : "";
 }
 
-bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); 
}
+bool driver::IsClangCL(StringRef DriverMode) { return DriverMode == "cl"; }
 
 llvm::Error driver::expandResponseFiles(SmallVectorImpl &Args,
 bool ClangCLMode,
diff --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index aab98506adb96..85825e1ea65b1 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -481,8 +481,8 @@ static void addTocDataOptions(const llvm::opt::ArgList 
&Args,
 
   // Currently only supported for small code model.
   if (TOCDataGloballyinEffect &&
-  (Args.getLastArgValue(options::OPT_mcmodel_EQ).equals("large") ||
-   Args.getLastArgValue(options::OPT_mcmodel_EQ).equals("medium"))) {
+  (Args.getLastArgValue(options::OPT_mcmodel_EQ) == "large" ||
+   Args.getLastArgValue(options::OPT_mcmodel_EQ) == "medium")) {
 D.Diag(clang::diag::warn_drv_unsupported_tocdata);
 return;
   }
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 07965b487ea79..9ffea57b005de 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -732,7 +732,7 @@ AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, 
StringRef BoundArch,
 
   checkTargetID(*DAL);
 
-  if (!Args.getLastArgValue(options::OPT_x).equals("cl"))
+  if (Args.getLastArgValue(options::OPT_x) != "cl")
 return DAL;
 
   // Phase 1 (.cl -> .bc)
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 775dc24e1..449eb9b2a965a 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1526,7 +1526,7 @@ static void CollectARMPACBTIOptions(const ToolChain &TC, 
const ArgList &Args,
 
   CmdArgs.push_back(
   Args.MakeArgString(Twine("-msign-return-address=") + Scope));
-  if (!Scope.equals("none"))
+  if (Scope != "none")
 CmdArgs.push_back(
 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
   if (BranchProtectionPAuthLR)
@@ -1719,10 +1719,9 @@ void Clang::AddAArch64TargetArgs(const ArgList &Args,
   if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
 StringRef Val = A->getValue();
 const Driver &D = getToolChain().getDriver();
-if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
-Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
-Val.equals("256+")

[clang] [Clang][HLSL] Add environment parameter to availability attribute (PR #89809)

2024-05-09 Thread Helena Kotas via cfe-commits

https://github.com/hekota updated 
https://github.com/llvm/llvm-project/pull/89809

>From 22b67d30ca087d6a912183039c87fd1790eedfe4 Mon Sep 17 00:00:00 2001
From: Helena Kotas 
Date: Tue, 23 Apr 2024 00:49:28 -0700
Subject: [PATCH 1/7] Add environment parameter to clang availability attribute

---
 clang/include/clang/Basic/Attr.td |  33 +-
 clang/include/clang/Basic/AttrDocs.td |   2 +
 .../clang/Basic/DiagnosticParseKinds.td   |   2 +
 .../clang/Basic/DiagnosticSemaKinds.td|   5 +-
 clang/include/clang/Parse/Parser.h|   3 +
 clang/include/clang/Sema/ParsedAttr.h |  40 ---
 clang/include/clang/Sema/Sema.h   |   5 +-
 clang/lib/AST/DeclBase.cpp|  27 -
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  |  13 ++-
 clang/lib/Index/CommentToXML.cpp  |   3 +
 clang/lib/Parse/ParseDecl.cpp |  20 +++-
 clang/lib/Sema/SemaAPINotes.cpp   |   3 +-
 clang/lib/Sema/SemaAvailability.cpp   | 109 +-
 clang/lib/Sema/SemaDecl.cpp   |   2 +-
 clang/lib/Sema/SemaDeclAttr.cpp   |  34 --
 15 files changed, 232 insertions(+), 69 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index dc87a8c6f022d..1b07f4eb40809 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -956,7 +956,7 @@ def Availability : InheritableAttr {
   VersionArgument<"deprecated">, VersionArgument<"obsoleted">,
   BoolArgument<"unavailable">, StringArgument<"message">,
   BoolArgument<"strict">, StringArgument<"replacement">,
-  IntArgument<"priority">];
+  IntArgument<"priority">, IdentifierArgument<"environment">];
   let AdditionalMembers =
 [{static llvm::StringRef getPrettyPlatformName(llvm::StringRef Platform) {
 return llvm::StringSwitch(Platform)
@@ -976,7 +976,7 @@ def Availability : InheritableAttr {
  .Case("xros", "visionOS")
  .Case("xros_app_extension", "visionOS (App Extension)")
  .Case("swift", "Swift")
- .Case("shadermodel", "HLSL ShaderModel")
+ .Case("shadermodel", "HLSL Shader Model")
  .Case("ohos", "OpenHarmony OS")
  .Default(llvm::StringRef());
 }
@@ -1016,7 +1016,34 @@ static llvm::StringRef 
canonicalizePlatformName(llvm::StringRef Platform) {
  .Case("visionos_app_extension", "xros_app_extension")
  .Case("ShaderModel", "shadermodel")
  .Default(Platform);
-} }];
+}
+static llvm::StringRef getPrettyEnviromentName(llvm::StringRef Environment) {
+return llvm::StringSwitch(Environment)
+ .Case("pixel", "pixel shader")
+ .Case("vertex", "vertex shader")
+ .Case("geometry", "geometry shader")
+ .Case("hull", "hull shader")
+ .Case("domain", "domain shader")
+ .Case("compute", "compute shader")
+ .Case("mesh", "mesh shader")
+ .Case("amplification", "amplification shader")
+ .Case("library", "shader library")
+ .Default(Environment);
+}
+static llvm::Triple::EnvironmentType getEnvironmentType(llvm::StringRef 
Environment) {
+return llvm::StringSwitch(Environment)
+ .Case("pixel", llvm::Triple::Pixel)
+ .Case("vertex", llvm::Triple::Vertex)
+ .Case("geometry", llvm::Triple::Geometry)
+ .Case("hull", llvm::Triple::Hull)
+ .Case("domain", llvm::Triple::Domain)
+ .Case("compute", llvm::Triple::Compute)
+ .Case("mesh", llvm::Triple::Mesh)
+ .Case("amplification", llvm::Triple::Amplification)
+ .Case("library", llvm::Triple::Library)
+ .Default(llvm::Triple::UnknownEnvironment);
+}
+}];
   let HasCustomParsing = 1;
   let InheritEvenIfAlreadyPresent = 1;
   let Subjects = SubjectList<[Named]>;
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index a0bbe5861c572..a81163df35ca8 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1593,6 +1593,8 @@ replacement=\ *string-literal*
   a warning about use of a deprecated declaration. The Fix-It will replace
   the deprecated declaration with the new declaration specified.
 
+// HEKOTA TODO add docs here
+
 Multiple availability attributes can be placed on a declaration, which may
 correspond to different platforms. For most platforms, the availability
 attribute with the platform corresponding to the target platform will be used;
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 66405095d51de..631dc8880fcfc 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1103,6 +1103,8 @@ def e

[clang] [analyzer] Support determining origins in a conditional operator in WebKit checkers. (PR #91143)

2024-05-09 Thread Ryosuke Niwa via cfe-commits

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


[clang] 21be818 - [analyzer] Support determining origins in a conditional operator in WebKit checkers. (#91143)

2024-05-09 Thread via cfe-commits

Author: Ryosuke Niwa
Date: 2024-05-09T21:32:28-07:00
New Revision: 21be8182239a9c87a50071d122d5532037fd8305

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

LOG: [analyzer] Support determining origins in a conditional operator in WebKit 
checkers. (#91143)

This PR adds the support for determining the origin of a pointer in a
conditional operator.

Because such an expression can have two distinct origins each of which
needs to be visited, this PR refactors tryToFindPtrOrigin to take a
callback instead of returning a pair.

The callback is called for the second operand and the third operand of
the conditioanl operator (i.e. E2 and E3 in E1 ? E2 : E3).

Also treat nullptr and integer literal as safe pointer origins in the
local variable checker.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
clang/test/Analysis/Checkers/WebKit/call-args.cpp
clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 5c49eecacc0f2..f81db0e67d835 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -16,8 +16,9 @@
 
 namespace clang {
 
-std::pair
-tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj) {
+bool tryToFindPtrOrigin(
+const Expr *E, bool StopAtFirstRefCountedObj,
+std::function callback) {
   while (E) {
 if (auto *tempExpr = dyn_cast(E)) {
   E = tempExpr->getSubExpr();
@@ -31,12 +32,18 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   E = tempExpr->getSubExpr();
   continue;
 }
+if (auto *Expr = dyn_cast(E)) {
+  return tryToFindPtrOrigin(Expr->getTrueExpr(), StopAtFirstRefCountedObj,
+callback) &&
+ tryToFindPtrOrigin(Expr->getFalseExpr(), StopAtFirstRefCountedObj,
+callback);
+}
 if (auto *cast = dyn_cast(E)) {
   if (StopAtFirstRefCountedObj) {
 if (auto *ConversionFunc =
 dyn_cast_or_null(cast->getConversionFunction())) 
{
   if (isCtorOfRefCounted(ConversionFunc))
-return {E, true};
+return callback(E, true);
 }
   }
   // FIXME: This can give false "origin" that would lead to false negatives
@@ -51,7 +58,7 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   if (IsGetterOfRefCt && *IsGetterOfRefCt) {
 E = memberCall->getImplicitObjectArgument();
 if (StopAtFirstRefCountedObj) {
-  return {E, true};
+  return callback(E, true);
 }
 continue;
   }
@@ -68,17 +75,17 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   if (auto *callee = call->getDirectCallee()) {
 if (isCtorOfRefCounted(callee)) {
   if (StopAtFirstRefCountedObj)
-return {E, true};
+return callback(E, true);
 
   E = call->getArg(0);
   continue;
 }
 
 if (isReturnValueRefCounted(callee))
-  return {E, true};
+  return callback(E, true);
 
 if (isSingleton(callee))
-  return {E, true};
+  return callback(E, true);
 
 if (isPtrConversion(callee)) {
   E = call->getArg(0);
@@ -95,7 +102,7 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
 break;
   }
   // Some other expression.
-  return {E, false};
+  return callback(E, false);
 }
 
 bool isASafeCallArg(const Expr *E) {

diff  --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
index e35ea4ef05dd1..e972924e0c523 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
@@ -13,6 +13,7 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/Support/Casting.h"
 
+#include 
 #include 
 #include 
 
@@ -48,10 +49,12 @@ class Expr;
 /// represents ref-counted object during the traversal we return relevant
 /// sub-expression and true.
 ///
-/// \returns subexpression that we traversed to and if \p
-/// StopAtFirstRefCountedObj is true we also return whether we stopped early.
-std::pair
-tryToFindPtrOrigin(const clang::Expr *E, bool StopAtFirstRefCountedObj);
+/// Calls \p callback with the subexpression that we traversed to and if \p
+/// StopAtFirstRefCountedObj is true we also specify whe

[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread Craig Topper via cfe-commits

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

LGTM

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


[clang] Add support for builtin_verbose_trap (PR #79230)

2024-05-09 Thread Akira Hatanaka via cfe-commits


@@ -27,6 +27,9 @@ namespace llvm {
   }
 }
 
+// Prefix for __builtin_verbose_trap.
+#define CLANG_VERBOSE_TRAP_PREFIX "__llvm_verbose_trap"

ahatanak wrote:

I can make it a C++ constant if that's preferable.

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


[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff db78ee0cb82669302a5e0f18a15fd53346a73823 
d50ae3b317839f5603b091aa029414b3c3c42259 -- llvm/lib/TargetParser/Host.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/TargetParser/Host.cpp b/llvm/lib/TargetParser/Host.cpp
index c5156c6cb8..ca053c8872 100644
--- a/llvm/lib/TargetParser/Host.cpp
+++ b/llvm/lib/TargetParser/Host.cpp
@@ -1803,7 +1803,7 @@ bool sys::getHostCPUFeatures(StringMap &Features) {
   // AVX512 is only supported if the OS supports the context save for it.
   Features["avx512f"]= HasLeaf7 && ((EBX >> 16) & 1) && HasAVX512Save;
   if (Features["avx512f"])
-Features["evex512"]  = true;
+Features["evex512"] = true;
   Features["avx512dq"]   = HasLeaf7 && ((EBX >> 17) & 1) && HasAVX512Save;
   Features["rdseed"] = HasLeaf7 && ((EBX >> 18) & 1);
   Features["adx"]= HasLeaf7 && ((EBX >> 19) & 1);

``




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


[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread Phoebe Wang via cfe-commits

phoebewang wrote:

> Could you make getHostCPUFeatures only write the Features["evex512"] entry if 
> Features["avx512f"] is true? Instead of copying Features["avx512f"]?

Good idea, done.

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


[clang] [llvm] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread Phoebe Wang via cfe-commits

https://github.com/phoebewang updated 
https://github.com/llvm/llvm-project/pull/91694

>From 6ea15aa0ee6726cad8dccff10155f058afa0f013 Mon Sep 17 00:00:00 2001
From: Phoebe Wang 
Date: Fri, 10 May 2024 11:21:41 +0800
Subject: [PATCH 1/2] [X86][Driver] Do not add `-evex512` for `-march=native`
 when the target doesn't support AVX512

Users want `-march=sandybridge -mavx512f -mavx512vl` behaves the same as
`-march=native -mavx512f -mavx512vl` on a sandybridge target.

Fixes: #91076
---
 clang/lib/Driver/ToolChains/Arch/X86.cpp | 8 ++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Arch/X86.cpp 
b/clang/lib/Driver/ToolChains/Arch/X86.cpp
index 53e26a9f8e229..c6d97ef4e971a 100644
--- a/clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -132,10 +132,14 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
 if (StringRef(A->getValue()) == "native") {
   llvm::StringMap HostFeatures;
-  if (llvm::sys::getHostCPUFeatures(HostFeatures))
-for (auto &F : HostFeatures)
+  if (llvm::sys::getHostCPUFeatures(HostFeatures)) {
+for (auto &F : HostFeatures) {
+  if (!F.second && F.first() == "evex512")
+continue;
   Features.push_back(
   Args.MakeArgString((F.second ? "+" : "-") + F.first()));
+}
+  }
 }
   }
 

>From d50ae3b317839f5603b091aa029414b3c3c42259 Mon Sep 17 00:00:00 2001
From: Phoebe Wang 
Date: Fri, 10 May 2024 12:02:09 +0800
Subject: [PATCH 2/2] Address review comment

---
 clang/lib/Driver/ToolChains/Arch/X86.cpp | 8 ++--
 llvm/lib/TargetParser/Host.cpp   | 3 ++-
 2 files changed, 4 insertions(+), 7 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Arch/X86.cpp 
b/clang/lib/Driver/ToolChains/Arch/X86.cpp
index c6d97ef4e971a..53e26a9f8e229 100644
--- a/clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -132,14 +132,10 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
 if (StringRef(A->getValue()) == "native") {
   llvm::StringMap HostFeatures;
-  if (llvm::sys::getHostCPUFeatures(HostFeatures)) {
-for (auto &F : HostFeatures) {
-  if (!F.second && F.first() == "evex512")
-continue;
+  if (llvm::sys::getHostCPUFeatures(HostFeatures))
+for (auto &F : HostFeatures)
   Features.push_back(
   Args.MakeArgString((F.second ? "+" : "-") + F.first()));
-}
-  }
 }
   }
 
diff --git a/llvm/lib/TargetParser/Host.cpp b/llvm/lib/TargetParser/Host.cpp
index 834f4536f93ac..c5156c6cb802c 100644
--- a/llvm/lib/TargetParser/Host.cpp
+++ b/llvm/lib/TargetParser/Host.cpp
@@ -1802,7 +1802,8 @@ bool sys::getHostCPUFeatures(StringMap &Features) {
   Features["rtm"]= HasLeaf7 && ((EBX >> 11) & 1);
   // AVX512 is only supported if the OS supports the context save for it.
   Features["avx512f"]= HasLeaf7 && ((EBX >> 16) & 1) && HasAVX512Save;
-  Features["evex512"]= Features["avx512f"];
+  if (Features["avx512f"])
+Features["evex512"]  = true;
   Features["avx512dq"]   = HasLeaf7 && ((EBX >> 17) & 1) && HasAVX512Save;
   Features["rdseed"] = HasLeaf7 && ((EBX >> 18) & 1);
   Features["adx"]= HasLeaf7 && ((EBX >> 19) & 1);

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


[clang] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread Craig Topper via cfe-commits

topperc wrote:

Could you make getHostCPUFeatures only write the Features["evex512"] entry if 
Features["avx512f"] is true? Instead of copying Features["avx512f"]?

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


[clang] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-driver

Author: Phoebe Wang (phoebewang)


Changes

Users want `-march=sandybridge -mavx512f -mavx512vl` behaves the same as 
`-march=native -mavx512f -mavx512vl` on a sandybridge target.

Fixes: #91076

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


1 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Arch/X86.cpp (+6-2) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Arch/X86.cpp 
b/clang/lib/Driver/ToolChains/Arch/X86.cpp
index 53e26a9f8e229..c6d97ef4e971a 100644
--- a/clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -132,10 +132,14 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
 if (StringRef(A->getValue()) == "native") {
   llvm::StringMap HostFeatures;
-  if (llvm::sys::getHostCPUFeatures(HostFeatures))
-for (auto &F : HostFeatures)
+  if (llvm::sys::getHostCPUFeatures(HostFeatures)) {
+for (auto &F : HostFeatures) {
+  if (!F.second && F.first() == "evex512")
+continue;
   Features.push_back(
   Args.MakeArgString((F.second ? "+" : "-") + F.first()));
+}
+  }
 }
   }
 

``




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


[clang] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread Phoebe Wang via cfe-commits

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


[clang] [X86][Driver] Do not add `-evex512` for `-march=native` when the target doesn't support AVX512 (PR #91694)

2024-05-09 Thread Phoebe Wang via cfe-commits

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


[clang] [X86][Driver] Do not add `-evex512` for `-march=native` when the targ… (PR #91694)

2024-05-09 Thread Phoebe Wang via cfe-commits

https://github.com/phoebewang created 
https://github.com/llvm/llvm-project/pull/91694

…et doesn't support AVX512

Users want `-march=sandybridge -mavx512f -mavx512vl` behaves the same as 
`-march=native -mavx512f -mavx512vl` on a sandybridge target.

Fixes: #91076

>From 6ea15aa0ee6726cad8dccff10155f058afa0f013 Mon Sep 17 00:00:00 2001
From: Phoebe Wang 
Date: Fri, 10 May 2024 11:21:41 +0800
Subject: [PATCH] [X86][Driver] Do not add `-evex512` for `-march=native` when
 the target doesn't support AVX512

Users want `-march=sandybridge -mavx512f -mavx512vl` behaves the same as
`-march=native -mavx512f -mavx512vl` on a sandybridge target.

Fixes: #91076
---
 clang/lib/Driver/ToolChains/Arch/X86.cpp | 8 ++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Arch/X86.cpp 
b/clang/lib/Driver/ToolChains/Arch/X86.cpp
index 53e26a9f8e229..c6d97ef4e971a 100644
--- a/clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -132,10 +132,14 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
 if (StringRef(A->getValue()) == "native") {
   llvm::StringMap HostFeatures;
-  if (llvm::sys::getHostCPUFeatures(HostFeatures))
-for (auto &F : HostFeatures)
+  if (llvm::sys::getHostCPUFeatures(HostFeatures)) {
+for (auto &F : HostFeatures) {
+  if (!F.second && F.first() == "evex512")
+continue;
   Features.push_back(
   Args.MakeArgString((F.second ? "+" : "-") + F.first()));
+}
+  }
 }
   }
 

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


[clang] [Clang][Sema] Revise the transformation of CTAD parameters of nested class templates (PR #91628)

2024-05-09 Thread via cfe-commits

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

These changes make sense to me, but please wait for the others to review as 
well.

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


[clang] [Sema] Fix handling of fields with initializers in nested anonymous unions. (PR #91692)

2024-05-09 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 7115ed0fff027b65fa76fdfae215ed1382ed1473 
44c9e4b9920ab23db93a8a716695a6e712edcf01 -- clang/lib/Sema/SemaInit.cpp 
clang/test/AST/ast-dump-APValue-anon-union.cpp 
clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 0a3d3ea019..331f4cdc5e 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -814,8 +814,8 @@ InitListChecker::FillInEmptyInitializations(const 
InitializedEntity &Entity,
   if (const RecordType *RType = ILE->getType()->getAs()) {
 const RecordDecl *RDecl = RType->getDecl();
 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
-  FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
-  Entity, ILE, RequiresSecondPass, FillWithNoInit);
+  FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, 
ILE,
+  RequiresSecondPass, FillWithNoInit);
 } else {
   assert((!RDecl->isUnion() || !isa(RDecl) ||
   !cast(RDecl)->hasInClassInitializer()) &&

``




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


[clang] [Sema] Fix handling of fields with initializers in nested anonymous unions. (PR #91692)

2024-05-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Eli Friedman (efriedma-quic)


Changes

Make sure we count the anonymous union as an initialized field, so we properly 
construct the AST.

Included bonus testcase Test3, which shows a remaining gap: an anonymous union 
can contain a partially initialized anonymous struct, and we handle that 
inconsistently.

Fixes #91257

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


3 Files Affected:

- (modified) clang/lib/Sema/SemaInit.cpp (+8-11) 
- (modified) clang/test/AST/ast-dump-APValue-anon-union.cpp (+1-1) 
- (modified) clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp (+35) 


``diff
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 7d9eaf6720461..0a3d3ea019b1c 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -813,19 +813,13 @@ InitListChecker::FillInEmptyInitializations(const 
InitializedEntity &Entity,
 
   if (const RecordType *RType = ILE->getType()->getAs()) {
 const RecordDecl *RDecl = RType->getDecl();
-if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
+if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
   FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
   Entity, ILE, RequiresSecondPass, FillWithNoInit);
-else if (RDecl->isUnion() && isa(RDecl) &&
- cast(RDecl)->hasInClassInitializer()) {
-  for (auto *Field : RDecl->fields()) {
-if (Field->hasInClassInitializer()) {
-  FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
-  FillWithNoInit);
-  break;
-}
-  }
 } else {
+  assert((!RDecl->isUnion() || !isa(RDecl) ||
+  !cast(RDecl)->hasInClassInitializer()) &&
+ "We should have computed initialized fields already");
   // The fields beyond ILE->getNumInits() are default initialized, so in
   // order to leave them uninitialized, the ILE is expanded and the extra
   // fields are then filled with NoInitExpr.
@@ -2163,12 +2157,15 @@ void InitListChecker::CheckStructUnionTypes(
 return;
   for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Field != FieldEnd; ++Field) {
-if (Field->hasInClassInitializer()) {
+if (Field->hasInClassInitializer() ||
+(Field->isAnonymousStructOrUnion() &&
+ Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) 
{
   StructuredList->setInitializedFieldInUnion(*Field);
   // FIXME: Actually build a CXXDefaultInitExpr?
   return;
 }
   }
+  llvm_unreachable("Couldn't find in-class initializer");
 }
 
 // Value-initialize the first member of the union that isn't an unnamed
diff --git a/clang/test/AST/ast-dump-APValue-anon-union.cpp 
b/clang/test/AST/ast-dump-APValue-anon-union.cpp
index 0e6466ee1fd73..ffe14ed7322de 100644
--- a/clang/test/AST/ast-dump-APValue-anon-union.cpp
+++ b/clang/test/AST/ast-dump-APValue-anon-union.cpp
@@ -36,7 +36,7 @@ void Test() {
 
   constexpr U0 u0a{};
   // CHECK:  | `-VarDecl {{.*}}  col:{{.*}} u0a 'const 
U0' constexpr listinit
-  // CHECK-NEXT:  |   |-value: Union None
+  // CHECK-NEXT:  |   |-value: Union .U0::(anonymous union at {{.*}}) Union .f 
Float 3.141500e+00
 
   constexpr U0 u0b{3.1415f};
   // CHECK:  | `-VarDecl {{.*}}  col:{{.*}} u0b 'const 
U0' constexpr listinit
diff --git a/clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp 
b/clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp
index 3d5e7726a17e5..ca60cf513b4a2 100644
--- a/clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp
+++ b/clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp
@@ -77,3 +77,38 @@ namespace use_self {
 
   int fib(int n) { return FibTree{n}.v; }
 }
+
+namespace nested_union {
+  union Test1 {
+union {
+  int inner { 42 };
+};
+int outer;
+  };
+  static_assert(Test1{}.inner == 42, "");
+  struct Test2 {
+union {
+  struct {
+int inner : 32 { 42 }; // expected-warning {{C++20 extension}}
+  };
+  int outer;
+};
+  };
+  static_assert(Test2{}.inner == 42, "");
+  struct Int { int x; };
+  struct Test3 {
+int x;
+union {
+  struct {
+const int& y;
+int inner : 32 { 42 }; // expected-warning {{C++20 extension}}
+  };
+  int outer;
+};
+  };
+  constexpr char f(Test3) { return 1; } // expected-note {{candidate function}}
+  constexpr char f(Int) { return 2; } // expected-note {{candidate function}}
+  // FIXME: This shouldn't be ambiguous; either we should reject the 
declaration
+  // of Test3, or we should exclude f(Test3) as a candidate.
+  static_assert(f({1}) == 2, ""); // expected-error {{call to 'f' is 
ambiguous}}
+}

``




https://github.com/llvm/llvm-project/pull/91692
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https

[clang] [Sema] Fix handling of fields with initializers in nested anonymous unions. (PR #91692)

2024-05-09 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic created 
https://github.com/llvm/llvm-project/pull/91692

Make sure we count the anonymous union as an initialized field, so we properly 
construct the AST.

Included bonus testcase Test3, which shows a remaining gap: an anonymous union 
can contain a partially initialized anonymous struct, and we handle that 
inconsistently.

Fixes #91257

>From 44c9e4b9920ab23db93a8a716695a6e712edcf01 Mon Sep 17 00:00:00 2001
From: Eli Friedman 
Date: Thu, 9 May 2024 19:40:46 -0700
Subject: [PATCH] [Sema] Fix handling of fields with initializers in nested
 anonymous unions.

Make sure we count the anonymous union as an initialized field, so we
properly construct the AST.

Included bonus testcase Test3, which shows a remaining gap: an anonymous
union can contain a partially initialized anonymous struct, and we
handle that inconsistently.

Fixes #91257
---
 clang/lib/Sema/SemaInit.cpp   | 19 +-
 .../test/AST/ast-dump-APValue-anon-union.cpp  |  2 +-
 .../SemaCXX/cxx1y-initializer-aggregates.cpp  | 35 +++
 3 files changed, 44 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 7d9eaf6720461..0a3d3ea019b1c 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -813,19 +813,13 @@ InitListChecker::FillInEmptyInitializations(const 
InitializedEntity &Entity,
 
   if (const RecordType *RType = ILE->getType()->getAs()) {
 const RecordDecl *RDecl = RType->getDecl();
-if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
+if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
   FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
   Entity, ILE, RequiresSecondPass, FillWithNoInit);
-else if (RDecl->isUnion() && isa(RDecl) &&
- cast(RDecl)->hasInClassInitializer()) {
-  for (auto *Field : RDecl->fields()) {
-if (Field->hasInClassInitializer()) {
-  FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
-  FillWithNoInit);
-  break;
-}
-  }
 } else {
+  assert((!RDecl->isUnion() || !isa(RDecl) ||
+  !cast(RDecl)->hasInClassInitializer()) &&
+ "We should have computed initialized fields already");
   // The fields beyond ILE->getNumInits() are default initialized, so in
   // order to leave them uninitialized, the ILE is expanded and the extra
   // fields are then filled with NoInitExpr.
@@ -2163,12 +2157,15 @@ void InitListChecker::CheckStructUnionTypes(
 return;
   for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Field != FieldEnd; ++Field) {
-if (Field->hasInClassInitializer()) {
+if (Field->hasInClassInitializer() ||
+(Field->isAnonymousStructOrUnion() &&
+ Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) 
{
   StructuredList->setInitializedFieldInUnion(*Field);
   // FIXME: Actually build a CXXDefaultInitExpr?
   return;
 }
   }
+  llvm_unreachable("Couldn't find in-class initializer");
 }
 
 // Value-initialize the first member of the union that isn't an unnamed
diff --git a/clang/test/AST/ast-dump-APValue-anon-union.cpp 
b/clang/test/AST/ast-dump-APValue-anon-union.cpp
index 0e6466ee1fd73..ffe14ed7322de 100644
--- a/clang/test/AST/ast-dump-APValue-anon-union.cpp
+++ b/clang/test/AST/ast-dump-APValue-anon-union.cpp
@@ -36,7 +36,7 @@ void Test() {
 
   constexpr U0 u0a{};
   // CHECK:  | `-VarDecl {{.*}}  col:{{.*}} u0a 'const 
U0' constexpr listinit
-  // CHECK-NEXT:  |   |-value: Union None
+  // CHECK-NEXT:  |   |-value: Union .U0::(anonymous union at {{.*}}) Union .f 
Float 3.141500e+00
 
   constexpr U0 u0b{3.1415f};
   // CHECK:  | `-VarDecl {{.*}}  col:{{.*}} u0b 'const 
U0' constexpr listinit
diff --git a/clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp 
b/clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp
index 3d5e7726a17e5..ca60cf513b4a2 100644
--- a/clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp
+++ b/clang/test/SemaCXX/cxx1y-initializer-aggregates.cpp
@@ -77,3 +77,38 @@ namespace use_self {
 
   int fib(int n) { return FibTree{n}.v; }
 }
+
+namespace nested_union {
+  union Test1 {
+union {
+  int inner { 42 };
+};
+int outer;
+  };
+  static_assert(Test1{}.inner == 42, "");
+  struct Test2 {
+union {
+  struct {
+int inner : 32 { 42 }; // expected-warning {{C++20 extension}}
+  };
+  int outer;
+};
+  };
+  static_assert(Test2{}.inner == 42, "");
+  struct Int { int x; };
+  struct Test3 {
+int x;
+union {
+  struct {
+const int& y;
+int inner : 32 { 42 }; // expected-warning {{C++20 extension}}
+  };
+  int outer;
+};
+  };
+  constexpr char f(Test3) { return 1; } // expected-note {{candidate function}}
+  constexpr char f(Int) { 

[clang] [Clang][Sema] Revise the transformation of CTAD parameters of nested class templates (PR #91628)

2024-05-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Younan Zhang (zyn0217)


Changes

This fixes a regression introduced by bee78b88f.

When we form a deduction guide for a constructor, basically, we do the 
following work:
- Collect template parameters from the constructor's surrounding class 
template, if present.
- Collect template parameters from the constructor.
- Splice these template parameters together into a new template parameter list.
- Turn all the references (e.g. the function parameter list) to the invented 
parameter list by applying a `TreeTransform` to the function type.

In the previous fix, we handled cases of nested class templates by substituting 
the "outer" template parameters (i.e. those not declared at the surrounding 
class template or the constructor) with the instantiating template arguments. 
The approach per se makes sense, but there was a flaw in the following case:

```cpp
template  struct X {
  template  struct Y {
template  Y(T) {}
  };

  template  Y(T) -> Y;
};

X::Y y(42);
```

While we're transforming the parameters for `Y(T)`, we first attempt to 
transform all references to `V` and `T`; then, we handle the references to 
outer parameters `U` and `Us` using the template arguments from `X` 
by transforming the same `ParamDecl`. However, the first step results in the 
reference `T` being `` because the invented `T` is 
the last of the parameter list of the deduction guide, and what we're 
substituting with is a corresponding parameter pack (which is `Us`, though 
empty). Hence we're messing up the substitution.

I think we can resolve it by reversing the substitution order, which means 
handling outer template parameters first and then the inner parameters.

There's no release note because this is a regression in 18, and I hope we can 
catch up with the last release.

Fixes https://github.com/llvm/llvm-project/issues/88142

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaTemplate.cpp (+19-6) 
- (modified) clang/test/SemaTemplate/nested-implicit-deduction-guides.cpp (+14) 


``diff
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 7e57fa0696725..63c16b3fbc279 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2491,9 +2491,6 @@ struct ConvertConstructorToDeductionGuideTransform {
   Args.addOuterRetainedLevel();
 }
 
-if (NestedPattern)
-  Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
-
 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
.getAsAdjusted();
 assert(FPTL && "no prototype for constructor declaration");
@@ -2583,11 +2580,27 @@ struct ConvertConstructorToDeductionGuideTransform {
 
 //-- The types of the function parameters are those of the constructor.
 for (auto *OldParam : TL.getParams()) {
-  ParmVarDecl *NewParam =
-  transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
-  if (NestedPattern && NewParam)
+  ParmVarDecl *NewParam = OldParam;
+  // Given
+  //   template  struct C {
+  // template  struct D {
+  //   template  D(U, V);
+  // };
+  //   };
+  // First, transform all the references to template parameters that are
+  // defined outside of the surrounding class template. That is T in the
+  // above example.
+  if (NestedPattern) {
 NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs,
   MaterializedTypedefs);
+if (!NewParam)
+  return QualType();
+  }
+  // Then, transform all the references to template parameters that are
+  // defined at the class template and the constructor. In this example,
+  // they're U and V, respectively.
+  NewParam =
+  transformFunctionTypeParam(NewParam, Args, MaterializedTypedefs);
   if (!NewParam)
 return QualType();
   ParamTypes.push_back(NewParam->getType());
diff --git a/clang/test/SemaTemplate/nested-implicit-deduction-guides.cpp 
b/clang/test/SemaTemplate/nested-implicit-deduction-guides.cpp
index 38b6706595a11..5428a4eab01cf 100644
--- a/clang/test/SemaTemplate/nested-implicit-deduction-guides.cpp
+++ b/clang/test/SemaTemplate/nested-implicit-deduction-guides.cpp
@@ -84,3 +84,17 @@ nested_init_list::concept_fail nil_invalid{1, ""};
 // expected-note@#INIT_LIST_INNER_INVALID {{candidate template ignored: 
substitution failure [with F = const char *]: constraints not satisfied for 
class template 'concept_fail' [with F = const char *]}}
 // expected-note@#INIT_LIST_INNER_INVALID {{candidate function template not 
viable: requires 1 argument, but 2 were provided}}
 // expected-note@#INIT_LIST_INNER_INVALID {{candidate function template not 

[clang] [Clang][Sema] Revise the transformation of CTAD parameters of nested class templates (PR #91628)

2024-05-09 Thread Younan Zhang via cfe-commits

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


[clang] [Clang][Sema] Revise the transformation of CTAD parameters of nested class templates (PR #91628)

2024-05-09 Thread Younan Zhang via cfe-commits

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


[clang-tools-extra] [clang-tidy] support expect no diagnosis test (PR #91293)

2024-05-09 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/91293

>From 55aecbedf3e10207eaef1d4c7913086a32e16b1e Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Tue, 7 May 2024 10:55:45 +0800
Subject: [PATCH 1/5] [clang-tidy] support expect no diagnosis test

---
 .../test/clang-tidy/check_clang_tidy.py | 13 +++--
 .../clang-tidy/checkers/misc/unused-using-decls.hpp |  6 ++
 .../clang-tidy/checkers/misc/unused-using-decls.hxx |  6 --
 3 files changed, 17 insertions(+), 8 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hpp
 delete mode 100644 
clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hxx

diff --git a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py 
b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
index 6d4b466afa691..d1cfe086fc968 100755
--- a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -99,6 +99,7 @@ def __init__(self, args, extra_args):
 self.has_check_fixes = False
 self.has_check_messages = False
 self.has_check_notes = False
+self.expect_no_diagnosis = args.expect_no_diagnosis
 self.export_fixes = args.export_fixes
 self.fixes = MessagePrefix("CHECK-FIXES")
 self.messages = MessagePrefix("CHECK-MESSAGES")
@@ -225,6 +226,11 @@ def run_clang_tidy(self):
 print(diff_output)
 
print("--")
 return clang_tidy_output
+
+def check_no_diagnosis(self, clang_tidy_output):
+print(clang_tidy_output)
+if clang_tidy_output != "":
+sys.exit('expect no diagnosis')
 
 def check_fixes(self):
 if self.has_check_fixes:
@@ -273,11 +279,13 @@ def check_notes(self, clang_tidy_output):
 
 def run(self):
 self.read_input()
-if self.export_fixes is None:
+if self.export_fixes is None and not self.expect_no_diagnosis:
 self.get_prefixes()
 self.prepare_test_inputs()
 clang_tidy_output = self.run_clang_tidy()
-if self.export_fixes is None:
+if self.expect_no_diagnosis:
+self.check_no_diagnosis(clang_tidy_output)
+elif self.export_fixes is None:
 self.check_fixes()
 self.check_messages(clang_tidy_output)
 self.check_notes(clang_tidy_output)
@@ -310,6 +318,7 @@ def parse_arguments():
 formatter_class=argparse.RawDescriptionHelpFormatter,
 )
 parser.add_argument("-expect-clang-tidy-error", action="store_true")
+parser.add_argument("-expect-no-diagnosis", action="store_true")
 parser.add_argument("-resource-dir")
 parser.add_argument("-assume-filename")
 parser.add_argument("input_file_name")
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hpp 
b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hpp
new file mode 100644
index 0..ce37877a22eca
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy %s misc-unused-using-decls -expect-no-diagnosis %t
+
+// Verify that we don't generate the warnings on header files.
+namespace foo { class Foo {}; }
+
+using foo::Foo;
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hxx 
b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hxx
deleted file mode 100644
index f15e4fae80c0b..0
--- a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.hxx
+++ /dev/null
@@ -1,6 +0,0 @@
-// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- --fix-notes -- 
-fno-delayed-template-parsing -isystem %S/Inputs
-
-// Verify that we don't generate the warnings on header files.
-namespace foo { class Foo {}; }
-
-using foo::Foo;

>From 2a5d18a739e56cbefbff40d49cc1546fcd4b82d4 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Tue, 7 May 2024 13:32:29 +0800
Subject: [PATCH 2/5] format

---
 clang-tools-extra/test/clang-tidy/check_clang_tidy.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py 
b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
index d1cfe086fc968..e87a53df29969 100755
--- a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -226,11 +226,11 @@ def run_clang_tidy(self):
 print(diff_output)
 
print("--")
 return clang_tidy_output
-
+
 def check_no_diagnosis(self, clang_tidy_output):
 print(clang_tidy_output)
 if clang_tidy_output != "":
-sys.exit('expect no diagnosis')
+sys.exit("expect no diagnosis")
 
 def check_fixes(self):
 if self.has_c

[clang] [clang][Driver] Fix enabling strict alising by default when the environment is MSVC (PR #91689)

2024-05-09 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-driver

Author: Max Winkler (MaxEW707)


Changes

I noticed this when changing some of my local projects to use my preferred 
driver mode, GCC, instead of the CL driver mode.

>From looking at the rest of code and from my own understanding the driver mode 
>is supposed to be independent of MSVC compatibility when the target triple is 
>`*-windows-msvc`.
Therefore strict aliasing should be disabled by default when the target triple 
is `*-windows-msvc` so code assuming MSVC behaves as expected when compiled 
with Clang.

Let me know if this requires a note in the release notes.
It didn't feel like this change belonged under the "Clang Frontend Potentially 
Breaking Changes" section or the "Windows Support" section.

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


3 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+2-3) 
- (modified) clang/test/Driver/Ofast.c (+5-2) 
- (modified) clang/test/Driver/clang_f_opts.c (+6) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 0a2ea96de7382..8286c7ae51276 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5651,11 +5651,10 @@ void Clang::ConstructJob(Compilation &C, const 
JobAction &JA,
   // enabled.  This alias option is being used to simplify the hasFlag logic.
   OptSpecifier StrictAliasingAliasOption =
   OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
-  // We turn strict aliasing off by default if we're in CL mode, since MSVC
+  // We turn strict aliasing off by default if we're Windows MSVC since MSVC
   // doesn't do any TBAA.
-  bool TBAAOnByDefault = !D.IsCLMode();
   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
-options::OPT_fno_strict_aliasing, TBAAOnByDefault))
+options::OPT_fno_strict_aliasing, !IsWindowsMSVC))
 CmdArgs.push_back("-relaxed-aliasing");
   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
 options::OPT_fno_struct_path_tbaa, true))
diff --git a/clang/test/Driver/Ofast.c b/clang/test/Driver/Ofast.c
index 1f9fc78ec1ef8..8b7f2217eca2f 100644
--- a/clang/test/Driver/Ofast.c
+++ b/clang/test/Driver/Ofast.c
@@ -3,7 +3,9 @@
 // RUN: %clang -fno-fast-math -Ofast -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST %s
 // RUN: %clang -fno-strict-aliasing -Ofast -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST %s
 // RUN: %clang -fno-vectorize -Ofast -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST %s
-// RUN: %clang -Ofast -O2 -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-O2 %s
+// RUN: %clang -Ofast -O2 -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-O2 \
+// RUN:  %if target={{.*-windows-msvc.*}} %{ 
--check-prefix=CHECK-OFAST-O2-ALIASING-MSVC %} \
+// RUN:  %else %{ --check-prefix=CHECK-OFAST-O2-ALIASING %} %s
 // RUN: %clang -Ofast -fno-fast-math -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-NO-FAST-MATH %s
 // RUN: %clang -Ofast -fno-strict-aliasing -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-NO-STRICT-ALIASING %s
 // RUN: %clang -Ofast -fno-vectorize -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-NO-VECTORIZE %s
@@ -15,7 +17,8 @@
 // CHECK-OFAST: -vectorize-loops
 
 // CHECK-OFAST-O2: -cc1
-// CHECK-OFAST-O2-NOT: -relaxed-aliasing
+// CHECK-OFAST-O2-ALIASING-NOT: -relaxed-aliasing
+// CHECK-OFAST-O2-ALIASING-MSVC: -relaxed-aliasing
 // CHECK-OFAST-O2-NOT: -ffast-math
 // CHECK-OFAST-O2-NOT: -Ofast
 // CHECK-OFAST-O2: -vectorize-loops
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 472d0725a7934..d69cd199ac61d 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -623,3 +623,9 @@
 // RUN: %clang -### --target=aarch64-windows-msvc -fno-ms-volatile %s 2>&1 | 
FileCheck -check-prefix=CHECK-NO-MS-VOLATILE %s
 // CHECK-MS-VOLATILE: -fms-volatile
 // CHECK-NO-MS-VOLATILE-NOT: -fms-volatile
+
+// RUN: %clang -### --target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-STRICT-ALIASING %s
+// RUN: %clang -### --target=x86_64-pc-windows-msvc -fstrict-aliasing %s 2>&1 
| FileCheck -check-prefix=CHECK-STRICT-ALIASING %s
+// RUN: %clang -### --target=x86_64-pc-windows-msvc -fno-strict-aliasing %s 
2>&1 | FileCheck -check-prefix=CHECK-NO-STRICT-ALIASING %s
+// CHECK-STRICT-ALIASING-NOT: -relaxed-aliasing
+// CHECK-NO-STRICT-ALIASING: -relaxed-aliasing

``




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


[clang] [clang][Driver] Fix enabling strict alising by default when the environment is MSVC (PR #91689)

2024-05-09 Thread Max Winkler via cfe-commits

https://github.com/MaxEW707 created 
https://github.com/llvm/llvm-project/pull/91689

I noticed this when changing some of my local projects to use my preferred 
driver mode, GCC, instead of the CL driver mode.

>From looking at the rest of code and from my own understanding the driver mode 
>is supposed to be independent of MSVC compatibility when the target triple is 
>`*-windows-msvc`.
Therefore strict aliasing should be disabled by default when the target triple 
is `*-windows-msvc` so code assuming MSVC behaves as expected when compiled 
with Clang.

Let me know if this requires a note in the release notes.
It didn't feel like this change belonged under the "Clang Frontend Potentially 
Breaking Changes" section or the "Windows Support" section.

>From b43a6302009b9a11ef672f3bd01e10342102de44 Mon Sep 17 00:00:00 2001
From: MaxEW707 
Date: Thu, 9 May 2024 21:21:22 -0400
Subject: [PATCH] [clang][Driver] Fix enabling strict alising by default when
 the environment is MSVC

---
 clang/lib/Driver/ToolChains/Clang.cpp | 5 ++---
 clang/test/Driver/Ofast.c | 7 +--
 clang/test/Driver/clang_f_opts.c  | 6 ++
 3 files changed, 13 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 0a2ea96de7382..8286c7ae51276 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5651,11 +5651,10 @@ void Clang::ConstructJob(Compilation &C, const 
JobAction &JA,
   // enabled.  This alias option is being used to simplify the hasFlag logic.
   OptSpecifier StrictAliasingAliasOption =
   OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
-  // We turn strict aliasing off by default if we're in CL mode, since MSVC
+  // We turn strict aliasing off by default if we're Windows MSVC since MSVC
   // doesn't do any TBAA.
-  bool TBAAOnByDefault = !D.IsCLMode();
   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
-options::OPT_fno_strict_aliasing, TBAAOnByDefault))
+options::OPT_fno_strict_aliasing, !IsWindowsMSVC))
 CmdArgs.push_back("-relaxed-aliasing");
   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
 options::OPT_fno_struct_path_tbaa, true))
diff --git a/clang/test/Driver/Ofast.c b/clang/test/Driver/Ofast.c
index 1f9fc78ec1ef8..8b7f2217eca2f 100644
--- a/clang/test/Driver/Ofast.c
+++ b/clang/test/Driver/Ofast.c
@@ -3,7 +3,9 @@
 // RUN: %clang -fno-fast-math -Ofast -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST %s
 // RUN: %clang -fno-strict-aliasing -Ofast -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST %s
 // RUN: %clang -fno-vectorize -Ofast -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST %s
-// RUN: %clang -Ofast -O2 -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-O2 %s
+// RUN: %clang -Ofast -O2 -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-O2 \
+// RUN:  %if target={{.*-windows-msvc.*}} %{ 
--check-prefix=CHECK-OFAST-O2-ALIASING-MSVC %} \
+// RUN:  %else %{ --check-prefix=CHECK-OFAST-O2-ALIASING %} %s
 // RUN: %clang -Ofast -fno-fast-math -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-NO-FAST-MATH %s
 // RUN: %clang -Ofast -fno-strict-aliasing -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-NO-STRICT-ALIASING %s
 // RUN: %clang -Ofast -fno-vectorize -### %s 2>&1 | FileCheck 
-check-prefix=CHECK-OFAST-NO-VECTORIZE %s
@@ -15,7 +17,8 @@
 // CHECK-OFAST: -vectorize-loops
 
 // CHECK-OFAST-O2: -cc1
-// CHECK-OFAST-O2-NOT: -relaxed-aliasing
+// CHECK-OFAST-O2-ALIASING-NOT: -relaxed-aliasing
+// CHECK-OFAST-O2-ALIASING-MSVC: -relaxed-aliasing
 // CHECK-OFAST-O2-NOT: -ffast-math
 // CHECK-OFAST-O2-NOT: -Ofast
 // CHECK-OFAST-O2: -vectorize-loops
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 472d0725a7934..d69cd199ac61d 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -623,3 +623,9 @@
 // RUN: %clang -### --target=aarch64-windows-msvc -fno-ms-volatile %s 2>&1 | 
FileCheck -check-prefix=CHECK-NO-MS-VOLATILE %s
 // CHECK-MS-VOLATILE: -fms-volatile
 // CHECK-NO-MS-VOLATILE-NOT: -fms-volatile
+
+// RUN: %clang -### --target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-STRICT-ALIASING %s
+// RUN: %clang -### --target=x86_64-pc-windows-msvc -fstrict-aliasing %s 2>&1 
| FileCheck -check-prefix=CHECK-STRICT-ALIASING %s
+// RUN: %clang -### --target=x86_64-pc-windows-msvc -fno-strict-aliasing %s 
2>&1 | FileCheck -check-prefix=CHECK-NO-STRICT-ALIASING %s
+// CHECK-STRICT-ALIASING-NOT: -relaxed-aliasing
+// CHECK-NO-STRICT-ALIASING: -relaxed-aliasing

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


[clang] [clang][driver] Support `-x` for all languages in CL mode (PR #89772)

2024-05-09 Thread Fangrui Song via cfe-commits

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


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


[clang] [Clang][HLSL] Add environment parameter to availability attribute (PR #89809)

2024-05-09 Thread Helena Kotas via cfe-commits

https://github.com/hekota updated 
https://github.com/llvm/llvm-project/pull/89809

>From 22b67d30ca087d6a912183039c87fd1790eedfe4 Mon Sep 17 00:00:00 2001
From: Helena Kotas 
Date: Tue, 23 Apr 2024 00:49:28 -0700
Subject: [PATCH 1/7] Add environment parameter to clang availability attribute

---
 clang/include/clang/Basic/Attr.td |  33 +-
 clang/include/clang/Basic/AttrDocs.td |   2 +
 .../clang/Basic/DiagnosticParseKinds.td   |   2 +
 .../clang/Basic/DiagnosticSemaKinds.td|   5 +-
 clang/include/clang/Parse/Parser.h|   3 +
 clang/include/clang/Sema/ParsedAttr.h |  40 ---
 clang/include/clang/Sema/Sema.h   |   5 +-
 clang/lib/AST/DeclBase.cpp|  27 -
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  |  13 ++-
 clang/lib/Index/CommentToXML.cpp  |   3 +
 clang/lib/Parse/ParseDecl.cpp |  20 +++-
 clang/lib/Sema/SemaAPINotes.cpp   |   3 +-
 clang/lib/Sema/SemaAvailability.cpp   | 109 +-
 clang/lib/Sema/SemaDecl.cpp   |   2 +-
 clang/lib/Sema/SemaDeclAttr.cpp   |  34 --
 15 files changed, 232 insertions(+), 69 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index dc87a8c6f022d..1b07f4eb40809 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -956,7 +956,7 @@ def Availability : InheritableAttr {
   VersionArgument<"deprecated">, VersionArgument<"obsoleted">,
   BoolArgument<"unavailable">, StringArgument<"message">,
   BoolArgument<"strict">, StringArgument<"replacement">,
-  IntArgument<"priority">];
+  IntArgument<"priority">, IdentifierArgument<"environment">];
   let AdditionalMembers =
 [{static llvm::StringRef getPrettyPlatformName(llvm::StringRef Platform) {
 return llvm::StringSwitch(Platform)
@@ -976,7 +976,7 @@ def Availability : InheritableAttr {
  .Case("xros", "visionOS")
  .Case("xros_app_extension", "visionOS (App Extension)")
  .Case("swift", "Swift")
- .Case("shadermodel", "HLSL ShaderModel")
+ .Case("shadermodel", "HLSL Shader Model")
  .Case("ohos", "OpenHarmony OS")
  .Default(llvm::StringRef());
 }
@@ -1016,7 +1016,34 @@ static llvm::StringRef 
canonicalizePlatformName(llvm::StringRef Platform) {
  .Case("visionos_app_extension", "xros_app_extension")
  .Case("ShaderModel", "shadermodel")
  .Default(Platform);
-} }];
+}
+static llvm::StringRef getPrettyEnviromentName(llvm::StringRef Environment) {
+return llvm::StringSwitch(Environment)
+ .Case("pixel", "pixel shader")
+ .Case("vertex", "vertex shader")
+ .Case("geometry", "geometry shader")
+ .Case("hull", "hull shader")
+ .Case("domain", "domain shader")
+ .Case("compute", "compute shader")
+ .Case("mesh", "mesh shader")
+ .Case("amplification", "amplification shader")
+ .Case("library", "shader library")
+ .Default(Environment);
+}
+static llvm::Triple::EnvironmentType getEnvironmentType(llvm::StringRef 
Environment) {
+return llvm::StringSwitch(Environment)
+ .Case("pixel", llvm::Triple::Pixel)
+ .Case("vertex", llvm::Triple::Vertex)
+ .Case("geometry", llvm::Triple::Geometry)
+ .Case("hull", llvm::Triple::Hull)
+ .Case("domain", llvm::Triple::Domain)
+ .Case("compute", llvm::Triple::Compute)
+ .Case("mesh", llvm::Triple::Mesh)
+ .Case("amplification", llvm::Triple::Amplification)
+ .Case("library", llvm::Triple::Library)
+ .Default(llvm::Triple::UnknownEnvironment);
+}
+}];
   let HasCustomParsing = 1;
   let InheritEvenIfAlreadyPresent = 1;
   let Subjects = SubjectList<[Named]>;
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index a0bbe5861c572..a81163df35ca8 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1593,6 +1593,8 @@ replacement=\ *string-literal*
   a warning about use of a deprecated declaration. The Fix-It will replace
   the deprecated declaration with the new declaration specified.
 
+// HEKOTA TODO add docs here
+
 Multiple availability attributes can be placed on a declaration, which may
 correspond to different platforms. For most platforms, the availability
 attribute with the platform corresponding to the target platform will be used;
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 66405095d51de..631dc8880fcfc 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1103,6 +1103,8 @@ def e

[clang-tools-extra] [clang-query] Load queries and matchers from file during REPL cycle (PR #90603)

2024-05-09 Thread Chris Warner via cfe-commits


@@ -281,5 +282,26 @@ const QueryKind SetQueryKind::value;
 const QueryKind SetQueryKind::value;
 #endif
 
+bool FileQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
+  auto Buffer = llvm::MemoryBuffer::getFile(StringRef{File}.trim());
+  if (!Buffer) {
+if (Prefix.has_value())
+  llvm::errs() << *Prefix << ": ";
+llvm::errs() << "cannot open " << File << ": "
+ << Buffer.getError().message() << "\n";

cwarner-8702 wrote:

Got any tips on using `TextDiagnostic`?  I am struggling to figure out what to 
pass as the `LangOptions` and `DiagnosticOptions` considering the error isn't 
coming from code per-se (getting the `ASTContext` from one of the `ASTUnit` 
objects and the options from it seems too hacky)

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


[clang-tools-extra] [clang-query] Load queries and matchers from file during REPL cycle (PR #90603)

2024-05-09 Thread Chris Warner via cfe-commits

https://github.com/cwarner-8702 updated 
https://github.com/llvm/llvm-project/pull/90603

>From 9b1fe59633b5404281b5b9fd754b8a81fae411d0 Mon Sep 17 00:00:00 2001
From: Chris Warner 
Date: Tue, 23 Apr 2024 10:48:44 -0700
Subject: [PATCH 1/4] Load queries and matchers from file during REPL cycle

The clang-query tool has the ability to execute or pre-load queries from
a file when the tool is started, but doesn't have the ability to do the
same from the interactive REPL prompt.  Because the prompt also doesn't
seem to allow multi-line matchers, this can make prototyping and
iterating on more complicated matchers difficult.

Supporting a dynamic load at REPL time allows the cost of reading the
compilation database and building the AST to be imposed just once, and
allows faster prototyping.
---
 clang-tools-extra/clang-query/Query.cpp   | 22 +++
 clang-tools-extra/clang-query/Query.h | 18 ++-
 clang-tools-extra/clang-query/QueryParser.cpp | 10 +++--
 .../clang-query/tool/ClangQuery.cpp   | 18 ++-
 .../test/clang-query/Inputs/file.script   |  1 +
 .../clang-query/Inputs/runtime_file.script|  1 +
 .../test/clang-query/file-query.c | 11 ++
 .../unittests/clang-query/QueryParserTest.cpp |  4 +++-
 8 files changed, 65 insertions(+), 20 deletions(-)
 create mode 100644 clang-tools-extra/test/clang-query/Inputs/file.script
 create mode 100644 
clang-tools-extra/test/clang-query/Inputs/runtime_file.script
 create mode 100644 clang-tools-extra/test/clang-query/file-query.c

diff --git a/clang-tools-extra/clang-query/Query.cpp 
b/clang-tools-extra/clang-query/Query.cpp
index c436d6fa94986..9d5807a52fa8e 100644
--- a/clang-tools-extra/clang-query/Query.cpp
+++ b/clang-tools-extra/clang-query/Query.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "Query.h"
+#include "QueryParser.h"
 #include "QuerySession.h"
 #include "clang/AST/ASTDumper.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
@@ -281,5 +282,26 @@ const QueryKind SetQueryKind::value;
 const QueryKind SetQueryKind::value;
 #endif
 
+bool FileQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
+  auto Buffer = llvm::MemoryBuffer::getFile(StringRef{File}.trim());
+  if (!Buffer) {
+if (Prefix.has_value())
+  llvm::errs() << *Prefix << ": ";
+llvm::errs() << "cannot open " << File << ": "
+ << Buffer.getError().message() << "\n";
+return false;
+  }
+
+  StringRef FileContentRef(Buffer.get()->getBuffer());
+
+  while (!FileContentRef.empty()) {
+QueryRef Q = QueryParser::parse(FileContentRef, QS);
+if (!Q->run(llvm::outs(), QS))
+  return false;
+FileContentRef = Q->RemainingContent;
+  }
+  return true;
+}
+
 } // namespace query
 } // namespace clang
diff --git a/clang-tools-extra/clang-query/Query.h 
b/clang-tools-extra/clang-query/Query.h
index 7aefa6bb5ee0d..7242479633c24 100644
--- a/clang-tools-extra/clang-query/Query.h
+++ b/clang-tools-extra/clang-query/Query.h
@@ -30,7 +30,8 @@ enum QueryKind {
   QK_SetTraversalKind,
   QK_EnableOutputKind,
   QK_DisableOutputKind,
-  QK_Quit
+  QK_Quit,
+  QK_File
 };
 
 class QuerySession;
@@ -188,6 +189,21 @@ struct DisableOutputQuery : SetNonExclusiveOutputQuery {
   }
 };
 
+struct FileQuery : Query {
+  FileQuery(StringRef File, StringRef Prefix = StringRef())
+  : Query(QK_File), File(File),
+Prefix(!Prefix.empty() ? std::optional(Prefix)
+   : std::nullopt) {}
+
+  bool run(llvm::raw_ostream &OS, QuerySession &QS) const override;
+
+  static bool classof(const Query *Q) { return Q->Kind == QK_File; }
+
+private:
+  std::string File;
+  std::optional Prefix;
+};
+
 } // namespace query
 } // namespace clang
 
diff --git a/clang-tools-extra/clang-query/QueryParser.cpp 
b/clang-tools-extra/clang-query/QueryParser.cpp
index 162acc1a598dd..85a442bdd7ded 100644
--- a/clang-tools-extra/clang-query/QueryParser.cpp
+++ b/clang-tools-extra/clang-query/QueryParser.cpp
@@ -183,7 +183,8 @@ enum ParsedQueryKind {
   PQK_Unlet,
   PQK_Quit,
   PQK_Enable,
-  PQK_Disable
+  PQK_Disable,
+  PQK_File
 };
 
 enum ParsedQueryVariable {
@@ -222,12 +223,14 @@ QueryRef QueryParser::doParse() {
   .Case("let", PQK_Let)
   .Case("m", PQK_Match, /*IsCompletion=*/false)
   .Case("match", PQK_Match)
-  .Case("q", PQK_Quit,  /*IsCompletion=*/false)
+  .Case("q", PQK_Quit, /*IsCompletion=*/false)
   .Case("quit", PQK_Quit)
   .Case("set", PQK_Set)
   .Case("enable", PQK_Enable)
   .Case("disable", PQK_Disable)
   .Case("unlet", PQK_Unlet)
+  .Case("f", PQK_File, /*IsCompletion=*/false)
+

[clang] [Clang] Fix incorrect passing of _BitInt args (PR #90741)

2024-05-09 Thread Eli Friedman via cfe-commits


@@ -0,0 +1,14 @@
+// REQUIRES: arm-registered-target
+// RUN: %clang_cc1 -triple aarch64-none-elf \
+// RUN:   -O2 \
+// RUN:   -emit-llvm -fexperimental-max-bitint-width=1024 -o - %s | FileCheck 
%s

efriedma-quic wrote:

Can we integrate this into some existing test file for aarch64 calling 
conventions?

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


[clang] [llvm] [AArch64] Add intrinsics for bfloat16 min/max/minnm/maxnm (PR #90105)

2024-05-09 Thread Hassnaa Hamdi via cfe-commits

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


[clang] [llvm] [AArch64] Add intrinsics for bfloat16 min/max/minnm/maxnm (PR #90105)

2024-05-09 Thread Hassnaa Hamdi via cfe-commits

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


[clang] [BoundsSafety] Allow 'counted_by' attribute on pointers in structs in C (PR #90786)

2024-05-09 Thread Yeoul Na via cfe-commits

rapidsna wrote:

> I've been thinking about this restriction. Why is this necessary? My 
> assumption was that applying counted_by to a pointer causes a bounds check on 
> an index into the pointer rather than its underlying type.

@bwendling It's because these types are not indexable really.

**void:**
`void` doesn't have a size and C standard doesn't allow indexing into `void *`. 
I understand `void *` can be indexable under a GNU extension, but I don't see 
not supporting it is a problem because we can use `__sized_by` to annotate 
`void *` to clearly indicate the byte size. We will upstream `__sized_by` 
support soon so you can use it for `void *`.

**function types**
Although, again, the GNU extension allows it, we don't really want to index 
into function pointers. We can still use `__sized_by` if we really need to.

**Incomplete structs**
You can't really index into an incomplete struct. Though as @apple-fcloutier 
mentioned, by the point when the pointer is actually indexed, you should have 
the complete type definition. Otherwise, indexing will be an error anyway. So 
we have been considering relaxing this requirement, and move the error point to 
where the pointer is actually used in a way it requires the concrete element 
size (e.g, places you would insert `__dynamic_builtin_object_size`, you need 
the element size to calculate the byte size; indexing into a pointer to 
incomplete struct is already an error). 

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


[clang] [BoundsSafety] Allow 'counted_by' attribute on pointers in structs in C (PR #90786)

2024-05-09 Thread Dan Liew via cfe-commits

delcypher wrote:

@bwendling

> I've been thinking about this restriction. Why is this necessary? My 
> assumption was that applying counted_by to a pointer causes a bounds check on 
> an index into the pointer rather than its underlying type.

@rapidsna Please add additional points if I accidentally miss something.

I can try to explain the restrictions from the perspective of the 
`-fbounds-safety` perspective. Essentially the reason these constructs are 
illegal in `-fbounds-safety` is because at runtime we need to be able to 
construct a wide pointer from `__counted_by()` pointers.  In the cases I've 
made illegal in this PR, this is either impossible to do correctly if we don't 
know the size of the pointee.

What I mean specifically by wide pointer is `__bidi_indexable` which is 
`-fbounds-safety`'s wide pointer that can be indexed positively and negatively. 
In `-fbounds-safety`'s model all pointers on the stack are `__bidi_indexable`  
by default and all `__counted_by()` pointers are implicitly converted to wide 
pointers when they are used inside a function.

`-fbounds-safety`'s `__bidi_indexable` is **very roughly** equivalent to this 
C++ code

```c++
template  struct WidePtr {
  T *ptr; // The address that is dereferenced
  // The bounds of the memory that forms the range of valid bytes to access
  // [lower_bound, upper_bound)
  void *lower_bound;
  void *upper_bound;

  WidePtr(T * /*__counted_by(count)*/ p, size_t count) {
ptr = p;
lower_bound = (void *)p;
// NEED sizeof(T) here!
upper_bound = ((char *)p) + sizeof(T) * count;
  }

  T& operator*() {
check_bounds();
return *ptr;
  }

  void check_bounds() {
if (ptr < lower_bound)
  __builtin_trap();

uintptr_t LastByteAccessedPlusOne;
// NEED sizeof(T) here!
if (__builtin_uadd_overflow(ptr, sizeof(T), &LastByteAccessedPlusOne))
  __builtin_trap();

if (LastByteAccessedPlusOne > upper_bound)
  __builtin_trap();
  }

  // Lots of other operators are overloaded (e.g. +, -[], ++, -- and ->).
};
```

We need to know what `sizeof(T)` is in two places:

1. Everywhere you want to do a bounds check. E.g. when dereferencing the 
pointer.
2. When converting a `T* __counted_by()` pointer to a `WidePointer` (or `T* 
__bidi_indexable` in `-fbounds-safety` parlance). If you look at the 
constructor **we need to know** `sizeof(T)` when computing the upper bound of 
the wide pointer. Given that this conversion happens whenever a pointer of the 
type `T* __counted_by()` is used inside a function in the `-fbounds-safety` 
model,  the model requires that `T` have a known size. Technically this PR is 
being even stricter. It's forbidding declaring a `T* __counted_by()` even if it 
isn't used. However, this is a restriction we can lift later once more of the 
implementation is in place.

I've tried to annotate your code below with the specific reasons they are 
forbidden.

```c
// Both `foo` and `bar` are legal
struct foo;
struct bar {
  int a;
  int fam[] __counted_by(a);
};

struct x {
// Illegal in `-fbounds-safety`. We can't compute the upper bound of this 
pointer
// because `sizeof(void)*count` isn't valid. In `-fbounds-safety` the 
attribute you
// would use here is `__sized_by()` which is a byte count rather than an 
element count.
void *p __counted_by(count); 

// Illegal in `-fbounds-safety`. We can't compute the upper bound of this 
pointer because
// `sizeof(struct foo)*count` isn't valid. In particular `sizeof(struct 
foo)` is invalid because
// `struct foo` is an incomplete type.
struct foo *f __counted_by(count);

// Illegal in `-fbounds-safety`. While we can technically compute 
`sizeof(struct bar)*count`
// that computation is completely wrong unless the `bar::a` is `0`. To 
actually get the correct
// count we would need to walk every `struct bar` object in the buffer 
pointed to by `b` to
//  read `b::a`. This could be expensive (and prone to race conditions) so 
we simply
// don't support this right now.
struct bar *b __counted_by(count);

int count;
};
```

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


[clang] [clang][static analyzer] ignore try statements in dead code checker (PR #91675)

2024-05-09 Thread Andrew Sukach via cfe-commits


@@ -159,8 +159,10 @@ void 
UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
   SL = DL.asLocation();
   if (SR.isInvalid() || !SL.isValid())
 continue;
-}
-else
+
+  if (isa(S))

soukatch wrote:

everything besides this if statement is just a clang-format change

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


[clang] [clang][static analyzer] ignore try statements in dead code checker (PR #91675)

2024-05-09 Thread Andrew Sukach via cfe-commits

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


[clang] [clang][static analyzer] ignore try statements in dead code checker (PR #91675)

2024-05-09 Thread Andrew Sukach via cfe-commits

soukatch wrote:

@steakhal I believe you're the best person to tag :).

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


[clang] [clang][static analyzer] ignore try statements in dead code checker (PR #91675)

2024-05-09 Thread Andrew Sukach via cfe-commits


@@ -159,8 +159,10 @@ void 
UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
   SL = DL.asLocation();
   if (SR.isInvalid() || !SL.isValid())
 continue;
-}
-else
+
+  if (isa(S))

soukatch wrote:

everything above this point is just clang-format changes

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


[clang] [clang][static analyzer] ignore try statements in dead code checker (PR #91675)

2024-05-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Andrew Sukach (soukatch)


Changes

Fixes #90162. Simplest approach I could come up with was to skip cxxtry 
statements. Let me know if you have any suggestions. Thanks!

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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp 
(+16-14) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
index d24a124f5ffee..205f646194f58 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
@@ -12,10 +12,10 @@
 // A similar flow-sensitive only check exists in Analysis/ReachableCode.cpp
 
//===--===//
 
-#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/AST/ParentMap.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
@@ -34,6 +34,7 @@ class UnreachableCodeChecker : public 
Checker {
 public:
   void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
 ExprEngine &Eng) const;
+
 private:
   typedef llvm::SmallSet CFGBlocksSet;
 
@@ -44,10 +45,9 @@ class UnreachableCodeChecker : public 
Checker {
   static bool isInvalidPath(const CFGBlock *CB, const ParentMap &PM);
   static inline bool isEmptyCFGBlock(const CFGBlock *CB);
 };
-}
+} // namespace
 
-void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
-  BugReporter &B,
+void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
   ExprEngine &Eng) const {
   CFGBlocksSet reachable, visited;
 
@@ -126,8 +126,8 @@ void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph 
&G,
 // such as llvm_unreachable.
 if (!CB->empty()) {
   bool foundUnreachable = false;
-  for (CFGBlock::const_iterator ci = CB->begin(), ce = CB->end();
-   ci != ce; ++ci) {
+  for (CFGBlock::const_iterator ci = CB->begin(), ce = CB->end(); ci != ce;
+   ++ci) {
 if (std::optional S = (*ci).getAs())
   if (const CallExpr *CE = dyn_cast(S->getStmt())) {
 if (CE->getBuiltinCallee() == Builtin::BI__builtin_unreachable ||
@@ -159,8 +159,10 @@ void 
UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
   SL = DL.asLocation();
   if (SR.isInvalid() || !SL.isValid())
 continue;
-}
-else
+
+  if (isa(S))
+continue;
+} else
   continue;
 
 // Check if the SourceLocation is in a system header
@@ -229,9 +231,9 @@ bool UnreachableCodeChecker::isInvalidPath(const CFGBlock 
*CB,
   // Get the predecessor block's terminator condition
   const Stmt *cond = pred->getTerminatorCondition();
 
-  //assert(cond && "CFGBlock's predecessor has a terminator condition");
-  // The previous assertion is invalid in some cases (eg do/while). Leaving
-  // reporting of these situations on at the moment to help triage these cases.
+  // assert(cond && "CFGBlock's predecessor has a terminator condition");
+  //  The previous assertion is invalid in some cases (eg do/while). Leaving
+  //  reporting of these situations on at the moment to help triage these 
cases.
   if (!cond)
 return false;
 
@@ -243,9 +245,9 @@ bool UnreachableCodeChecker::isInvalidPath(const CFGBlock 
*CB,
 
 // Returns true if the given CFGBlock is empty
 bool UnreachableCodeChecker::isEmptyCFGBlock(const CFGBlock *CB) {
-  return CB->getLabel() == nullptr // No labels
-  && CB->size() == 0   // No statements
-  && !CB->getTerminatorStmt(); // No terminator
+  return CB->getLabel() == nullptr// No labels
+ && CB->size() == 0   // No statements
+ && !CB->getTerminatorStmt(); // No terminator
 }
 
 void ento::registerUnreachableCodeChecker(CheckerManager &mgr) {

``




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


[clang] [clang][static analyzer] ignore try statements in dead code checker (PR #91675)

2024-05-09 Thread Andrew Sukach via cfe-commits

https://github.com/soukatch created 
https://github.com/llvm/llvm-project/pull/91675

Fixes #90162. Simplest approach I could come up with was to skip cxxtry 
statements. Let me know if you have any suggestions. Thanks!

>From e1fcdc37e52189abcdf8ce84ada463491d8b6c04 Mon Sep 17 00:00:00 2001
From: Andrew Sukach 
Date: Thu, 9 May 2024 18:49:41 -0400
Subject: [PATCH] [clang][static analyzer] ignore try statements in dead code
 checker

---
 .../Checkers/UnreachableCodeChecker.cpp   | 30 ++-
 1 file changed, 16 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
index d24a124f5ffee..205f646194f58 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp
@@ -12,10 +12,10 @@
 // A similar flow-sensitive only check exists in Analysis/ReachableCode.cpp
 
//===--===//
 
-#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/AST/ParentMap.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
@@ -34,6 +34,7 @@ class UnreachableCodeChecker : public 
Checker {
 public:
   void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
 ExprEngine &Eng) const;
+
 private:
   typedef llvm::SmallSet CFGBlocksSet;
 
@@ -44,10 +45,9 @@ class UnreachableCodeChecker : public 
Checker {
   static bool isInvalidPath(const CFGBlock *CB, const ParentMap &PM);
   static inline bool isEmptyCFGBlock(const CFGBlock *CB);
 };
-}
+} // namespace
 
-void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
-  BugReporter &B,
+void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
   ExprEngine &Eng) const {
   CFGBlocksSet reachable, visited;
 
@@ -126,8 +126,8 @@ void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph 
&G,
 // such as llvm_unreachable.
 if (!CB->empty()) {
   bool foundUnreachable = false;
-  for (CFGBlock::const_iterator ci = CB->begin(), ce = CB->end();
-   ci != ce; ++ci) {
+  for (CFGBlock::const_iterator ci = CB->begin(), ce = CB->end(); ci != ce;
+   ++ci) {
 if (std::optional S = (*ci).getAs())
   if (const CallExpr *CE = dyn_cast(S->getStmt())) {
 if (CE->getBuiltinCallee() == Builtin::BI__builtin_unreachable ||
@@ -159,8 +159,10 @@ void 
UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
   SL = DL.asLocation();
   if (SR.isInvalid() || !SL.isValid())
 continue;
-}
-else
+
+  if (isa(S))
+continue;
+} else
   continue;
 
 // Check if the SourceLocation is in a system header
@@ -229,9 +231,9 @@ bool UnreachableCodeChecker::isInvalidPath(const CFGBlock 
*CB,
   // Get the predecessor block's terminator condition
   const Stmt *cond = pred->getTerminatorCondition();
 
-  //assert(cond && "CFGBlock's predecessor has a terminator condition");
-  // The previous assertion is invalid in some cases (eg do/while). Leaving
-  // reporting of these situations on at the moment to help triage these cases.
+  // assert(cond && "CFGBlock's predecessor has a terminator condition");
+  //  The previous assertion is invalid in some cases (eg do/while). Leaving
+  //  reporting of these situations on at the moment to help triage these 
cases.
   if (!cond)
 return false;
 
@@ -243,9 +245,9 @@ bool UnreachableCodeChecker::isInvalidPath(const CFGBlock 
*CB,
 
 // Returns true if the given CFGBlock is empty
 bool UnreachableCodeChecker::isEmptyCFGBlock(const CFGBlock *CB) {
-  return CB->getLabel() == nullptr // No labels
-  && CB->size() == 0   // No statements
-  && !CB->getTerminatorStmt(); // No terminator
+  return CB->getLabel() == nullptr// No labels
+ && CB->size() == 0   // No statements
+ && !CB->getTerminatorStmt(); // No terminator
 }
 
 void ento::registerUnreachableCodeChecker(CheckerManager &mgr) {

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


[clang] [BoundsSafety] Allow 'counted_by' attribute on pointers in structs in C (PR #90786)

2024-05-09 Thread via cfe-commits

apple-fcloutier wrote:

I think that there's room to allow `__counted_by` on incomplete types so that a 
TU where it's complete could use it (and we have use cases where that would be 
handy), but our implementation doesn't support it at this time. This can be 
added without disruptions at a later time. FWIW, the point of bounds-checking 
an index is moot at least while the type is incomplete, since it's an error to 
dereference a pointer to an incomplete type. Aside from indexing, operations 
that would cast the pointer (such as `memset(x->foo, 0, some_value)`, assuming 
`memset(void *__sized_by(n), int, size_t n)`) would still have to be illegal 
when `struct foo` is incomplete because there's no way to know how many bytes 
we have at x->foo without `sizeof(struct foo)`.

`void *__counted_by` could be made legal because clang defines `sizeof(void) == 
1` in C mode, as an extension to the C standard. I think it's still best 
avoided: "how many voids do I have at p?" is not a great question to ask, 
whereas the same with `__sized_by` just makes sense. It's also a little bit 
easier to filter out `void` with the rest of the incomplete types.

For structs with a flexible array member, the reason is that `sizeof(struct 
bar)` is a lie. How would we reconcile, for instance, a count of 1 (implying 
there's like 4 bytes at `x->bar`) with a `x->bar->a` of 10 (implying that 
`x->bar->fam[8]` is in bounds)? How do we feel that `x->bar[0]->fam[0]` aliases 
with `x->bar[1]->a`?

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


[clang] [AArch64] add some more tests for FMV (PR #91490)

2024-05-09 Thread Vladimir Vereschaka via cfe-commits

vvereschaka wrote:

@tmatheson-arm , the `Clang::aarch64-fmv.c` gets failed on Windows to Arm Linux 
cross builds with the following errors:

```
# .---command stderr
# | 
C:\buildbot\as-builder-2\x-aarch64\llvm-project\clang\test\Driver\aarch64-fmv.c:27:18:
 error: FMV-DISABLED: expected string not found in input
# | // FMV-DISABLED: "-target-feature" "-fmv"
# |  ^
# | :1:1: note: scanning from here
# | clang version 19.0.0git (https://github.com/llvm/llvm-project.git 
639a740035b732e9bc0f43f3f95d1ce3acf82e1b)
# | ^
# | :7:362: note: possible intended match here
# |  "C:\\buildbot\\as-builder-2\\x-aarch64\\build\\bin\\clang.exe" "-cc1" 
"-triple" "aarch64" "-emit-obj" "-disable-free" "-clear-ast-before-backend" 
"-main-file-name" "aarch64-fmv.c" "-mrelocation-model" "static" 
"-mframe-pointer=non-leaf" "-fmath-errno" "-ffp-contract=on" 
"-fno-rounding-math" "-mconstructor-aliases" "-funwind-tables=2" "-target-cpu" 
"generic" "-target-feature" "+v8a" "-target-feature" "+fp-armv8" 
"-target-feature" "+neon" "-target-abi" "aapcs" "-debugger-tuning=gdb" 
"-fdebug-compilation-dir=C:\\buildbot\\as-builder-2\\x-aarch64\\build\\tools\\clang\\test\\Driver"
 
"-fcoverage-compilation-dir=C:\\buildbot\\as-builder-2\\x-aarch64\\build\\tools\\clang\\test\\Driver"
 "-resource-dir" "C:\\buildbot\\as-builder-2\\x-aarch64\\build\\lib\\clang\\19" 
"-isysroot" "c:/buildbot/fs/jetson-agx-ubuntu" "-ferror-limit" "19" 
"-fno-signed-char" "-fgnuc-version=4.2.1" "-fskip-odr-check-in-gmf" "-faddrsig" 
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o" "aarch64-fmv.o" "-x" "c" 
"C:\\buildbot\\as-builder-2\\x-aarch64\\llvm-project\\clang\\test\\Driver\\aarch64-fmv.c"
# | 



 ^
# | 
# | Input file: 
# | Check file: 
C:\buildbot\as-builder-2\x-aarch64\llvm-project\clang\test\Driver\aarch64-fmv.c
# | 
# | -dump-input=help explains the following input dump.
# | 
# | Input was:
# | <<
# | 1: clang version 19.0.0git 
(https://github.com/llvm/llvm-project.git 
639a740035b732e9bc0f43f3f95d1ce3acf82e1b) 
# | check:27'0 
X~~~
 error: no match found
# | 2: Target: aarch64 
# | check:27'0 
# | 3: Thread model: posix 
# | check:27'0 
# | 4: InstalledDir: C:\buildbot\as-builder-2\x-aarch64\build\bin 
# | check:27'0 ~~~
# | 5: Build config: +assertions 
# | check:27'0 ~~
# | 6:  (in-process) 
# | check:27'0 ~~
# | 7:  
"C:\\buildbot\\as-builder-2\\x-aarch64\\build\\bin\\clang.exe" "-cc1" "-triple" 
"aarch64" "-emit-obj" "-disable-free" "-clear-ast-before-backend" 
"-main-file-name" "aarch64-fmv.c" "-mrelocation-model" "static" 
"-mframe-pointer=non-leaf" "-fmath-errno" "-ffp-contract=on" 
"-fno-rounding-math" "-mconstructor-aliases" "-funwind-tables=2" "-target-cpu" 
"generic" "-target-feature" "+v8a" "-target-feature" "+fp-armv8" 
"-target-feature" "+neon" "-target-abi" "aapcs" "-debugger-tuning=gdb" 
"-fdebug-compilation-dir=C:\\buildbot\\as-builder-2\\x-aarch64\\build\\tools\\clang\\test\\Driver"
 
"-fcoverage-compilation-dir=C:\\buildbot\\as-builder-2\\x-aarch64\\build\\tools\\clang\\test\\Driver"
 "-resource-dir" "C:\\buildbot\\as-builder-2\\x-aarch64\\build\\lib\\clang\\19" 
"-isysroot" "c:/buildbot/fs/jetson-agx-ubuntu" "-ferror-limit" "19" 
"-fno-signed-char" "-fgnuc-version=4.2.1" "-fskip-odr-check-in-gmf" "-faddrsig" 
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o" "aarch64-fmv.o" "-x" "c" 
"C:\\buildbot\\as-builder-2\\x-aarch64\\llvm-project\\clang\\test\\Driver\\aarch64-fmv.c"
 
# | check:27'0 
~~

[clang] [llvm] [WebAssembly] Implement prototype f32.store_f16 instruction. (PR #91545)

2024-05-09 Thread Heejin Ahn via cfe-commits

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


[clang] 8a3277a - [WebAssembly] Implement prototype f32.store_f16 instruction. (#91545)

2024-05-09 Thread via cfe-commits

Author: Brendan Dahl
Date: 2024-05-09T15:38:13-07:00
New Revision: 8a3277acbc7b7af917f570f7d6430dda41c4d9ee

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

LOG: [WebAssembly] Implement prototype f32.store_f16 instruction. (#91545)

Adds a builtin and intrinsic for the f32.store_f16 instruction.

The instruction stores an f32 value as an f16 memory. Specified at:

https://github.com/WebAssembly/half-precision/blob/29a9b9462c9285d4ccc1a5dc39214ddfd1892658/proposals/half-precision/Overview.md

Note: the current spec has f32.store_f16 as opcode 0xFD0121, but this is
incorrect and will be changed to 0xFC31 soon.

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsWebAssembly.def
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/builtins-wasm.c
llvm/include/llvm/IR/IntrinsicsWebAssembly.td
llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h
llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
llvm/lib/Target/WebAssembly/WebAssemblyInstrMemory.td
llvm/test/CodeGen/WebAssembly/half-precision.ll
llvm/test/CodeGen/WebAssembly/offset.ll
llvm/test/MC/WebAssembly/simd-encodings.s

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsWebAssembly.def 
b/clang/include/clang/Basic/BuiltinsWebAssembly.def
index cf54f8f4422f8..8645cff1e8679 100644
--- a/clang/include/clang/Basic/BuiltinsWebAssembly.def
+++ b/clang/include/clang/Basic/BuiltinsWebAssembly.def
@@ -192,6 +192,7 @@ 
TARGET_BUILTIN(__builtin_wasm_relaxed_dot_bf16x8_add_f32_f32x4, "V4fV8UsV8UsV4f"
 
 // Half-Precision (fp16)
 TARGET_BUILTIN(__builtin_wasm_loadf16_f32, "fh*", "nU", "half-precision")
+TARGET_BUILTIN(__builtin_wasm_storef16_f32, "vfh*", "n", "half-precision")
 
 // Reference Types builtins
 // Some builtins are custom type-checked - see 't' as part of the third 
argument,

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 4b03b8b0e093e..f9ee93049b12d 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -21310,6 +21310,12 @@ Value 
*CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
 Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_loadf16_f32);
 return Builder.CreateCall(Callee, {Addr});
   }
+  case WebAssembly::BI__builtin_wasm_storef16_f32: {
+Value *Val = EmitScalarExpr(E->getArg(0));
+Value *Addr = EmitScalarExpr(E->getArg(1));
+Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_storef16_f32);
+return Builder.CreateCall(Callee, {Val, Addr});
+  }
   case WebAssembly::BI__builtin_wasm_table_get: {
 assert(E->getArg(0)->getType()->isArrayType());
 Value *Table = EmitArrayToPointerDecay(E->getArg(0)).emitRawPointer(*this);

diff  --git a/clang/test/CodeGen/builtins-wasm.c 
b/clang/test/CodeGen/builtins-wasm.c
index ab1c6cd494ae5..bcb15969de1c5 100644
--- a/clang/test/CodeGen/builtins-wasm.c
+++ b/clang/test/CodeGen/builtins-wasm.c
@@ -807,6 +807,12 @@ float load_f16_f32(__fp16 *addr) {
   // WEBASSEMBLY: call float @llvm.wasm.loadf16.f32(ptr %{{.*}})
 }
 
+void store_f16_f32(float val, __fp16 *addr) {
+  return __builtin_wasm_storef16_f32(val, addr);
+  // WEBASSEMBLY: tail call void @llvm.wasm.storef16.f32(float %val, ptr 
%{{.*}})
+  // WEBASSEMBLY-NEXT: ret
+}
+
 __externref_t externref_null() {
   return __builtin_wasm_ref_null_extern();
   // WEBASSEMBLY: tail call ptr addrspace(10) @llvm.wasm.ref.null.extern()

diff  --git a/llvm/include/llvm/IR/IntrinsicsWebAssembly.td 
b/llvm/include/llvm/IR/IntrinsicsWebAssembly.td
index f8142a8ca9e93..572d334ac9552 100644
--- a/llvm/include/llvm/IR/IntrinsicsWebAssembly.td
+++ b/llvm/include/llvm/IR/IntrinsicsWebAssembly.td
@@ -332,6 +332,11 @@ def int_wasm_loadf16_f32:
 [llvm_ptr_ty],
 [IntrReadMem, IntrArgMemOnly],
  "", [SDNPMemOperand]>;
+def int_wasm_storef16_f32:
+  Intrinsic<[],
+[llvm_float_ty, llvm_ptr_ty],
+[IntrWriteMem, IntrArgMemOnly],
+ "", [SDNPMemOperand]>;
 
 
 
//===--===//

diff  --git 
a/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h 
b/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h
index d3b496ae59179..d4e9fb057c44d 100644
--- a/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h
+++ b/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h
@@ -207,6 +207,7 @@ inline unsigned GetDefaultP2AlignAny(unsigned Opc) {
   WASM_LOAD_STORE(LOAD_LANE_I16x8)
   WASM_LOAD_STORE(STORE_LANE_I16x8)
   WASM_LOAD_STORE(LOAD_F16_F32)
+  WASM_LOAD_STORE(STORE_F16_F32)
   return 1;
   WASM_LOAD_STORE(LOAD_I32)
   WASM_LOAD_STORE(LOAD_F32)

diff  --git a/llvm/lib/Target/WebAssembly/WebAssemb

[clang] [alpha.webkit.UncountedCallArgsChecker] Allow trivial operator++ (PR #91102)

2024-05-09 Thread Ryosuke Niwa via cfe-commits

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


[clang] a99cb96 - [alpha.webkit.UncountedCallArgsChecker] Allow trivial operator++ (#91102)

2024-05-09 Thread via cfe-commits

Author: Ryosuke Niwa
Date: 2024-05-09T15:34:27-07:00
New Revision: a99cb96dfa97c04c3313cb3770b876fee20eb131

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

LOG: [alpha.webkit.UncountedCallArgsChecker] Allow trivial operator++ (#91102)

This PR adds the support for trivial operator++ implementations. T&
operator++() and T operator++(int) are trivial if the callee is trivial.

Also allow incrementing and decrementing of a POD member variable.

Also treat any __builtin_ functions as trivial.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 6901dbb415bf7..3abfa4cbb295d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -309,21 +309,8 @@ class TrivialFunctionAnalysisVisitor
   bool VisitDefaultStmt(const DefaultStmt *DS) { return VisitChildren(DS); }
 
   bool VisitUnaryOperator(const UnaryOperator *UO) {
-// Operator '*' and '!' are allowed as long as the operand is trivial.
-auto op = UO->getOpcode();
-if (op == UO_Deref || op == UO_AddrOf || op == UO_LNot || op == UO_Not)
-  return Visit(UO->getSubExpr());
-
-if (UO->isIncrementOp() || UO->isDecrementOp()) {
-  // Allow increment or decrement of a POD type.
-  if (auto *RefExpr = dyn_cast(UO->getSubExpr())) {
-if (auto *Decl = dyn_cast(RefExpr->getDecl()))
-  return Decl->isLocalVarDeclOrParm() &&
- Decl->getType().isPODType(Decl->getASTContext());
-  }
-}
-// Other operators are non-trivial.
-return false;
+// Unary operators are trivial if its operand is trivial except co_await.
+return UO->getOpcode() != UO_Coawait && Visit(UO->getSubExpr());
   }
 
   bool VisitBinaryOperator(const BinaryOperator *BO) {
@@ -364,7 +351,7 @@ class TrivialFunctionAnalysisVisitor
 
 if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" ||
 Name == "WTFReportAssertionFailure" ||
-Name == "compilerFenceForCrash" || Name == "__builtin_unreachable")
+Name == "compilerFenceForCrash" || Name.find("__builtin") == 0)
   return true;
 
 return TrivialFunctionAnalysis::isTrivialImpl(Callee, Cache);
@@ -405,6 +392,16 @@ class TrivialFunctionAnalysisVisitor
 return TrivialFunctionAnalysis::isTrivialImpl(Callee, Cache);
   }
 
+  bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE) {
+if (!checkArguments(OCE))
+  return false;
+auto *Callee = OCE->getCalleeDecl();
+if (!Callee)
+  return false;
+// Recursively descend into the callee to confirm that it's trivial as 
well.
+return TrivialFunctionAnalysis::isTrivialImpl(Callee, Cache);
+  }
+
   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
 if (auto *Expr = E->getExpr()) {
   if (!Visit(Expr))

diff  --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp 
b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
index e75d42b9f1491..6ca7677511d73 100644
--- a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
@@ -138,11 +138,29 @@ class Number {
   Number(int v) : v(v) { }
   Number(double);
   Number operator+(const Number&);
+  Number& operator++() { ++v; return *this; }
+  Number operator++(int) { Number returnValue(v); ++v; return returnValue; }
   const int& value() const { return v; }
+  void someMethod();
+
 private:
   int v;
 };
 
+class ComplexNumber {
+public:
+  ComplexNumber() : real(0), complex(0) { }
+  ComplexNumber(const ComplexNumber&);
+  ComplexNumber& operator++() { real.someMethod(); return *this; }
+  ComplexNumber operator++(int);
+  ComplexNumber& operator<<(int);
+  ComplexNumber& operator+();
+
+private:
+  Number real;
+  Number complex;
+};
+
 class RefCounted {
 public:
   void ref() const;
@@ -210,6 +228,12 @@ class RefCounted {
   unsigned trivial32() { return sizeof(int); }
   unsigned trivial33() { return ~0xff; }
   template  unsigned trivial34() { return v; }
+  void trivial35() { v++; }
+  void trivial36() { ++(*number); }
+  void trivial37() { (*number)++; }
+  void trivial38() { v++; if (__builtin_expect(!!(number), 1)) (*number)++; }
+  int trivial39() { return -v; }
+  int trivial40() { return v << 2; }
 
   static RefCounted& singleton() {
 static RefCounted s_RefCounted;
@@ -284,9 +308,14 @@ class RefCounted {
 
   int nonTrivial13() { return ~otherFunction(); }
   int nonTrivial14() { int r = 0xff; r |= otherFunction(); return r; }
+  void n

[clang-tools-extra] [clang-tidy] Ignore unevaluated context in bugprone-optional-value-conversion (PR #90410)

2024-05-09 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti approved this pull request.


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


[clang-tools-extra] [clang-tidy] Ignore unevaluated context in bugprone-optional-value-conversion (PR #90410)

2024-05-09 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

> And in example that you provided there is no issue.

Alright, at least not a bugrprone issue. And the argument for a readability 
issue (which is the direction I initially was going) would probably end in 
someone saying `we use this to diagnose compile errors earlier, not deeper in 
any instantiations`

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


[clang] [llvm] [RISCV] Allow extra underscores in parseNormalizedArchString and parseArchString. (PR #91532)

2024-05-09 Thread Craig Topper via cfe-commits

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


[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-09 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/91430

>From 002751420c7f71fa9903d94e135565793bd8c6f8 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Tue, 7 May 2024 22:32:39 +0800
Subject: [PATCH 1/2] [Clang][Sema] access checking of friend declaration
 should not be delayed

---
 clang/include/clang/Sema/Scope.h |  6 ++
 clang/lib/Parse/ParseDecl.cpp|  7 +--
 clang/lib/Sema/Scope.cpp |  2 ++
 clang/lib/Sema/SemaAccess.cpp| 12 ++--
 clang/test/SemaCXX/PR12361.cpp   | 30 ++
 5 files changed, 53 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/SemaCXX/PR12361.cpp

diff --git a/clang/include/clang/Sema/Scope.h b/clang/include/clang/Sema/Scope.h
index 1752a25111a77..084db73034219 100644
--- a/clang/include/clang/Sema/Scope.h
+++ b/clang/include/clang/Sema/Scope.h
@@ -159,6 +159,9 @@ class Scope {
 
 /// This is a scope of type alias declaration.
 TypeAliasScope = 0x2000,
+
+/// This is a scope of friend declaration.
+FriendScope = 0x4000,
   };
 
 private:
@@ -586,6 +589,9 @@ class Scope {
   /// Determine whether this scope is a type alias scope.
   bool isTypeAliasScope() const { return getFlags() & Scope::TypeAliasScope; }
 
+  /// Determine whether this scope is a friend scope.
+  bool isFriendScope() const { return getFlags() & Scope::FriendScope; }
+
   /// Returns if rhs has a higher scope depth than this.
   ///
   /// The caller is responsible for calling this only if one of the two scopes
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 2c11ae693c354..5b5fc02ad4023 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -4331,9 +4331,12 @@ void Parser::ParseDeclarationSpecifiers(
 
 // friend
 case tok::kw_friend:
-  if (DSContext == DeclSpecContext::DSC_class)
+  if (DSContext == DeclSpecContext::DSC_class) {
 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
-  else {
+Scope *CurS = getCurScope();
+if (!isInvalid && CurS)
+  CurS->setFlags(CurS->getFlags() | Scope::FriendScope);
+  } else {
 PrevSpec = ""; // not actually used by the diagnostic
 DiagID = diag::err_friend_invalid_in_context;
 isInvalid = true;
diff --git a/clang/lib/Sema/Scope.cpp b/clang/lib/Sema/Scope.cpp
index 11a41753a1bda..780aa898b1085 100644
--- a/clang/lib/Sema/Scope.cpp
+++ b/clang/lib/Sema/Scope.cpp
@@ -229,6 +229,8 @@ void Scope::dumpImpl(raw_ostream &OS) const {
   {ClassInheritanceScope, "ClassInheritanceScope"},
   {CatchScope, "CatchScope"},
   {OpenACCComputeConstructScope, "OpenACCComputeConstructScope"},
+  {TypeAliasScope, "TypeAliasScope"},
+  {FriendScope, "FriendScope"},
   };
 
   for (auto Info : FlagInfo) {
diff --git a/clang/lib/Sema/SemaAccess.cpp b/clang/lib/Sema/SemaAccess.cpp
index 6a707eeb66d01..72c6736bb6648 100644
--- a/clang/lib/Sema/SemaAccess.cpp
+++ b/clang/lib/Sema/SemaAccess.cpp
@@ -1477,8 +1477,16 @@ static Sema::AccessResult CheckAccess(Sema &S, 
SourceLocation Loc,
   //   void foo(A::private_type);
   //   void B::foo(A::private_type);
   if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
-S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
-return Sema::AR_delayed;
+Scope *TS = S.getCurScope();
+bool IsFriendDeclaration = false;
+while (TS && !IsFriendDeclaration) {
+  IsFriendDeclaration = TS->isFriendScope();
+  TS = TS->getParent();
+}
+if (!IsFriendDeclaration) {
+  S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
+  return Sema::AR_delayed;
+}
   }
 
   EffectiveContext EC(S.CurContext);
diff --git a/clang/test/SemaCXX/PR12361.cpp b/clang/test/SemaCXX/PR12361.cpp
new file mode 100644
index 0..95ceb45b7ba04
--- /dev/null
+++ b/clang/test/SemaCXX/PR12361.cpp
@@ -0,0 +1,30 @@
+ // RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s
+ // RUN: %clang_cc1 -fsyntax-only -verify -std=c++17 %s
+ 
+class D {
+class E{
+class F{}; // expected-note{{implicitly declared private here}}
+friend  void foo(D::E::F& q);
+};
+friend  void foo(D::E::F& q); // expected-error{{'F' is a private member 
of 'D::E'}}
+};
+
+void foo(D::E::F& q) {}
+
+class D1 {
+class E1{
+class F1{}; // expected-note{{implicitly declared private here}}
+friend  D1::E1::F1 foo1();
+};
+friend  D1::E1::F1 foo1(); // expected-error{{'F1' is a private member of 
'D1::E1'}}
+};
+
+D1::E1::F1 foo1() { return D1::E1::F1(); }
+
+class D2 {
+class E2{
+class F2{};
+friend  void foo2();
+};
+friend  void foo2(){ D2::E2::F2 c;}
+};

>From 113c8508881babe25ab9d1daa9ab9a72018da124 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Wed, 8 May 2024 21:22:01 +0800
Subject: [PATCH 2/2] apply reviews

---
 clang/docs/ReleaseN

[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)

2024-05-09 Thread Julian Schmidt via cfe-commits

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


[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)

2024-05-09 Thread Julian Schmidt via cfe-commits


@@ -311,7 +311,12 @@ ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(
 : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine),
   RemoveIncompatibleErrors(RemoveIncompatibleErrors),
   GetFixesFromNotes(GetFixesFromNotes),
-  EnableNolintBlocks(EnableNolintBlocks) {}
+  EnableNolintBlocks(EnableNolintBlocks) {
+
+  if (Context.getOptions().ExcludeHeaderFilterRegex)
+ExcludeHeaderFilter = std::make_unique(
+*Context.getOptions().ExcludeHeaderFilterRegex);
+}

5chmidti wrote:

> which I think is handled in the latest revision

I agree

> I could migrate HeaderFilter to mirror the new and improved 
> ExcludeHeaderFilter...though I worry a bit about this change growing larger 
> and larger

Sure, a small follow-up pr would probably be better.

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


[clang] [analyzer] Support determining origins in a conditional operator in WebKit checkers. (PR #91143)

2024-05-09 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/91143

>From d3a5518192fdc2ee121ef960a91a10ec1e3fffc2 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 5 May 2024 13:40:10 -0700
Subject: [PATCH] [analyzer] Support determining origins in a conditional
 operator in WebKit checkers.

This PR adds the support for determining the origin of a pointer in a 
conditional operator.

Because such an expression can have two distinct origins each of which needs to 
be visited,
this PR refactors tryToFindPtrOrigin to take a callback instead of returning a 
pair.

The callback is called for the second operand and the third operand of the 
conditioanl
operator (i.e. E2 and E3 in E1 ? E2 : E3).

Also treat nullptr and integer literal as safe pointer origins in the local 
variable checker.
---
 .../Checkers/WebKit/ASTUtils.cpp  | 23 --
 .../StaticAnalyzer/Checkers/WebKit/ASTUtils.h | 11 ++-
 .../WebKit/UncountedCallArgsChecker.cpp   | 36 +
 .../WebKit/UncountedLocalVarsChecker.cpp  | 73 +++
 .../Analysis/Checkers/WebKit/call-args.cpp| 14 
 .../Checkers/WebKit/uncounted-local-vars.cpp  | 18 +
 6 files changed, 113 insertions(+), 62 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 5c49eecacc0f2..f81db0e67d835 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -16,8 +16,9 @@
 
 namespace clang {
 
-std::pair
-tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj) {
+bool tryToFindPtrOrigin(
+const Expr *E, bool StopAtFirstRefCountedObj,
+std::function callback) {
   while (E) {
 if (auto *tempExpr = dyn_cast(E)) {
   E = tempExpr->getSubExpr();
@@ -31,12 +32,18 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   E = tempExpr->getSubExpr();
   continue;
 }
+if (auto *Expr = dyn_cast(E)) {
+  return tryToFindPtrOrigin(Expr->getTrueExpr(), StopAtFirstRefCountedObj,
+callback) &&
+ tryToFindPtrOrigin(Expr->getFalseExpr(), StopAtFirstRefCountedObj,
+callback);
+}
 if (auto *cast = dyn_cast(E)) {
   if (StopAtFirstRefCountedObj) {
 if (auto *ConversionFunc =
 dyn_cast_or_null(cast->getConversionFunction())) 
{
   if (isCtorOfRefCounted(ConversionFunc))
-return {E, true};
+return callback(E, true);
 }
   }
   // FIXME: This can give false "origin" that would lead to false negatives
@@ -51,7 +58,7 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   if (IsGetterOfRefCt && *IsGetterOfRefCt) {
 E = memberCall->getImplicitObjectArgument();
 if (StopAtFirstRefCountedObj) {
-  return {E, true};
+  return callback(E, true);
 }
 continue;
   }
@@ -68,17 +75,17 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   if (auto *callee = call->getDirectCallee()) {
 if (isCtorOfRefCounted(callee)) {
   if (StopAtFirstRefCountedObj)
-return {E, true};
+return callback(E, true);
 
   E = call->getArg(0);
   continue;
 }
 
 if (isReturnValueRefCounted(callee))
-  return {E, true};
+  return callback(E, true);
 
 if (isSingleton(callee))
-  return {E, true};
+  return callback(E, true);
 
 if (isPtrConversion(callee)) {
   E = call->getArg(0);
@@ -95,7 +102,7 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
 break;
   }
   // Some other expression.
-  return {E, false};
+  return callback(E, false);
 }
 
 bool isASafeCallArg(const Expr *E) {
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
index e35ea4ef05dd1..e972924e0c523 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
@@ -13,6 +13,7 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/Support/Casting.h"
 
+#include 
 #include 
 #include 
 
@@ -48,10 +49,12 @@ class Expr;
 /// represents ref-counted object during the traversal we return relevant
 /// sub-expression and true.
 ///
-/// \returns subexpression that we traversed to and if \p
-/// StopAtFirstRefCountedObj is true we also return whether we stopped early.
-std::pair
-tryToFindPtrOrigin(const clang::Expr *E, bool StopAtFirstRefCountedObj);
+/// Calls \p callback with the subexpression that we traversed to and if \p
+/// StopAtFirstRefCountedObj is true we also specify whether we stopped early.
+/// Returns false if any of calls to callbacks returned false. Otherwise true.
+bool tryToFindPtrOrigin(
+const clang::Expr *E, bool StopAt

[clang] [llvm] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin, fmax and frexp. (PR #88978)

2024-05-09 Thread Hubert Tong via cfe-commits

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


[clang] [llvm] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin, fmax and frexp. (PR #88978)

2024-05-09 Thread Hubert Tong via cfe-commits


@@ -14572,6 +14572,9 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr 
*E) {
 int FrexpExp;
 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
 Result = llvm::frexp(Result, FrexpExp, RM);
+if (!Result.isZero() && !Result.isNaN() && !Result.isInfinity())
+  assert(llvm::APFloat::isInRange(Result) &&
+"The value is not in the expected range for frexp.");

hubert-reinterpretcast wrote:

assert((Result.isZero() || Result.isNaN() || Result.isInfinity() || ...) && 
"...");



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


[clang] [llvm] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin, fmax and frexp. (PR #88978)

2024-05-09 Thread Hubert Tong via cfe-commits


@@ -951,6 +951,19 @@ class APFloat : public APFloatBase {
 
   bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); }
 
+  //  Checks that the value x is in the range (-1;-0.5], [0.5; 1)
+  static bool isInRange(const llvm::APFloat &x) {

hubert-reinterpretcast wrote:

I don't think this should be a member function of `APFloat`. It can be an 
implementation detail of `ExprConstant.cpp`. In either case, the function 
should be named something like `isInFrexpResultRange`.

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


[clang] [llvm] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin, fmax and frexp. (PR #88978)

2024-05-09 Thread Hubert Tong via cfe-commits

https://github.com/hubert-reinterpretcast commented:

Partial review comments.

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


[clang] [llvm] [MC,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)

2024-05-09 Thread Fangrui Song via cfe-commits

MaskRay wrote:

> I think it would be useful to nominate a source as the canonical reference 
> for the specification which is updated along with any implementation changes. 
> I think 
> [discourse.llvm.org/t/rfc-crel-a-compact-relocation-format-for-elf/77600/3](https://discourse.llvm.org/t/rfc-crel-a-compact-relocation-format-for-elf/77600/3)
>  is a good starting point.
> 
> Possible examples:
> 
> * A patch to the LLVM documentation.
> * A blog-post that is kept up to date with the implementation.
> * A discourse post that is updated.

Thanks. I frequently update my blog posts and 
https://maskray.me/blog/2024-03-09-a-compact-relocation-format-for-elf#crel-relocation-format
 will be kept up to date.

However, I feel not so good to name my personal website. Then, 
https://discourse.llvm.org/t/rfc-crel-a-compact-relocation-format-for-elf/77600/3
 should serve the purpose well. discourse.llvm.org posts become non-editable 
after a period of time. I'll need to make further applies if changes are made.

> Link: 
> [discourse.llvm.org/t/rfc-crel-a-compact-relocation-format-for-elf/77600](https://discourse.llvm.org/t/rfc-crel-a-compact-relocation-format-for-elf/77600)

I can edit the link to append `/3` to refer to the specification.

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


[clang] [analyzer] Support determining origins in a conditional operator in WebKit checkers. (PR #91143)

2024-05-09 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/91143

>From a1b53d5eba21e527c292c7a899487c911d75029d Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 5 May 2024 13:40:10 -0700
Subject: [PATCH] [analyzer] Support determining origins in a conditional
 operator in WebKit checkers.

This PR adds the support for determining the origin of a pointer in a 
conditional operator.

Because such an expression can have two distinct origins each of which needs to 
be visited,
this PR refactors tryToFindPtrOrigin to take a callback instead of returning a 
pair.

The callback is called for the second operand and the third operand of the 
conditioanl
operator (i.e. E2 and E3 in E1 ? E2 : E3).

Also treat nullptr and integer literal as safe pointer origins in the local 
variable checker.
---
 .../Checkers/WebKit/ASTUtils.cpp  | 22 --
 .../StaticAnalyzer/Checkers/WebKit/ASTUtils.h | 11 ++-
 .../WebKit/UncountedCallArgsChecker.cpp   | 36 +
 .../WebKit/UncountedLocalVarsChecker.cpp  | 73 +++
 .../Analysis/Checkers/WebKit/call-args.cpp| 14 
 .../Checkers/WebKit/uncounted-local-vars.cpp  | 18 +
 6 files changed, 112 insertions(+), 62 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 5c49eecacc0f2..899fbf3cbe119 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -16,8 +16,9 @@
 
 namespace clang {
 
-std::pair
-tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj) {
+bool tryToFindPtrOrigin(
+const Expr *E, bool StopAtFirstRefCountedObj,
+std::function callback) {
   while (E) {
 if (auto *tempExpr = dyn_cast(E)) {
   E = tempExpr->getSubExpr();
@@ -30,13 +31,18 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
 if (auto *tempExpr = dyn_cast(E)) {
   E = tempExpr->getSubExpr();
   continue;
+if (auto *Expr = dyn_cast(E)) {
+  return tryToFindPtrOrigin(Expr->getTrueExpr(), StopAtFirstRefCountedObj,
+callback) &&
+ tryToFindPtrOrigin(Expr->getFalseExpr(), StopAtFirstRefCountedObj,
+callback);
 }
 if (auto *cast = dyn_cast(E)) {
   if (StopAtFirstRefCountedObj) {
 if (auto *ConversionFunc =
 dyn_cast_or_null(cast->getConversionFunction())) 
{
   if (isCtorOfRefCounted(ConversionFunc))
-return {E, true};
+return callback(E, true);
 }
   }
   // FIXME: This can give false "origin" that would lead to false negatives
@@ -51,7 +57,7 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   if (IsGetterOfRefCt && *IsGetterOfRefCt) {
 E = memberCall->getImplicitObjectArgument();
 if (StopAtFirstRefCountedObj) {
-  return {E, true};
+  return callback(E, true);
 }
 continue;
   }
@@ -68,17 +74,17 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   if (auto *callee = call->getDirectCallee()) {
 if (isCtorOfRefCounted(callee)) {
   if (StopAtFirstRefCountedObj)
-return {E, true};
+return callback(E, true);
 
   E = call->getArg(0);
   continue;
 }
 
 if (isReturnValueRefCounted(callee))
-  return {E, true};
+  return callback(E, true);
 
 if (isSingleton(callee))
-  return {E, true};
+  return callback(E, true);
 
 if (isPtrConversion(callee)) {
   E = call->getArg(0);
@@ -95,7 +101,7 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
 break;
   }
   // Some other expression.
-  return {E, false};
+  return callback(E, false);
 }
 
 bool isASafeCallArg(const Expr *E) {
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
index e35ea4ef05dd1..e972924e0c523 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
@@ -13,6 +13,7 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/Support/Casting.h"
 
+#include 
 #include 
 #include 
 
@@ -48,10 +49,12 @@ class Expr;
 /// represents ref-counted object during the traversal we return relevant
 /// sub-expression and true.
 ///
-/// \returns subexpression that we traversed to and if \p
-/// StopAtFirstRefCountedObj is true we also return whether we stopped early.
-std::pair
-tryToFindPtrOrigin(const clang::Expr *E, bool StopAtFirstRefCountedObj);
+/// Calls \p callback with the subexpression that we traversed to and if \p
+/// StopAtFirstRefCountedObj is true we also specify whether we stopped early.
+/// Returns false if any of calls to callbacks returned false. Otherwise true.
+bool tryToFindPtrOrigin(
+   

[clang] [clang][dataflow] Fully support Environment construction for Stmt analysis. (PR #91616)

2024-05-09 Thread Samira Bazuzi via cfe-commits

https://github.com/bazuzi updated 
https://github.com/llvm/llvm-project/pull/91616

>From b62a95001e32a0c1d63204950481eb500c9d0275 Mon Sep 17 00:00:00 2001
From: Samira Bazuzi 
Date: Thu, 9 May 2024 12:00:06 -0400
Subject: [PATCH 1/2] [clang][dataflow] Fully support Environment construction
 for Stmt analysis.

Assume in fewer places that the analysis is of a FunctionDecl, and initialize 
the Environment properly for Stmts.

Moves constructors for Environment to header to make it more obvious
that there are only minor differences between them and very little
initialization in the constructors.

Tested check-clang-tooling.
---
 .../FlowSensitive/DataflowEnvironment.h   | 133 --
 .../FlowSensitive/DataflowEnvironment.cpp | 113 +++
 .../TypeErasedDataflowAnalysis.cpp|   2 +-
 .../FlowSensitive/DataflowEnvironmentTest.cpp |  33 +
 .../Analysis/FlowSensitive/TestingSupport.h   |   4 +-
 5 files changed, 176 insertions(+), 109 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index cdf89c7def2c9..dfc3f6a35e4e0 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -19,6 +19,7 @@
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/Type.h"
+#include "clang/Analysis/FlowSensitive/ASTOps.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Analysis/FlowSensitive/Formula.h"
@@ -28,8 +29,10 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/PointerUnion.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
+#include 
 #include 
 #include 
 #include 
@@ -155,7 +158,9 @@ class Environment {
 
   /// Creates an environment that uses `DACtx` to store objects that encompass
   /// the state of a program.
-  explicit Environment(DataflowAnalysisContext &DACtx);
+  explicit Environment(DataflowAnalysisContext &DACtx)
+  : DACtx(&DACtx),
+FlowConditionToken(DACtx.arena().makeFlowConditionToken()) {}
 
   // Copy-constructor is private, Environments should not be copied. See 
fork().
   Environment &operator=(const Environment &Other) = delete;
@@ -164,23 +169,25 @@ class Environment {
   Environment &operator=(Environment &&Other) = default;
 
   /// Creates an environment that uses `DACtx` to store objects that encompass
-  /// the state of a program.
-  ///
-  /// If `DeclCtx` is a function, initializes the environment with symbolic
-  /// representations of the function parameters.
-  ///
-  /// If `DeclCtx` is a non-static member function, initializes the environment
-  /// with a symbolic representation of the `this` pointee.
-  Environment(DataflowAnalysisContext &DACtx, const DeclContext &DeclCtx);
+  /// the state of a program, with `FD` as the current analysis target.
+  Environment(DataflowAnalysisContext &DACtx, const FunctionDecl &FD)
+  : Environment(DACtx) {
+TargetStack.push_back(&FD);
+  }
+
+  /// Creates an environment that uses `DACtx` to store objects that encompass
+  /// the state of a program, with `S` as the current analysis target.
+  Environment(DataflowAnalysisContext &DACtx, Stmt &S) : Environment(DACtx) {
+TargetStack.push_back(&S);
+  }
 
   /// Assigns storage locations and values to all parameters, captures, global
-  /// variables, fields and functions referenced in the function currently 
being
-  /// analyzed.
+  /// variables, fields and functions referenced in the target currently
+  /// being analyzed.
   ///
-  /// Requirements:
-  ///
-  ///  The function must have a body, i.e.
-  ///  `FunctionDecl::doesThisDecalarationHaveABody()` must be true.
+  /// If the current analysis target is a non-static member function,
+  /// initializes the environment with a symbolic representation of the `this`
+  /// pointee.
   void initialize();
 
   /// Returns a new environment that is a copy of this one.
@@ -365,46 +372,51 @@ class Environment {
   RecordStorageLocation &
   getResultObjectLocation(const Expr &RecordPRValue) const;
 
-  /// Returns the return value of the current function. This can be null if:
+  /// Returns the return value of the function currently being analyzed.
+  /// This can be null if:
   /// - The function has a void return type
   /// - No return value could be determined for the function, for example
   ///   because it calls a function without a body.
   ///
   /// Requirements:
-  ///  The current function must have a non-reference return type.
+  ///  The current analysis target must be a function and must have a
+  ///  non-reference return type.
   Value *getReturnValue() const {
 assert(getCurrentFunc() != nullptr &&
!getCurrentFunc()->getReturnType()->is

[clang] [flang] [flang] New -fdebug-unparse-with-modules option (PR #91660)

2024-05-09 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Peter Klausler (klausler)


Changes

This option is a compilation action that parses a source file and performs 
semantic analysis on it, like the existing -fdebug-unparse option does.  Its 
output, however, is preceded by the effective contents of all of the 
non-intrinsic modules on which it depends but does not define, transitively 
preceded by the closure of all of those modules' dependencies.

The output from this option is therefore the analyzed parse tree for a source 
file encapsulated with all of its non-intrinsic module dependencies.  This 
output may be useful for extracting code from large applications for use as an 
attachment to a bug report, or as input to a test case reduction tool for 
problem isolation.

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


11 Files Affected:

- (modified) clang/include/clang/Driver/Options.td (+3-1) 
- (modified) flang/include/flang/Frontend/FrontendActions.h (+4) 
- (modified) flang/include/flang/Frontend/FrontendOptions.h (+4) 
- (modified) flang/include/flang/Semantics/unparse-with-symbols.h (+4) 
- (modified) flang/lib/Frontend/CompilerInvocation.cpp (+3) 
- (modified) flang/lib/Frontend/FrontendActions.cpp (+9) 
- (modified) flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp (+2) 
- (modified) flang/lib/Semantics/mod-file.cpp (+18-2) 
- (modified) flang/lib/Semantics/mod-file.h (+3) 
- (modified) flang/lib/Semantics/unparse-with-symbols.cpp (+38) 
- (added) flang/test/Driver/unparse-with-modules.f90 (+34) 


``diff
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 73a2518480e9b..2e6db8d5ebd56 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6644,7 +6644,9 @@ def fdebug_unparse : Flag<["-"], "fdebug-unparse">, 
Group,
   DocBrief<[{Run the parser and the semantic checks. Then unparse the
 parse-tree and output the generated Fortran source file.}]>;
 def fdebug_unparse_with_symbols : Flag<["-"], "fdebug-unparse-with-symbols">, 
Group,
-  HelpText<"Unparse and stop.">;
+  HelpText<"Unparse with symbols and stop.">;
+def fdebug_unparse_with_modules : Flag<["-"], "fdebug-unparse-with-modules">, 
Group,
+  HelpText<"Unparse with dependent modules and stop.">;
 def fdebug_dump_symbols : Flag<["-"], "fdebug-dump-symbols">, 
Group,
   HelpText<"Dump symbols after the semantic analysis">;
 def fdebug_dump_parse_tree : Flag<["-"], "fdebug-dump-parse-tree">, 
Group,
diff --git a/flang/include/flang/Frontend/FrontendActions.h 
b/flang/include/flang/Frontend/FrontendActions.h
index e2e859f3a81bd..7823565eb815f 100644
--- a/flang/include/flang/Frontend/FrontendActions.h
+++ b/flang/include/flang/Frontend/FrontendActions.h
@@ -108,6 +108,10 @@ class DebugUnparseWithSymbolsAction : public 
PrescanAndSemaAction {
   void executeAction() override;
 };
 
+class DebugUnparseWithModulesAction : public PrescanAndSemaAction {
+  void executeAction() override;
+};
+
 class DebugUnparseAction : public PrescanAndSemaAction {
   void executeAction() override;
 };
diff --git a/flang/include/flang/Frontend/FrontendOptions.h 
b/flang/include/flang/Frontend/FrontendOptions.h
index 06b1318f243b0..82ca99672ec61 100644
--- a/flang/include/flang/Frontend/FrontendOptions.h
+++ b/flang/include/flang/Frontend/FrontendOptions.h
@@ -63,6 +63,10 @@ enum ActionKind {
   /// Fortran source file
   DebugUnparseWithSymbols,
 
+  /// Parse, run semantics, and output a Fortran source file preceded
+  /// by all the necessary modules (transitively)
+  DebugUnparseWithModules,
+
   /// Parse, run semantics and then output symbols from semantics
   DebugDumpSymbols,
 
diff --git a/flang/include/flang/Semantics/unparse-with-symbols.h 
b/flang/include/flang/Semantics/unparse-with-symbols.h
index d70110245e2b2..5e18b3fc3063d 100644
--- a/flang/include/flang/Semantics/unparse-with-symbols.h
+++ b/flang/include/flang/Semantics/unparse-with-symbols.h
@@ -21,8 +21,12 @@ struct Program;
 }
 
 namespace Fortran::semantics {
+class SemanticsContext;
 void UnparseWithSymbols(llvm::raw_ostream &, const parser::Program &,
 parser::Encoding encoding = parser::Encoding::UTF_8);
+void UnparseWithModules(llvm::raw_ostream &, SemanticsContext &,
+const parser::Program &,
+parser::Encoding encoding = parser::Encoding::UTF_8);
 }
 
 #endif // FORTRAN_SEMANTICS_UNPARSE_WITH_SYMBOLS_H_
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index 4318286e74152..e0d5043823a6c 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -488,6 +488,9 @@ static bool parseFrontendArgs(FrontendOptions &opts, 
llvm::opt::ArgList &args,
 case clang::driver::options::OPT_fdebug_unparse_with_symbols:
   opts.programAction = DebugUnparseWithSymbols;
   break;
+case clang::driver::options::OPT_fdebug_unparse_with_modules:
+  opts.progra

[clang] [flang] [flang] New -fdebug-unparse-with-modules option (PR #91660)

2024-05-09 Thread Peter Klausler via cfe-commits

https://github.com/klausler created 
https://github.com/llvm/llvm-project/pull/91660

This option is a compilation action that parses a source file and performs 
semantic analysis on it, like the existing -fdebug-unparse option does.  Its 
output, however, is preceded by the effective contents of all of the 
non-intrinsic modules on which it depends but does not define, transitively 
preceded by the closure of all of those modules' dependencies.

The output from this option is therefore the analyzed parse tree for a source 
file encapsulated with all of its non-intrinsic module dependencies.  This 
output may be useful for extracting code from large applications for use as an 
attachment to a bug report, or as input to a test case reduction tool for 
problem isolation.

>From f56d89ab6ff37d974a3081792422a69d89266c38 Mon Sep 17 00:00:00 2001
From: Peter Klausler 
Date: Thu, 9 May 2024 14:27:02 -0700
Subject: [PATCH] [flang] New -fdebug-unparse-with-modules option

This option is a compilation action that parses a source file
and performs semantic analysis on it, like the existing -fdebug-unparse
option does.  Its output, however, is preceded by the effective
contents of all of the non-intrinsic modules on which it depends
but does not define, transitively preceded by the closure of all of
those modules' dependencies.

The output from this option is therefore the analyzed parse tree
for a source file encapsulated with all of its non-intrinsic module
dependencies.  This output may be useful for extracting code from
large applications for use as an attachment to a bug report, or
as input to a test case reduction tool for problem isolation.
---
 clang/include/clang/Driver/Options.td |  4 +-
 .../include/flang/Frontend/FrontendActions.h  |  4 ++
 .../include/flang/Frontend/FrontendOptions.h  |  4 ++
 .../flang/Semantics/unparse-with-symbols.h|  4 ++
 flang/lib/Frontend/CompilerInvocation.cpp |  3 ++
 flang/lib/Frontend/FrontendActions.cpp|  9 +
 .../ExecuteCompilerInvocation.cpp |  2 +
 flang/lib/Semantics/mod-file.cpp  | 20 +-
 flang/lib/Semantics/mod-file.h|  3 ++
 flang/lib/Semantics/unparse-with-symbols.cpp  | 38 +++
 flang/test/Driver/unparse-with-modules.f90| 34 +
 11 files changed, 122 insertions(+), 3 deletions(-)
 create mode 100644 flang/test/Driver/unparse-with-modules.f90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 73a2518480e9b..2e6db8d5ebd56 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6644,7 +6644,9 @@ def fdebug_unparse : Flag<["-"], "fdebug-unparse">, 
Group,
   DocBrief<[{Run the parser and the semantic checks. Then unparse the
 parse-tree and output the generated Fortran source file.}]>;
 def fdebug_unparse_with_symbols : Flag<["-"], "fdebug-unparse-with-symbols">, 
Group,
-  HelpText<"Unparse and stop.">;
+  HelpText<"Unparse with symbols and stop.">;
+def fdebug_unparse_with_modules : Flag<["-"], "fdebug-unparse-with-modules">, 
Group,
+  HelpText<"Unparse with dependent modules and stop.">;
 def fdebug_dump_symbols : Flag<["-"], "fdebug-dump-symbols">, 
Group,
   HelpText<"Dump symbols after the semantic analysis">;
 def fdebug_dump_parse_tree : Flag<["-"], "fdebug-dump-parse-tree">, 
Group,
diff --git a/flang/include/flang/Frontend/FrontendActions.h 
b/flang/include/flang/Frontend/FrontendActions.h
index e2e859f3a81bd..7823565eb815f 100644
--- a/flang/include/flang/Frontend/FrontendActions.h
+++ b/flang/include/flang/Frontend/FrontendActions.h
@@ -108,6 +108,10 @@ class DebugUnparseWithSymbolsAction : public 
PrescanAndSemaAction {
   void executeAction() override;
 };
 
+class DebugUnparseWithModulesAction : public PrescanAndSemaAction {
+  void executeAction() override;
+};
+
 class DebugUnparseAction : public PrescanAndSemaAction {
   void executeAction() override;
 };
diff --git a/flang/include/flang/Frontend/FrontendOptions.h 
b/flang/include/flang/Frontend/FrontendOptions.h
index 06b1318f243b0..82ca99672ec61 100644
--- a/flang/include/flang/Frontend/FrontendOptions.h
+++ b/flang/include/flang/Frontend/FrontendOptions.h
@@ -63,6 +63,10 @@ enum ActionKind {
   /// Fortran source file
   DebugUnparseWithSymbols,
 
+  /// Parse, run semantics, and output a Fortran source file preceded
+  /// by all the necessary modules (transitively)
+  DebugUnparseWithModules,
+
   /// Parse, run semantics and then output symbols from semantics
   DebugDumpSymbols,
 
diff --git a/flang/include/flang/Semantics/unparse-with-symbols.h 
b/flang/include/flang/Semantics/unparse-with-symbols.h
index d70110245e2b2..5e18b3fc3063d 100644
--- a/flang/include/flang/Semantics/unparse-with-symbols.h
+++ b/flang/include/flang/Semantics/unparse-with-symbols.h
@@ -21,8 +21,12 @@ struct Program;
 }
 
 namespace Fortran::semantics {
+class SemanticsContext;
 void UnparseWithSymbols(llvm::raw_ostream &, 

[clang] [llvm] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin, fmax and frexp. (PR #88978)

2024-05-09 Thread Zahira Ammarguellat via cfe-commits

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


[clang] [ClangOffloadBundler] make hipv4 and hip compatible (PR #91637)

2024-05-09 Thread Yaxun Liu via cfe-commits

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


[clang] ca39175 - [ClangOffloadBundler] make hipv4 and hip compatible (#91637)

2024-05-09 Thread via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2024-05-09T17:14:43-04:00
New Revision: ca3917538de1deeb0e51f11fbdbe295b6d3768d1

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

LOG: [ClangOffloadBundler] make hipv4 and hip compatible (#91637)

The distinction between the hip and hipv4 offload kinds is historically
based. Originally, these designations might have indicated different
versions of the code object ABI (Application Binary Interface). However,
as the system has evolved, the ABI version is now embedded directly
within the code object itself, making these historical distinctions
irrelevant during the unbundling process. Consequently, hip and hipv4
are treated as compatible in current implementations, facilitating
interchangeable handling of code objects without differentiation based
on offload kind. This change streamlines code management within the
ecosystem.

Added: 


Modified: 
clang/docs/ClangOffloadBundler.rst
clang/lib/Driver/OffloadBundler.cpp
clang/test/Driver/clang-offload-bundler.c
clang/test/Driver/linker-wrapper.c
clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Removed: 




diff  --git a/clang/docs/ClangOffloadBundler.rst 
b/clang/docs/ClangOffloadBundler.rst
index 515e6c00a3b80..3c241027d405c 100644
--- a/clang/docs/ClangOffloadBundler.rst
+++ b/clang/docs/ClangOffloadBundler.rst
@@ -245,7 +245,7 @@ Where:
 object as a data section with the name ``.hip_fatbin``.
 
   hipv4 Offload code object for the HIP language. Used for AMD GPU
-code objects with at least ABI version V4 when the
+code objects with at least ABI version V4 and above when 
the
 ``clang-offload-bundler`` is used to create a *fat binary*
 to be loaded by the HIP runtime. The fat binary can be
 loaded directly from a file, or be embedded in the host 
code
@@ -254,6 +254,14 @@ Where:
   openmpOffload code object for the OpenMP language extension.
   = 
==
 
+Note: The distinction between the `hip` and `hipv4` offload kinds is 
historically based.
+Originally, these designations might have indicated 
diff erent versions of the
+code object ABI. However, as the system has evolved, the ABI version is now 
embedded
+directly within the code object itself, making these historical distinctions 
irrelevant
+during the unbundling process. Consequently, `hip` and `hipv4` are treated as 
compatible
+in current implementations, facilitating interchangeable handling of code 
objects
+without 
diff erentiation based on offload kind.
+
 **target-triple**
 The target triple of the code object. See `Target Triple
 `_.
@@ -295,7 +303,7 @@ Compatibility Rules for Bundle Entry ID
   A code object, specified using its Bundle Entry ID, can be loaded and
   executed on a target processor, if:
 
-  * Their offload kinds are the same.
+  * Their offload kinds are the same or comptible.
   * Their target triples are compatible.
   * Their Target IDs are compatible as defined in 
:ref:`compatibility-target-id`.
 

diff  --git a/clang/lib/Driver/OffloadBundler.cpp 
b/clang/lib/Driver/OffloadBundler.cpp
index 8cc82a0ee7168..191d108e9b739 100644
--- a/clang/lib/Driver/OffloadBundler.cpp
+++ b/clang/lib/Driver/OffloadBundler.cpp
@@ -113,8 +113,11 @@ bool OffloadTargetInfo::isOffloadKindValid() const {
 
 bool OffloadTargetInfo::isOffloadKindCompatible(
 const StringRef TargetOffloadKind) const {
-  if (OffloadKind == TargetOffloadKind)
+  if ((OffloadKind == TargetOffloadKind) ||
+  (OffloadKind == "hip" && TargetOffloadKind == "hipv4") ||
+  (OffloadKind == "hipv4" && TargetOffloadKind == "hip"))
 return true;
+
   if (BundlerConfig.HipOpenmpCompatible) {
 bool HIPCompatibleWithOpenMP = OffloadKind.starts_with_insensitive("hip") 
&&
TargetOffloadKind == "openmp";

diff  --git a/clang/test/Driver/clang-offload-bundler.c 
b/clang/test/Driver/clang-offload-bundler.c
index e492da31abb74..1909ff2d71d03 100644
--- a/clang/test/Driver/clang-offload-bundler.c
+++ b/clang/test/Driver/clang-offload-bundler.c
@@ -505,6 +505,17 @@
 // RUN:   -output=%t.res.tgt1 -input=%t.hip.bundle.bc -unbundle 2>&1 | 
FileCheck %s -check-prefix=NOGFX906
 // NOGFX906: error: Can't find bundles for hip-amdgcn-amd-amdhsa--gfx906
 
+//
+// Check hip and hipv4 are compatible as offload kind.
+//
+// RUN: clang-offload-bundler -type=o -targets=hip-amdgcn-amd-amdhsa--gfx90a 
-input=%t.tgt1 -output=%t.bundle3.o
+// RUN: clang-offload-bundler -type=o 
-targets=hipv4-amdgcn-amd-amdhsa--gfx90a:sramecc-:xnack

[clang] [llvm] [WebAssembly] Implement prototype f32.store_f16 instruction. (PR #91545)

2024-05-09 Thread Brendan Dahl via cfe-commits

https://github.com/brendandahl updated 
https://github.com/llvm/llvm-project/pull/91545

>From adcb77e15d09f466f217d754f6f80aeb729aadc4 Mon Sep 17 00:00:00 2001
From: Brendan Dahl 
Date: Wed, 8 May 2024 23:10:07 +
Subject: [PATCH 1/5] [WebAssembly] Implement prototype f32.store_f16
 instruction.

Adds a builtin and intrinsic for the f32.store_f16 instruction.

The instruction stores an f32 value as an f16 memory.
Specified at:
https://github.com/WebAssembly/half-precision/blob/29a9b9462c9285d4ccc1a5dc39214ddfd1892658/proposals/half-precision/Overview.md

Note: the current spec has f32.store_f16 as opcode 0xFD0121, but this is 
incorrect
and will be changed to 0xFC31 soon.
---
 .../clang/Basic/BuiltinsWebAssembly.def   |  1 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  6 +
 clang/test/CodeGen/builtins-wasm.c|  6 +
 llvm/include/llvm/IR/IntrinsicsWebAssembly.td |  5 
 .../MCTargetDesc/WebAssemblyMCTargetDesc.h|  1 +
 .../WebAssembly/WebAssemblyISelLowering.cpp   |  8 ++
 .../WebAssembly/WebAssemblyInstrMemory.td |  4 +++
 .../CodeGen/WebAssembly/half-precision.ll |  9 +++
 llvm/test/CodeGen/WebAssembly/offset.ll   | 27 +++
 llvm/test/MC/WebAssembly/simd-encodings.s |  3 +++
 10 files changed, 70 insertions(+)

diff --git a/clang/include/clang/Basic/BuiltinsWebAssembly.def 
b/clang/include/clang/Basic/BuiltinsWebAssembly.def
index cf54f8f4422f8..41fadd10e9432 100644
--- a/clang/include/clang/Basic/BuiltinsWebAssembly.def
+++ b/clang/include/clang/Basic/BuiltinsWebAssembly.def
@@ -192,6 +192,7 @@ 
TARGET_BUILTIN(__builtin_wasm_relaxed_dot_bf16x8_add_f32_f32x4, "V4fV8UsV8UsV4f"
 
 // Half-Precision (fp16)
 TARGET_BUILTIN(__builtin_wasm_loadf16_f32, "fh*", "nU", "half-precision")
+TARGET_BUILTIN(__builtin_wasm_storef16_f32, "vfh*", "nU", "half-precision")
 
 // Reference Types builtins
 // Some builtins are custom type-checked - see 't' as part of the third 
argument,
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index e8a6bd050e17e..abb644d8eb506 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -21308,6 +21308,12 @@ Value 
*CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
 Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_loadf16_f32);
 return Builder.CreateCall(Callee, {Addr});
   }
+  case WebAssembly::BI__builtin_wasm_storef16_f32: {
+Value *Val = EmitScalarExpr(E->getArg(0));
+Value *Addr = EmitScalarExpr(E->getArg(1));
+Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_storef16_f32);
+return Builder.CreateCall(Callee, {Val, Addr});
+  }
   case WebAssembly::BI__builtin_wasm_table_get: {
 assert(E->getArg(0)->getType()->isArrayType());
 Value *Table = EmitArrayToPointerDecay(E->getArg(0)).emitRawPointer(*this);
diff --git a/clang/test/CodeGen/builtins-wasm.c 
b/clang/test/CodeGen/builtins-wasm.c
index ab1c6cd494ae5..bcb15969de1c5 100644
--- a/clang/test/CodeGen/builtins-wasm.c
+++ b/clang/test/CodeGen/builtins-wasm.c
@@ -807,6 +807,12 @@ float load_f16_f32(__fp16 *addr) {
   // WEBASSEMBLY: call float @llvm.wasm.loadf16.f32(ptr %{{.*}})
 }
 
+void store_f16_f32(float val, __fp16 *addr) {
+  return __builtin_wasm_storef16_f32(val, addr);
+  // WEBASSEMBLY: tail call void @llvm.wasm.storef16.f32(float %val, ptr 
%{{.*}})
+  // WEBASSEMBLY-NEXT: ret
+}
+
 __externref_t externref_null() {
   return __builtin_wasm_ref_null_extern();
   // WEBASSEMBLY: tail call ptr addrspace(10) @llvm.wasm.ref.null.extern()
diff --git a/llvm/include/llvm/IR/IntrinsicsWebAssembly.td 
b/llvm/include/llvm/IR/IntrinsicsWebAssembly.td
index f8142a8ca9e93..572d334ac9552 100644
--- a/llvm/include/llvm/IR/IntrinsicsWebAssembly.td
+++ b/llvm/include/llvm/IR/IntrinsicsWebAssembly.td
@@ -332,6 +332,11 @@ def int_wasm_loadf16_f32:
 [llvm_ptr_ty],
 [IntrReadMem, IntrArgMemOnly],
  "", [SDNPMemOperand]>;
+def int_wasm_storef16_f32:
+  Intrinsic<[],
+[llvm_float_ty, llvm_ptr_ty],
+[IntrWriteMem, IntrArgMemOnly],
+ "", [SDNPMemOperand]>;
 
 
 
//===--===//
diff --git a/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h 
b/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h
index d3b496ae59179..d4e9fb057c44d 100644
--- a/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h
+++ b/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h
@@ -207,6 +207,7 @@ inline unsigned GetDefaultP2AlignAny(unsigned Opc) {
   WASM_LOAD_STORE(LOAD_LANE_I16x8)
   WASM_LOAD_STORE(STORE_LANE_I16x8)
   WASM_LOAD_STORE(LOAD_F16_F32)
+  WASM_LOAD_STORE(STORE_F16_F32)
   return 1;
   WASM_LOAD_STORE(LOAD_I32)
   WASM_LOAD_STORE(LOAD_F32)
diff --git a/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp 
b/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
index ed52fe53b

[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)

2024-05-09 Thread Justin Cady via cfe-commits


@@ -311,7 +311,12 @@ ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(
 : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine),
   RemoveIncompatibleErrors(RemoveIncompatibleErrors),
   GetFixesFromNotes(GetFixesFromNotes),
-  EnableNolintBlocks(EnableNolintBlocks) {}
+  EnableNolintBlocks(EnableNolintBlocks) {
+
+  if (Context.getOptions().ExcludeHeaderFilterRegex)
+ExcludeHeaderFilter = std::make_unique(
+*Context.getOptions().ExcludeHeaderFilterRegex);

justincady wrote:

What makes you suspect it doesn't work? I did some testing by placing `abort()` 
in an else clause and it caused many unit tests to crash. That leads me to 
believe it remains `std::nullopt` when the option is not specified.

I will do some more thorough testing to confirm.

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


[clang] [llvm] [WebAssembly] Implement prototype f32.store_f16 instruction. (PR #91545)

2024-05-09 Thread Heejin Ahn via cfe-commits

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

LGTM with removing the pure attribute

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


[clang-tools-extra] Add option to exclude headers from clang-tidy analysis (PR #91400)

2024-05-09 Thread Justin Cady via cfe-commits


@@ -311,7 +311,12 @@ ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(
 : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine),
   RemoveIncompatibleErrors(RemoveIncompatibleErrors),
   GetFixesFromNotes(GetFixesFromNotes),
-  EnableNolintBlocks(EnableNolintBlocks) {}
+  EnableNolintBlocks(EnableNolintBlocks) {
+
+  if (Context.getOptions().ExcludeHeaderFilterRegex)
+ExcludeHeaderFilter = std::make_unique(
+*Context.getOptions().ExcludeHeaderFilterRegex);
+}

justincady wrote:

Well, in the initial PR `ExcludeHeaderFilter` mirrored `HeaderFilter` behavior 
exactly. I changed it because @PiotrZSL made a nearly identical comment to 
yours about saving the call to `match` on an empty regex (which I think is 
handled in the latest revision).

I _could_ migrate `HeaderFilter` to mirror the new and improved 
`ExcludeHeaderFilter`...though I worry a bit about this change growing larger 
and larger. What do you think?

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


[clang] [clang-tools-extra] Reapply "[Clang][Sema] Diagnose class member access expressions naming non-existent members of the current instantiation prior to instantiation in the absence of dependent

2024-05-09 Thread Krystian Stasiowski via cfe-commits

sdkrystian wrote:

@dyung Per [[temp.dep.type] p10.11](http://eel.is/c++draft/temp.dep.type#10.11):
> A type is dependent if it is 
> - [...]
> - denoted by a _simple-template-id_ in which either the template name is a 
> template parameter or any of the template arguments is a dependent type or an 
> expression that is type-dependent or value-dependent or is a pack expansion,
> - [...]

In this case, `self` is a typedef for `COneSet` (the injected-class-name of the 
class template). When used as a _type-name_, the injected-class-name of a class 
template is equivalent to a _simple-template-id_ with the template arguments of 
the template parameters of that template. Despite that type _being_ the current 
instantiation, it is still considered to be a dependent type (name lookup has 
special rules when the lookup context is dependent _and_ is the current 
instantiation). 

Since `pSetOther` names a declaration that has a dependent type, 
`SWAP(pSetOther)` is a dependent call.

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


[clang] [lldb] [llvm] [AArch64] move extension information into tablgen (PR #90987)

2024-05-09 Thread Tomas Matheson via cfe-commits

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


[clang] 639a740 - [AArch64] move extension information into tablgen (#90987)

2024-05-09 Thread via cfe-commits

Author: Tomas Matheson
Date: 2024-05-09T21:54:48+01:00
New Revision: 639a740035b732e9bc0f43f3f95d1ce3acf82e1b

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

LOG: [AArch64] move extension information into tablgen (#90987)

Generate TargetParser extension information from tablegen. This includes FMV 
extension information. FMV only extensions are represented by a separate 
tablegen class.

Use MArchName/ArchKindEnumSpelling to avoid renamings.
Cases where there is simply a case difference are handled by
consistently uppercasing the AEK_ name in the emitted code.

Remove some Extensions which were not needed.
These had AEK entries but were never actually used for anything.
They are not present in Extensions[] data.

Added: 


Modified: 
clang/test/Driver/aarch64-implied-sme-features.c
clang/test/Driver/aarch64-implied-sve-features.c
lldb/test/Shell/Commands/command-disassemble-aarch64-extensions.s
llvm/include/llvm/TargetParser/AArch64TargetParser.h
llvm/lib/Target/AArch64/AArch64Features.td
llvm/unittests/TargetParser/TargetParserTest.cpp
llvm/utils/TableGen/ARMTargetDefEmitter.cpp

Removed: 




diff  --git a/clang/test/Driver/aarch64-implied-sme-features.c 
b/clang/test/Driver/aarch64-implied-sme-features.c
index 67836f42f2c02..eca62e2563b78 100644
--- a/clang/test/Driver/aarch64-implied-sme-features.c
+++ b/clang/test/Driver/aarch64-implied-sme-features.c
@@ -14,7 +14,7 @@
 // SME-CONFLICT: "-target-feature" "-bf16"{{.*}} "-target-feature" "-sme"
 
 // RUN: %clang -target aarch64-linux-gnu -march=armv8-a+sme-i16i64 %s -### 
2>&1 | FileCheck %s --check-prefix=SME-I16I64
-// SME-I16I64: "-target-feature" "+bf16"{{.*}} "-target-feature" "+sme-i16i64" 
"-target-feature" "+sme"
+// SME-I16I64: "-target-feature" "+bf16"{{.*}} "-target-feature" "+sme" 
"-target-feature" "+sme-i16i64"
 
 // RUN: %clang -target aarch64-linux-gnu -march=armv8-a+nosme-i16i64 %s -### 
2>&1 | FileCheck %s --check-prefix=NOSME-I16I64
 // NOSME-I16I64-NOT: "-target-feature" "+sme-i16i64"
@@ -23,7 +23,7 @@
 // NOSME-I16I64-NOT: sme-i16i64"
 
 // RUN: %clang -target aarch64-linux-gnu 
-march=armv8-a+sme-i16i64+nosme-i16i64 %s -### 2>&1 | FileCheck %s 
--check-prefix=SME-I16I64-REVERT
-// SME-I16I64-REVERT: "-target-feature" "+bf16"{{.*}} "-target-feature" 
"-sme-i16i64" "-target-feature" "+sme"
+// SME-I16I64-REVERT: "-target-feature" "+bf16"{{.*}} "-target-feature" "+sme" 
"-target-feature" "-sme-i16i64"
 
 // RUN: %clang -target aarch64-linux-gnu -march=armv8-a+nosme-f64f64 %s -### 
2>&1 | FileCheck %s --check-prefix=NOSME-F64F64
 // NOSME-F64F64-NOT: "-target-feature" "+sme-f64f64"
@@ -32,15 +32,15 @@
 // NOSME-F64F64-NOT: sme-f64f64"
 
 // RUN: %clang -target aarch64-linux-gnu 
-march=armv8-a+sme-f64f64+nosme-f64f64 %s -### 2>&1 | FileCheck %s 
--check-prefix=SME-F64F64-REVERT
-// SME-F64F64-REVERT: "-target-feature" "+bf16"{{.*}} "-target-feature" 
"-sme-f64f64" "-target-feature" "+sme"
+// SME-F64F64-REVERT: "-target-feature" "+bf16"{{.*}} "-target-feature" "+sme" 
"-target-feature" "-sme-f64f64"
 
 // RUN: %clang -target aarch64-linux-gnu 
-march=armv8-a+sme-f64f64+nosme-i16i64 %s -### 2>&1 | FileCheck %s 
--check-prefix=SME-SUBFEATURE-MIX
 // SME-SUBFEATURE-MIX-NOT: "+sme-i16i64"
-// SME-SUBFEATURE-MIX: "-target-feature" "+bf16"{{.*}} "-target-feature" 
"+sme-f64f64" "-target-feature" "+sme"
+// SME-SUBFEATURE-MIX: "-target-feature" "+bf16"{{.*}} "-target-feature" 
"+sme" "-target-feature" "+sme-f64f64"
 // SME-SUBFEATURE-MIX-NOT: "+sme-i16i64"
 
 // RUN: %clang -target aarch64-linux-gnu -march=armv8-a+sme-i16i64+nosme %s 
-### 2>&1 | FileCheck %s --check-prefix=SME-SUBFEATURE-CONFLICT1
-// SME-SUBFEATURE-CONFLICT1: "-target-feature" "+bf16"{{.*}} "-target-feature" 
"-sme-i16i64" "-target-feature" "-sme"
+// SME-SUBFEATURE-CONFLICT1: "-target-feature" "+bf16"{{.*}} "-target-feature" 
"-sme" "-target-feature" "-sme-i16i64"
 
 // RUN: %clang -target aarch64-linux-gnu -march=armv8-a+sme-f64f64+nobf16 %s 
-### 2>&1 | FileCheck %s --check-prefix=SME-SUBFEATURE-CONFLICT2
 // SME-SUBFEATURE-CONFLICT2-NOT: "-target-feature" "+bf16"
@@ -48,4 +48,4 @@
 // SME-SUBFEATURE-CONFLICT2-NOT: "-target-feature" "+sme-f64f64"
 
 // RUN: %clang -target aarch64-linux-gnu -march=armv8-a+nosme+sme-i16i64 %s 
-### 2>&1 | FileCheck %s --check-prefix=SME-SUBFEATURE-CONFLICT-REV
-// SME-SUBFEATURE-CONFLICT-REV: "-target-feature" "+bf16"{{.*}} 
"-target-feature" "+sme-i16i64" "-target-feature" "+sme"
+// SME-SUBFEATURE-CONFLICT-REV: "-target-feature" "+bf16"{{.*}} 
"-target-feature" "+sme" "-target-feature" "+sme-i16i64"

diff  --git a/clang/test/Driver/aarch64-implied-sve-features.c 
b/clang/test/Driver/aarch64-implied-sve-features.c
index 9227cd4981c2e..f04e1a785673b 100644
--- a/clang/test/Driver/aarc

[clang] [AArch64] add some more tests for FMV (PR #91490)

2024-05-09 Thread Tomas Matheson via cfe-commits

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


[clang] ddad7c3 - [AArch64] add some more tests for FMV (#91490)

2024-05-09 Thread via cfe-commits

Author: Tomas Matheson
Date: 2024-05-09T21:51:39+01:00
New Revision: ddad7c3c84a8706ad539f1a69660a31a00b411a2

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

LOG: [AArch64] add some more tests for FMV (#91490)

Add a couple of tests to make it clear:
- when FMV should be enabled and disabled by the driver.
- which extensions are enabled/disabled based on the dependencies
specified in TargetParser.

Added: 
clang/test/CodeGen/aarch64-fmv-dependencies.c
clang/test/Driver/aarch64-fmv.c

Modified: 


Removed: 




diff  --git a/clang/test/CodeGen/aarch64-fmv-dependencies.c 
b/clang/test/CodeGen/aarch64-fmv-dependencies.c
new file mode 100644
index 0..ec599e1b3fa76
--- /dev/null
+++ b/clang/test/CodeGen/aarch64-fmv-dependencies.c
@@ -0,0 +1,240 @@
+// Test/document all of the dependencies between possible AArch64 FMV 
extensions.
+// Also test the name mangling.
+
+// RUN: %clang --target=aarch64-linux-gnu --rtlib=compiler-rt -emit-llvm -S -o 
- %s | FileCheck %s
+
+// CHECK: define dso_local i32 @fmv._Maes() #[[ATTR0:[0-9]+]] {
+__attribute__((target_version("aes"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mbf16() #[[bf16_ebf16:[0-9]+]] {
+__attribute__((target_version("bf16"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mbti() #[[bti:[0-9]+]] {
+__attribute__((target_version("bti"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mcrc() #[[crc:[0-9]+]] {
+__attribute__((target_version("crc"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mdgh() #[[ATTR0:[0-9]+]] {
+__attribute__((target_version("dgh"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mdit() #[[dit:[0-9]+]] {
+__attribute__((target_version("dit"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mdotprod() #[[dotprod:[0-9]+]] {
+__attribute__((target_version("dotprod"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mdpb() #[[dpb:[0-9]+]] {
+__attribute__((target_version("dpb"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mdpb2() #[[dpb2:[0-9]+]] {
+__attribute__((target_version("dpb2"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mebf16() #[[bf16_ebf16:[0-9]+]] {
+__attribute__((target_version("ebf16"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mf32mm() #[[f32mm:[0-9]+]] {
+__attribute__((target_version("f32mm"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mf64mm() #[[f64mm:[0-9]+]] {
+__attribute__((target_version("f64mm"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mfcma() #[[fcma:[0-9]+]] {
+__attribute__((target_version("fcma"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mflagm() #[[flagm:[0-9]+]] {
+__attribute__((target_version("flagm"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mflagm2() #[[flagm2:[0-9]+]] {
+__attribute__((target_version("flagm2"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mfp() #[[ATTR0:[0-9]+]] {
+__attribute__((target_version("fp"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mfp16() #[[fp16:[0-9]+]] {
+__attribute__((target_version("fp16"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mfp16fml() #[[fp16fml:[0-9]+]] {
+__attribute__((target_version("fp16fml"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mfrintts() #[[frintts:[0-9]+]] {
+__attribute__((target_version("frintts"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mi8mm() #[[i8mm:[0-9]+]] {
+__attribute__((target_version("i8mm"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mjscvt() #[[jscvt:[0-9]+]] {
+__attribute__((target_version("jscvt"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mls64() #[[ATTR0:[0-9]+]] {
+__attribute__((target_version("ls64"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mls64_accdata() #[[ls64_accdata:[0-9]+]] {
+__attribute__((target_version("ls64_accdata"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mls64_v() #[[ATTR0:[0-9]+]] {
+__attribute__((target_version("ls64_v"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mlse() #[[lse:[0-9]+]] {
+__attribute__((target_version("lse"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mmemtag() #[[ATTR0:[0-9]+]] {
+__attribute__((target_version("memtag"))) int fmv(void) { return 0; }
+
+// CHECK: define dso_local i32 @fmv._Mmemtag2() #[[memtag2:[0-9]+]] {
+__attribute__((target_version("memtag2"))) int fmv(void) { return 0; }
+
+// CHECK: define 

  1   2   3   4   >