[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-19 Thread Vassil Vassilev via cfe-commits

vgvassilev wrote:

> > > Not entirely certain what you're asking, but MSVC CRT does have a 
> > > definition for sized delete:
> > > ```
> > > _CRT_SECURITYCRITICAL_ATTRIBUTE
> > > void __CRTDECL operator delete(void* const block, size_t const) noexcept
> > > {
> > > operator delete(block);
> > > }
> > > ```
> > > 
> > > 
> > > 
> > >   
> > > 
> > > 
> > >   
> > > 
> > > 
> > > 
> > >   
> > > in `crt\src\vcruntime\delete_scalar_size.cpp`
> > 
> > 
> > In that case for this test (or likely the entire interpreter library) we 
> > will have export that symbol with the linker. Something similar is done 
> > here: 
> > https://github.com/llvm/llvm-project/pull/84769/files#diff-d7f5dca2bd540f1b18ba90a66497b6b12e40fd07058b70f0fdec638c8e97406eR14-R71
> >  as part of #84769. Unfortunately, this is the only reliable way as of 
> > today to export crt symbols to the JIT. cc: @lhames, @fsfod.
> 
> So should I wait for landing this PR or is there a workaround to fix this 
> problem?

No, it'd be quite easy for somebody with a windows platform to export only this 
symbol as part of that test and if it works it'd be couple of lines of cmake. I 
am hoping @AaronBallman could give it a shot...

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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-19 Thread Wang Pengcheng via cfe-commits

wangpc-pp wrote:

> > Not entirely certain what you're asking, but MSVC CRT does have a 
> > definition for sized delete:
> > ```
> > _CRT_SECURITYCRITICAL_ATTRIBUTE
> > void __CRTDECL operator delete(void* const block, size_t const) noexcept
> > {
> > operator delete(block);
> > }
> > ```
> > 
> > 
> > 
> >   
> > 
> > 
> >   
> > 
> > 
> > 
> >   
> > in `crt\src\vcruntime\delete_scalar_size.cpp`
> 
> In that case for this test (or likely the entire interpreter library) we will 
> have export that symbol with the linker. Something similar is done here: 
> https://github.com/llvm/llvm-project/pull/84769/files#diff-d7f5dca2bd540f1b18ba90a66497b6b12e40fd07058b70f0fdec638c8e97406eR14-R71
>  as part of #84769. Unfortunately, this is the only reliable way as of today 
> to export crt symbols to the JIT. cc: @lhames, @fsfod.

So should I wait for landing this PR or is there a workaround to fix this 
problem?

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


[clang] [RISCV] Disallow target attribute use in multiversioning (PR #85899)

2024-03-19 Thread Piyou Chen via cfe-commits

https://github.com/BeMg created https://github.com/llvm/llvm-project/pull/85899

For RISC-V target only `target_clones` and `target_version` can enable function 
multiversion(FMV). 

This patch make target attribute trigger redefinition instead of emit FMV.

>From 0bbffb92e7f36957c042cab9a67a483571d9b3f9 Mon Sep 17 00:00:00 2001
From: Piyou Chen 
Date: Mon, 18 Mar 2024 05:07:14 -0700
Subject: [PATCH] [RISCV] Disallow target attribute use in multiversioning

---
 clang/lib/Sema/SemaDecl.cpp | 4 
 1 file changed, 4 insertions(+)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5850cd0ab6b9aa..e543aff77e67ea 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -11853,6 +11853,10 @@ static bool CheckMultiVersionFunction(Sema &S, 
FunctionDecl *NewFD,
   if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
 return false;
 
+  // Target attribute on RISCV is not used for multiversioning
+  if (NewTA && S.getASTContext().getTargetInfo().getTriple().isRISCV())
+return false;
+
   if (!OldDecl || !OldDecl->getAsFunction() ||
   OldDecl->getDeclContext()->getRedeclContext() !=
   NewFD->getDeclContext()->getRedeclContext()) {

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


[clang] [clang][Tooling] Add special symbol mappings for C, starting with size_t (PR #85784)

2024-03-19 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet updated 
https://github.com/llvm/llvm-project/pull/85784

From 8b12e22a01058bcfdcf211b1f64d192d7c5f8463 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Tue, 19 Mar 2024 13:33:35 +0100
Subject: [PATCH 1/3] [clang][Tooling] Add special symbol mappings for C,
 starting with size_t

---
 .../Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc  |  8 
 .../Tooling/Inclusions/Stdlib/StandardLibrary.cpp|  3 ++-
 clang/unittests/Tooling/StandardLibraryTest.cpp  | 12 
 3 files changed, 22 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc

diff --git a/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc 
b/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc
new file mode 100644
index 00..1d9c294d207970
--- /dev/null
+++ b/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc
@@ -0,0 +1,8 @@
+//===-- StdSpecialSymbolMap.inc ---*- C 
-*-===//
+//
+// This is a hand-curated list for C symbols that cannot be parsed/extracted
+// via the include-mapping tool (gen_std.py).
+//
+//===--===//
+
+SYMBOL(size_t, None, )
diff --git a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp 
b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
index adf1b230ff0318..386094fc2992e1 100644
--- a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -55,11 +55,12 @@ static const SymbolHeaderMapping *getMappingPerLang(Lang L) 
{
 }
 
 static int countSymbols(Lang Language) {
-  ArrayRef Symbols;
+  ArrayRef Symbols;
 #define SYMBOL(Name, NS, Header) #NS #Name,
   switch (Language) {
   case Lang::C: {
 static constexpr const char *CSymbols[] = {
+#include "CSpecialSymbolMap.inc"
 #include "CSymbolMap.inc"
 };
 Symbols = CSymbols;
diff --git a/clang/unittests/Tooling/StandardLibraryTest.cpp 
b/clang/unittests/Tooling/StandardLibraryTest.cpp
index edca31649accfa..d93b7d1af82d37 100644
--- a/clang/unittests/Tooling/StandardLibraryTest.cpp
+++ b/clang/unittests/Tooling/StandardLibraryTest.cpp
@@ -185,6 +185,18 @@ TEST(StdlibTest, RecognizerForC99) {
 stdlib::Symbol::named("", "uint8_t", stdlib::Lang::C));
 }
 
+TEST(StdlibTest, SpecialCMappings) {
+  TestInputs Input("typedef char size_t;");
+  Input.Language = TestLanguage::Lang_C99;
+  TestAST AST(Input);
+
+  auto &SizeT = lookup(AST, "size_t");
+  stdlib::Recognizer Recognizer;
+  auto ActualSym = Recognizer(&SizeT);
+  EXPECT_EQ(ActualSym, stdlib::Symbol::named("", "size_t", stdlib::Lang::C));
+  EXPECT_EQ(ActualSym->header()->name(), "");
+}
+
 } // namespace
 } // namespace tooling
 } // namespace clang

From 01f76a373ae64cfad3025bee57fada2368d20aa8 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Wed, 20 Mar 2024 07:43:21 +0100
Subject: [PATCH 2/3] add alternative headers

---
 clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc | 6 ++
 1 file changed, 6 insertions(+)

diff --git a/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc 
b/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc
index 1d9c294d207970..a515f69ea6a8cf 100644
--- a/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc
+++ b/clang/lib/Tooling/Inclusions/Stdlib/CSpecialSymbolMap.inc
@@ -6,3 +6,9 @@
 
//===--===//
 
 SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )
+SYMBOL(size_t, None, )

From bb12119a0b4e0c7ea298e4c8c2cdbdafd9e60641 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Wed, 20 Mar 2024 07:48:31 +0100
Subject: [PATCH 3/3] add assertion into tests and fix it

---
 clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp | 1 +
 clang/unittests/Tooling/StandardLibraryTest.cpp | 1 +
 2 files changed, 2 insertions(+)

diff --git a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp 
b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
index 386094fc2992e1..0832bcf66145fa 100644
--- a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -148,6 +148,7 @@ static int initialize(Lang Language) {
   switch (Language) {
   case Lang::C: {
 static constexpr Symbol CSymbols[] = {
+#include "CSpecialSymbolMap.inc"
 #include "CSymbolMap.inc"
 };
 for (const Symbol &S : CSymbols)
diff --git a/clang/unittests/Tooling/StandardLibraryTest.cpp 
b/clang/unittests/Tooling/StandardLibraryTest.cpp
index d93b7d1af82d37..e4c109f3d580d1 100644
--- a/clang/unittests/Tooling/StandardLibraryTest.cpp
+++ b/clang/unittests/Tooling/StandardLibraryTest.cpp
@@ -193,6 +193,7 @@ TEST(StdlibTest, SpecialCMappings) {
   auto &SizeT = lookup(AST, "size_t");
   stdlib::Recognizer Recognizer;
   auto ActualSym = Recogniz

[clang] [CMake] Change GCC_INSTALL_PREFIX from warning to fatal error (PR #85891)

2024-03-19 Thread Petr Hosek via cfe-commits

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


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


[clang] [X86][Headers] Specify result of NaN comparisons (PR #85862)

2024-03-19 Thread via cfe-commits

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

This looks okay, but please consider my comments.

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


[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits


@@ -439,82 +444,247 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // Bitfields that share parts of a single byte are, of necessity, placed in
+  // the same access unit. That unit will encompass a consecutive run where
+  // adjacent bitfields share parts of a byte. (The first bitfield of such an
+  // access unit will start at the beginning of a byte.)
+
+  // We then try and accumulate adjacent access units when the combined unit is
+  // naturally sized, no larger than a register, and (on a strict alignment
+  // ISA), naturally aligned. Note that this requires lookahead to one or more
+  // subsequent access units. For instance, consider a 2-byte access-unit
+  // followed by 2 1-byte units. We can merge that into a 4-byte access-unit,
+  // but we would not want to merge a 2-byte followed by a single 1-byte (and 
no
+  // available tail padding). We keep track of the best access unit seen so 
far,
+  // and use that when we determine we cannot accumulate any more. Then we 
start
+  // again at the bitfield following that best one.
+
+  // The accumulation is also prevented when:
+  // *) it would cross a character-aigned zero-width bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  // Data about the start of the span we're accumulating to create an access
+  // unit from. Begin is the first bitfie

[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits


@@ -439,82 +444,247 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // Bitfields that share parts of a single byte are, of necessity, placed in
+  // the same access unit. That unit will encompass a consecutive run where
+  // adjacent bitfields share parts of a byte. (The first bitfield of such an
+  // access unit will start at the beginning of a byte.)
+
+  // We then try and accumulate adjacent access units when the combined unit is
+  // naturally sized, no larger than a register, and (on a strict alignment
+  // ISA), naturally aligned. Note that this requires lookahead to one or more
+  // subsequent access units. For instance, consider a 2-byte access-unit
+  // followed by 2 1-byte units. We can merge that into a 4-byte access-unit,
+  // but we would not want to merge a 2-byte followed by a single 1-byte (and 
no
+  // available tail padding). We keep track of the best access unit seen so 
far,
+  // and use that when we determine we cannot accumulate any more. Then we 
start
+  // again at the bitfield following that best one.
+
+  // The accumulation is also prevented when:
+  // *) it would cross a character-aigned zero-width bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  // Data about the start of the span we're accumulating to create an access
+  // unit from. Begin is the first bitfie

[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits


@@ -439,82 +444,247 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // Bitfields that share parts of a single byte are, of necessity, placed in
+  // the same access unit. That unit will encompass a consecutive run where
+  // adjacent bitfields share parts of a byte. (The first bitfield of such an
+  // access unit will start at the beginning of a byte.)
+
+  // We then try and accumulate adjacent access units when the combined unit is
+  // naturally sized, no larger than a register, and (on a strict alignment
+  // ISA), naturally aligned. Note that this requires lookahead to one or more
+  // subsequent access units. For instance, consider a 2-byte access-unit
+  // followed by 2 1-byte units. We can merge that into a 4-byte access-unit,
+  // but we would not want to merge a 2-byte followed by a single 1-byte (and 
no
+  // available tail padding). We keep track of the best access unit seen so 
far,
+  // and use that when we determine we cannot accumulate any more. Then we 
start
+  // again at the bitfield following that best one.
+
+  // The accumulation is also prevented when:
+  // *) it would cross a character-aigned zero-width bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  // Data about the start of the span we're accumulating to create an access
+  // unit from. Begin is the first bitfie

[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits


@@ -439,82 +444,247 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // Bitfields that share parts of a single byte are, of necessity, placed in
+  // the same access unit. That unit will encompass a consecutive run where
+  // adjacent bitfields share parts of a byte. (The first bitfield of such an
+  // access unit will start at the beginning of a byte.)
+
+  // We then try and accumulate adjacent access units when the combined unit is
+  // naturally sized, no larger than a register, and (on a strict alignment
+  // ISA), naturally aligned. Note that this requires lookahead to one or more
+  // subsequent access units. For instance, consider a 2-byte access-unit
+  // followed by 2 1-byte units. We can merge that into a 4-byte access-unit,
+  // but we would not want to merge a 2-byte followed by a single 1-byte (and 
no
+  // available tail padding). We keep track of the best access unit seen so 
far,
+  // and use that when we determine we cannot accumulate any more. Then we 
start
+  // again at the bitfield following that best one.
+
+  // The accumulation is also prevented when:
+  // *) it would cross a character-aigned zero-width bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  // Data about the start of the span we're accumulating to create an access
+  // unit from. Begin is the first bitfie

[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits


@@ -439,82 +444,247 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // Bitfields that share parts of a single byte are, of necessity, placed in
+  // the same access unit. That unit will encompass a consecutive run where
+  // adjacent bitfields share parts of a byte. (The first bitfield of such an
+  // access unit will start at the beginning of a byte.)
+
+  // We then try and accumulate adjacent access units when the combined unit is
+  // naturally sized, no larger than a register, and (on a strict alignment
+  // ISA), naturally aligned. Note that this requires lookahead to one or more
+  // subsequent access units. For instance, consider a 2-byte access-unit
+  // followed by 2 1-byte units. We can merge that into a 4-byte access-unit,
+  // but we would not want to merge a 2-byte followed by a single 1-byte (and 
no
+  // available tail padding). We keep track of the best access unit seen so 
far,
+  // and use that when we determine we cannot accumulate any more. Then we 
start
+  // again at the bitfield following that best one.
+
+  // The accumulation is also prevented when:
+  // *) it would cross a character-aigned zero-width bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  // Data about the start of the span we're accumulating to create an access
+  // unit from. Begin is the first bitfie

[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits

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


[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits


@@ -439,82 +444,247 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // Bitfields that share parts of a single byte are, of necessity, placed in
+  // the same access unit. That unit will encompass a consecutive run where
+  // adjacent bitfields share parts of a byte. (The first bitfield of such an
+  // access unit will start at the beginning of a byte.)
+
+  // We then try and accumulate adjacent access units when the combined unit is
+  // naturally sized, no larger than a register, and (on a strict alignment
+  // ISA), naturally aligned. Note that this requires lookahead to one or more
+  // subsequent access units. For instance, consider a 2-byte access-unit
+  // followed by 2 1-byte units. We can merge that into a 4-byte access-unit,
+  // but we would not want to merge a 2-byte followed by a single 1-byte (and 
no
+  // available tail padding). We keep track of the best access unit seen so 
far,
+  // and use that when we determine we cannot accumulate any more. Then we 
start
+  // again at the bitfield following that best one.
+
+  // The accumulation is also prevented when:
+  // *) it would cross a character-aigned zero-width bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  // Data about the start of the span we're accumulating to create an access
+  // unit from. Begin is the first bitfie

[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits


@@ -439,82 +444,247 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // Bitfields that share parts of a single byte are, of necessity, placed in
+  // the same access unit. That unit will encompass a consecutive run where
+  // adjacent bitfields share parts of a byte. (The first bitfield of such an
+  // access unit will start at the beginning of a byte.)
+
+  // We then try and accumulate adjacent access units when the combined unit is
+  // naturally sized, no larger than a register, and (on a strict alignment
+  // ISA), naturally aligned. Note that this requires lookahead to one or more
+  // subsequent access units. For instance, consider a 2-byte access-unit
+  // followed by 2 1-byte units. We can merge that into a 4-byte access-unit,
+  // but we would not want to merge a 2-byte followed by a single 1-byte (and 
no
+  // available tail padding). We keep track of the best access unit seen so 
far,
+  // and use that when we determine we cannot accumulate any more. Then we 
start
+  // again at the bitfield following that best one.
+
+  // The accumulation is also prevented when:
+  // *) it would cross a character-aigned zero-width bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  // Data about the start of the span we're accumulating to create an access
+  // unit from. Begin is the first bitfie

[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits

https://github.com/rjmccall commented:

This looks great, thanks!  I have a few editorial nits, and there's an 
assertion that seems off, but otherwise this looks ready to go.

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


[clang] [clang] Better bitfield access units (PR #65742)

2024-03-19 Thread John McCall via cfe-commits


@@ -439,82 +444,247 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
 }
-return;
+return Field;
   }
 
-  // Check if OffsetInRecord (the size in bits of the current run) is better
-  // as a single field run. When OffsetInRecord has legal integer width, and
-  // its bitfield offset is naturally aligned, it is better to make the
-  // bitfield a separate storage component so as it can be accessed directly
-  // with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
-  uint64_t StartBitOffset) {
-if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
-  return false;
-if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
-!DataLayout.fitsInLegalInteger(OffsetInRecord))
-  return false;
-// Make sure StartBitOffset is naturally aligned if it is treated as an
-// IType integer.
-if (StartBitOffset %
-Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
-0)
-  return false;
-return true;
-  };
+  // The SysV ABI can overlap bitfield storage units with both other bitfield
+  // storage units /and/ other non-bitfield data members. Accessing a sequence
+  // of bitfields mustn't interfere with adjacent non-bitfields -- they're
+  // permitted to be accessed in separate threads for instance.
+
+  // We split runs of bit-fields into a sequence of "access units". When we 
emit
+  // a load or store of a bit-field, we'll load/store the entire containing
+  // access unit. As mentioned, the standard requires that these loads and
+  // stores must not interfere with accesses to other memory locations, and it
+  // defines the bit-field's memory location as the current run of
+  // non-zero-width bit-fields. So an access unit must never overlap with
+  // non-bit-field storage or cross a zero-width bit-field. Otherwise, we're
+  // free to draw the lines as we see fit.
+
+  // Drawing these lines well can be complicated. LLVM generally can't modify a
+  // program to access memory that it didn't before, so using very narrow 
access
+  // units can prevent the compiler from using optimal access patterns. For
+  // example, suppose a run of bit-fields occupies four bytes in a struct. If 
we
+  // split that into four 1-byte access units, then a sequence of assignments
+  // that doesn't touch all four bytes may have to be emitted with multiple
+  // 8-bit stores instead of a single 32-bit store. On the other hand, if we 
use
+  // very wide access units, we may find ourselves emitting accesses to
+  // bit-fields we didn't really need to touch, just because LLVM was unable to
+  // clean up after us.
+
+  // It is desirable to have access units be aligned powers of 2 no larger than
+  // a register. (On non-strict alignment ISAs, the alignment requirement can 
be
+  // dropped.) A three byte access unit will be accessed using 2-byte and 
1-byte
+  // accesses and bit manipulation. If no bitfield straddles across the two
+  // separate accesses, it is better to have separate 2-byte and 1-byte access
+  // units, as then LLVM will not generate unnecessary memory accesses, or bit
+  // manipulation. Similarly, on a strict-alignment architecture, it is better
+  // to keep access-units naturally aligned, to avoid similar bit
+  // manipulation synthesizing larger unaligned accesses.
+
+  // Bitfields that share parts of a single byte are, of necessity, placed in
+  // the same access unit. That unit will encompass a consecutive run where
+  // adjacent bitfields share parts of a byte. (The first bitfield of such an
+  // access unit will start at the beginning of a byte.)
+
+  // We then try and accumulate adjacent access units when the combined unit is
+  // naturally sized, no larger than a register, and (on a strict alignment
+  // ISA), naturally aligned. Note that this requires lookahead to one or more
+  // subsequent access units. For instance, consider a 2-byte access-unit
+  // followed by 2 1-byte units. We can merge that into a 4-byte access-unit,
+  // but we would not want to merge a 2-byte followed by a single 1-byte (and 
no
+  // available tail padding). We keep track of the best access unit seen so 
far,
+  // and use that when we determine we cannot accumulate any more. Then we 
start
+  // again at the bitfield following that best one.
+
+  // The accumulation is also prevented when:
+  // *) it would cross a character-aigned zero-width bitfield, or
+  // *) fine-grained bitfield access option is in effect.
+
+  CharUnits RegSize =
+  bitsToCharUnits(Context.getTargetInfo().getRegisterWidth());
+  unsigned CharBits = Context.getCharWidth();
+
+  // Data about the start of the span we're accumulating to create an access
+  // unit from. Begin is the first bitfie

[clang] [llvm] MIPS: Support -m(no-)unaligned-access for r6 (PR #85174)

2024-03-19 Thread YunQiang Su via cfe-commits

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


[clang] d7e28cd - MIPS: Support -m(no-)unaligned-access for r6 (#85174)

2024-03-19 Thread via cfe-commits

Author: YunQiang Su
Date: 2024-03-20T14:18:24+08:00
New Revision: d7e28cd82bd3141093f96f7ce2e7b36f1b115fad

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

LOG: MIPS: Support -m(no-)unaligned-access for r6 (#85174)

MIPSr6 ISA requires normal load/store instructions support
misunaligned memory access, while it is not always do so
by hardware. On some microarchitectures or some corner cases
it may need support by OS.

Don't confuse with pre-R6's lwl/lwr famlily: MIPSr6 doesn't
support them, instead, r6 requires lw instruction support
misunaligned memory access. So, if -mstrict-align is used for
pre-R6, lwl/lwr won't be disabled.

If -mstrict-align is used for r6 and the access is not well
aligned, some lb/lh instructions will be used to replace lw.
This is useful for OS kernels.

To be back-compatible with GCC, -m(no-)unaligned-access are also
added as Neg-Alias of -m(no-)strict-align.

Added: 
llvm/test/CodeGen/Mips/no-unaligned-access-r6.ll

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Arch/Mips.cpp
clang/test/Driver/mips-features.c
llvm/lib/Target/Mips/Mips.td
llvm/lib/Target/Mips/MipsISelLowering.cpp
llvm/lib/Target/Mips/MipsSEISelLowering.cpp
llvm/lib/Target/Mips/MipsSubtarget.cpp
llvm/lib/Target/Mips/MipsSubtarget.h
llvm/test/CodeGen/Mips/msa/f16-llvm-ir.ll

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 29c226f4bd8da7..9b5125ecfed8b3 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4704,9 +4704,9 @@ def mrvv_vector_bits_EQ : Joined<["-"], 
"mrvv-vector-bits=">, Group,
 " (RISC-V only)")>;
 
 def munaligned_access : Flag<["-"], "munaligned-access">, Group,
-  HelpText<"Allow memory accesses to be unaligned (AArch32 only)">;
+  HelpText<"Allow memory accesses to be unaligned (AArch32/MIPSr6 only)">;
 def mno_unaligned_access : Flag<["-"], "mno-unaligned-access">, Group,
-  HelpText<"Force all memory accesses to be aligned (AArch32 only)">;
+  HelpText<"Force all memory accesses to be aligned (AArch32/MIPSr6 only)">;
 def munaligned_symbols : Flag<["-"], "munaligned-symbols">, Group,
   HelpText<"Expect external char-aligned symbols to be without ABI alignment 
(SystemZ only)">;
 def mno_unaligned_symbols : Flag<["-"], "mno-unaligned-symbols">, 
Group,

diff  --git a/clang/lib/Driver/ToolChains/Arch/Mips.cpp 
b/clang/lib/Driver/ToolChains/Arch/Mips.cpp
index fe9d112b8800b1..74a8874a3ea2b7 100644
--- a/clang/lib/Driver/ToolChains/Arch/Mips.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/Mips.cpp
@@ -341,6 +341,15 @@ void mips::getMIPSTargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
"dspr2");
   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
"msa");
+  if (Arg *A = Args.getLastArg(
+  options::OPT_mstrict_align, options::OPT_mno_strict_align,
+  options::OPT_mno_unaligned_access, options::OPT_munaligned_access)) {
+if (A->getOption().matches(options::OPT_mstrict_align) ||
+A->getOption().matches(options::OPT_mno_unaligned_access))
+  Features.push_back(Args.MakeArgString("+strict-align"));
+else
+  Features.push_back(Args.MakeArgString("-strict-align"));
+  }
 
   // Add the last -mfp32/-mfpxx/-mfp64, if none are given and the ABI is O32
   // pass -mfpxx, or if none are given and fp64a is default, pass fp64 and

diff  --git a/clang/test/Driver/mips-features.c 
b/clang/test/Driver/mips-features.c
index fd06b1400c3123..5e92dccaa02abb 100644
--- a/clang/test/Driver/mips-features.c
+++ b/clang/test/Driver/mips-features.c
@@ -462,3 +462,29 @@
 // RUN: -mrelax-pic-calls -mno-relax-pic-calls 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NO-RELAX-PIC-CALLS %s
 // CHECK-NO-RELAX-PIC-CALLS: "-mllvm" "-mips-jalr-reloc=0"
+//
+// -mno-unaligned-access
+// RUN: %clang -target mips-unknown-linux-gnu -### -c %s \
+// RUN: -munaligned-access -mno-strict-align \
+// RUN: -mno-unaligned-access 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-STRICT-ALIGN %s
+// CHECK-STRICT-ALIGN: "-target-feature" "+strict-align"
+//
+// -munaligned-access
+// RUN: %clang -target mips-unknown-linux-gnu -### -c %s \
+// RUN: -mno-unaligned-access -mstrict-align \
+// RUN: -munaligned-access 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-STRICT-ALIGN %s
+// CHECK-NO-STRICT-ALIGN: "-target-feature" "-strict-align"
+//
+// -mstrict-align
+// RUN: %clang -target mips-unknown-linux-gnu -### -c %s \
+// RUN: -munaligned-access -mno-strict-align \
+// RUN: -mstrict-align 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-STRICT-ALIGN %s
+//
+// -mno-strict-align
+// RUN: %clang -tar

[clang] [X86][Headers] Specify result of NaN comparisons (PR #85862)

2024-03-19 Thread via cfe-commits


@@ -513,7 +526,7 @@ static __inline__ __m128d __DEFAULT_FN_ATTRS 
_mm_cmpge_pd(__m128d __a,
 ///operand are ordered with respect to those in the second operand.
 ///
 ///A pair of double-precision values are "ordered" with respect to each

craigflores wrote:

Line 528: Remove the quotation marks around "ordered"? What do they add? Note 
that there are other instances of this (as well as "unordered" where the 
quotation marks are inserted) that I have not commented on.

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


[clang] [X86][Headers] Specify result of NaN comparisons (PR #85862)

2024-03-19 Thread via cfe-commits

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


[clang] [X86][Headers] Specify result of NaN comparisons (PR #85862)

2024-03-19 Thread via cfe-commits

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


[clang] [X86][Headers] Specify result of NaN comparisons (PR #85862)

2024-03-19 Thread via cfe-commits


@@ -4743,7 +4771,9 @@ static __inline__ __m128d __DEFAULT_FN_ATTRS 
_mm_castsi128_pd(__m128i __a) {
 ///128-bit vectors of [2 x double], using the operation specified by the
 ///immediate integer operand.
 ///
-///Each comparison yields 0x0 for false, 0x for true.
+///Each comparison returns 0x0 for false, 0x for true.
+///If either value in a comparison is NaN, comparisons marked as ordered

craigflores wrote:

Say instead: "comparisons that are ordered return false, and comparisons that 
are unordered return true"? If no, I don't care for marked/unmarked. There are 
other instances of marked/unmarked that I have not flagged.

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


[clang] [Clang][Sema]: Allow flexible arrays in unions and alone in structs (PR #84428)

2024-03-19 Thread Kees Cook via cfe-commits

https://github.com/kees updated https://github.com/llvm/llvm-project/pull/84428

>From eb5138b45fa450737600050ad8dabdcb27513d42 Mon Sep 17 00:00:00 2001
From: Kees Cook 
Date: Thu, 7 Mar 2024 17:03:09 -0800
Subject: [PATCH 1/5] [Clang][Sema]: Allow flexible arrays in unions and alone
 in structs

GNU and MSVC have extensions where flexible array members (or their
equivalent) can be in unions or alone in structs. This is already fully
supported in Clang through the 0-sized array ("fake flexible array")
extension or when C99 flexible array members have been syntactically
obfuscated.

Clang needs to explicitly allow these extensions directly for C99
flexible arrays, since they are common code patterns in active use by the
Linux kernel (and other projects). Such projects have been using either
0-sized arrays (which is considered deprecated in favor of C99 flexible
array members) or via obfuscated syntax, both of which complicate their
code bases.

For example, these do not error by default:

union one {
int a;
int b[0];
};

union two {
int a;
struct {
struct { } __empty;
int b[];
};
};

But this does:

union three {
int a;
int b[];
};

Remove the default error diagnostics for this but continue to provide
warnings under Microsoft or GNU extensions checks. This will allow for
a seamless transition for code bases away from 0-sized arrays without
losing existing code patterns. Add explicit checking for the warnings
under various constructions.

Fixes #84565
---
 clang/docs/ReleaseNotes.rst   |  3 ++
 .../clang/Basic/DiagnosticSemaKinds.td|  5 --
 clang/lib/Sema/SemaDecl.cpp   |  8 +--
 clang/test/C/drs/dr5xx.c  |  2 +-
 clang/test/Sema/flexible-array-in-union.c | 53 +--
 clang/test/Sema/transparent-union.c   |  4 +-
 6 files changed, 57 insertions(+), 18 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1b901a27fd19d1..960ab7e021cf2f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -214,6 +214,9 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses lambda function expressions being implicitly cast to 
boolean values, under ``-Wpointer-bool-conversion``.
   Fixes #GH82512.
 
+- ``-Wmicrosoft`` or ``-Wgnu`` is now required to diagnose C99 flexible
+  array members in a union or alone in a struct.
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c8dfdc08f5ea07..f09121b8c7ec8f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6447,9 +6447,6 @@ def ext_c99_flexible_array_member : Extension<
 def err_flexible_array_virtual_base : Error<
   "flexible array member %0 not allowed in "
   "%select{struct|interface|union|class|enum}1 which has a virtual base 
class">;
-def err_flexible_array_empty_aggregate : Error<
-  "flexible array member %0 not allowed in otherwise empty "
-  "%select{struct|interface|union|class|enum}1">;
 def err_flexible_array_has_nontrivial_dtor : Error<
   "flexible array member %0 of type %1 with non-trivial destruction">;
 def ext_flexible_array_in_struct : Extension<
@@ -6464,8 +6461,6 @@ def ext_flexible_array_empty_aggregate_ms : Extension<
   "flexible array member %0 in otherwise empty "
   "%select{struct|interface|union|class|enum}1 is a Microsoft extension">,
   InGroup;
-def err_flexible_array_union : Error<
-  "flexible array member %0 in a union is not allowed">;
 def ext_flexible_array_union_ms : Extension<
   "flexible array member %0 in a union is a Microsoft extension">,
   InGroup;
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 67e56a917a51de..053122b588246b 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19357,15 +19357,11 @@ void Sema::ActOnFields(Scope *S, SourceLocation 
RecLoc, Decl *EnclosingDecl,
 } else if (Record->isUnion())
   DiagID = getLangOpts().MicrosoftExt
? diag::ext_flexible_array_union_ms
-   : getLangOpts().CPlusPlus
- ? diag::ext_flexible_array_union_gnu
- : diag::err_flexible_array_union;
+   : diag::ext_flexible_array_union_gnu;
 else if (NumNamedMembers < 1)
   DiagID = getLangOpts().MicrosoftExt
? diag::ext_flexible_array_empty_aggregate_ms
-   : getLangOpts().CPlusPlus
- ? diag::ext_flexible_array_empty_aggregate_gnu
- : diag::err_flexible_array_empty_aggregate;
+   : diag::ext_flexible_array_empty_aggregate_gnu;
 
 if (DiagID)
   Diag(FD->getLocatio

[clang] [llvm] [InstCombine] Canonicalize `(sitofp x)` -> `(uitofp x)` if `x >= 0` (PR #82404)

2024-03-19 Thread via cfe-commits

goldsteinn wrote:

> Heads up: we noticed at google that this is causing the following test to 
> fail:
> 
> https://github.com/google/swiftshader/blob/master/tests/ReactorUnitTests/ReactorUnitTests.cpp#L1312
> 
> I need to put a more proper reproducer, but thought that at least posting the 
> heads-up might be faster to unblock us and maybe the problem is clear. I see 
> that adding a flag vs reverting is already brought up in the last comment, 
> what's the plan for that ?

Reverted with: 
https://github.com/llvm/llvm-project/commit/6960ace534c4021301dd5a9933ca06ba96edea23

If you can get the repro though, that would still be useful for when I revisit.

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


[clang] 6960ace - Revert "[InstCombine] Canonicalize `(sitofp x)` -> `(uitofp x)` if `x >= 0`"

2024-03-19 Thread Noah Goldstein via cfe-commits

Author: Noah Goldstein
Date: 2024-03-20T00:50:45-05:00
New Revision: 6960ace534c4021301dd5a9933ca06ba96edea23

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

LOG: Revert "[InstCombine] Canonicalize `(sitofp x)` -> `(uitofp x)` if `x >= 
0`"

This reverts commit d80d5b923c6f611590a12543bdb33e0c16044d44.

It wasn't a particularly important transform to begin with and caused
some codegen regressions on targets that prefer `sitofp` so dropping.

Might re-visit along with adding `nneg` flag to `uitofp` so its easily
reversable for the backend.

Added: 


Modified: 
clang/test/Headers/__clang_hip_math.hip
llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
llvm/test/Transforms/InstCombine/add-sitofp.ll
llvm/test/Transforms/InstCombine/binop-itofp.ll
llvm/test/Transforms/InstCombine/clamp-to-minmax.ll
llvm/test/Transforms/InstCombine/fpcast.ll
llvm/test/Transforms/InstCombine/minmax-fold.ll
llvm/test/Transforms/InstCombine/minmax-fp.ll
llvm/test/Transforms/InstCombine/pr27236.ll
llvm/test/Transforms/LoopVectorize/X86/float-induction-x86.ll
llvm/test/Transforms/LoopVectorize/float-induction.ll

Removed: 




diff  --git a/clang/test/Headers/__clang_hip_math.hip 
b/clang/test/Headers/__clang_hip_math.hip
index 701f93853ab93c..37099de74fb8ec 100644
--- a/clang/test/Headers/__clang_hip_math.hip
+++ b/clang/test/Headers/__clang_hip_math.hip
@@ -1685,7 +1685,7 @@ extern "C" __device__ double test_j1(double x) {
 // DEFAULT-NEXT:[[__X1_0_I3:%.*]] = phi float [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // DEFAULT-NEXT:[[__X0_0_I2:%.*]] = phi float [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ [[CALL_I_I]], [[IF_END4_I]] ]
 // DEFAULT-NEXT:[[MUL_I:%.*]] = shl nuw nsw i32 [[__I_0_I4]], 1
-// DEFAULT-NEXT:[[CONV_I:%.*]] = uitofp i32 [[MUL_I]] to float
+// DEFAULT-NEXT:[[CONV_I:%.*]] = sitofp i32 [[MUL_I]] to float
 // DEFAULT-NEXT:[[DIV_I:%.*]] = fdiv contract float [[CONV_I]], [[Y]]
 // DEFAULT-NEXT:[[MUL8_I:%.*]] = fmul contract float [[__X1_0_I3]], 
[[DIV_I]]
 // DEFAULT-NEXT:[[SUB_I]] = fsub contract float [[MUL8_I]], [[__X0_0_I2]]
@@ -1718,7 +1718,7 @@ extern "C" __device__ double test_j1(double x) {
 // FINITEONLY-NEXT:[[__X1_0_I3:%.*]] = phi float [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // FINITEONLY-NEXT:[[__X0_0_I2:%.*]] = phi float [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ [[CALL_I_I]], [[IF_END4_I]] ]
 // FINITEONLY-NEXT:[[MUL_I:%.*]] = shl nuw nsw i32 [[__I_0_I4]], 1
-// FINITEONLY-NEXT:[[CONV_I:%.*]] = uitofp i32 [[MUL_I]] to float
+// FINITEONLY-NEXT:[[CONV_I:%.*]] = sitofp i32 [[MUL_I]] to float
 // FINITEONLY-NEXT:[[DIV_I:%.*]] = fdiv nnan ninf contract float 
[[CONV_I]], [[Y]]
 // FINITEONLY-NEXT:[[MUL8_I:%.*]] = fmul nnan ninf contract float 
[[__X1_0_I3]], [[DIV_I]]
 // FINITEONLY-NEXT:[[SUB_I]] = fsub nnan ninf contract float [[MUL8_I]], 
[[__X0_0_I2]]
@@ -1751,7 +1751,7 @@ extern "C" __device__ double test_j1(double x) {
 // APPROX-NEXT:[[__X1_0_I3:%.*]] = phi float [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // APPROX-NEXT:[[__X0_0_I2:%.*]] = phi float [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ [[CALL_I_I]], [[IF_END4_I]] ]
 // APPROX-NEXT:[[MUL_I:%.*]] = shl nuw nsw i32 [[__I_0_I4]], 1
-// APPROX-NEXT:[[CONV_I:%.*]] = uitofp i32 [[MUL_I]] to float
+// APPROX-NEXT:[[CONV_I:%.*]] = sitofp i32 [[MUL_I]] to float
 // APPROX-NEXT:[[DIV_I:%.*]] = fdiv contract float [[CONV_I]], [[Y]]
 // APPROX-NEXT:[[MUL8_I:%.*]] = fmul contract float [[__X1_0_I3]], 
[[DIV_I]]
 // APPROX-NEXT:[[SUB_I]] = fsub contract float [[MUL8_I]], [[__X0_0_I2]]
@@ -1788,7 +1788,7 @@ extern "C" __device__ float test_jnf(int x, float y) {
 // DEFAULT-NEXT:[[__X1_0_I3:%.*]] = phi double [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // DEFAULT-NEXT:[[__X0_0_I2:%.*]] = phi double [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ [[CALL_I_I]], [[IF_END4_I]] ]
 // DEFAULT-NEXT:[[MUL_I:%.*]] = shl nuw nsw i32 [[__I_0_I4]], 1
-// DEFAULT-NEXT:[[CONV_I:%.*]] = uitofp i32 [[MUL_I]] to double
+// DEFAULT-NEXT:[[CONV_I:%.*]] = sitofp i32 [[MUL_I]] to double
 // DEFAULT-NEXT:[[DIV_I:%.*]] = fdiv contract double [[CONV_I]], [[Y]]
 // DEFAULT-NEXT:[[MUL8_I:%.*]] = fmul contract double [[__X1_0_I3]], 
[[DIV_I]]
 // DEFAULT-NEXT:[[SUB_I]] = fsub contract double [[MUL8_I]], [[__X0_0_I2]]
@@ -1821,7 +1821,7 @@ extern "C" __device__ float test_jnf(int x, float y) {
 // FINITEONLY-NEXT:[[__X1_0_I3:%.*]] = phi double [ [[SUB_I:%.*]], 
[[FOR_BODY_I]] ], [ [[CALL_I21_I]], [[IF_END4_I]] ]
 // FINITEONLY-NEXT:[[__X0_0_I2:%.*]] = phi double [ [[__X1_0_I3]], 
[[FOR_BODY_I]] ], [ 

[clang] [X86_64] fix empty structure vaarg in c++ (PR #77907)

2024-03-19 Thread via cfe-commits

https://github.com/hstk30-hw updated 
https://github.com/llvm/llvm-project/pull/77907

>From 9f8515c020ba509ddd305d49883b8c622bfc21b5 Mon Sep 17 00:00:00 2001
From: Longsheng Mou 
Date: Fri, 12 Jan 2024 18:24:08 +0800
Subject: [PATCH] [X86_64] fix empty structure vaarg in c++

SizeInBytes of empty structure is 0 in C, while 1 in C++.
And empty structure argument of the function is ignored
in X86_64 backend.As a result, the value of variable
arguments in C++ is incorrect.So we should just make a
temporary and return its address.
---
 clang/lib/CodeGen/Targets/X86.cpp  |  4 
 clang/test/CodeGenCXX/x86_64-vaarg.cpp | 23 +++
 2 files changed, 27 insertions(+)
 create mode 100644 clang/test/CodeGenCXX/x86_64-vaarg.cpp

diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index d053f41ab168f5..936ca16f1565fa 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -3014,6 +3014,10 @@ Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, 
Address VAListAddr,
   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
/*isNamedArg*/false);
 
+  // Empty records are ignored for parameter passing purposes.
+  if (AI.isIgnore())
+return CGF.CreateMemTemp(Ty);
+
   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
   // in the registers. If not go to step 7.
   if (!neededInt && !neededSSE)
diff --git a/clang/test/CodeGenCXX/x86_64-vaarg.cpp 
b/clang/test/CodeGenCXX/x86_64-vaarg.cpp
new file mode 100644
index 00..f0177906a09a81
--- /dev/null
+++ b/clang/test/CodeGenCXX/x86_64-vaarg.cpp
@@ -0,0 +1,23 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -x c -o - %s | 
FileCheck %s
+
+typedef struct { struct {} a; } empty;
+
+// CHECK-LABEL: @{{.*}}empty_record_test
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca [[STRUCT_EMPTY:%.*]], align 1
+// CHECK-NEXT:[[Z_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:[[LIST:%.*]] = alloca [1 x %struct.__va_list_tag], align 16
+// CHECK-NEXT:[[TMP:%.*]] = alloca [[STRUCT_EMPTY]], align 1
+// CHECK-NEXT:store i32 [[Z:%.*]], ptr [[Z_ADDR]], align 4
+// CHECK-NEXT:[[ARRAYDECAY:%.*]] = getelementptr inbounds [1 x 
%struct.__va_list_tag], ptr [[LIST]], i64 0, i64 0
+// CHECK-NEXT:call void @llvm.va_start(ptr [[ARRAYDECAY]])
+// CHECK-NEXT:[[ARRAYDECAY1:%.*]] = getelementptr inbounds [1 x 
%struct.__va_list_tag], ptr [[LIST]], i64 0, i64 0
+// CHECK-NEXT:call void @llvm.memcpy.p0.p0.i64(ptr align 1 [[RETVAL]], ptr 
align 1 [[TMP]], i64 {{.*}}, i1 false)
+// CHECK-NEXT:ret void
+empty empty_record_test(int z, ...) {
+  __builtin_va_list list;
+  __builtin_va_start(list, z);
+  return __builtin_va_arg(list, empty);
+}

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


[clang] [clang] Implement __builtin_{clzg,ctzg} (PR #83431)

2024-03-19 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic approved this pull request.

LGTM with one minor comment

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


[clang] [clang] Implement __builtin_{clzg,ctzg} (PR #83431)

2024-03-19 Thread Eli Friedman via cfe-commits

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


[clang] [clang] Implement __builtin_{clzg,ctzg} (PR #83431)

2024-03-19 Thread Eli Friedman via cfe-commits


@@ -3504,6 +3504,47 @@ argument can be of any unsigned integer type.
 ``__builtin_popcount{,l,ll}`` builtins, with support for other integer types,
 such as ``unsigned __int128`` and C23 ``unsigned _BitInt(N)``.
 
+``__builtin_clzg`` and ``__builtin_ctzg``
+-
+
+``__builtin_clzg`` (respectively ``__builtin_ctzg``) returns the number of
+leading (respectively trailing) 0 bits in the first argument. The first 
argument
+can be of any unsigned integer type.
+
+If the first argument is 0 and an optional second argument of ``int`` type is
+provided, then the second argument is returned. If the first argument is 0, but
+only one argument is provided, then the returned value is undefined.

efriedma-quic wrote:

Probably should say "the behavior is undefined", to match the C standard 
wording for this sort of thing.  (The IR intrinsic returns poison, but "poison" 
isn't a C language concept.)

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


[clang] [InstallAPI] Simplify & improve symbol printing for diagnostics (PR #85894)

2024-03-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Cyndy Ishida (cyndyishida)


Changes

* Defer mangling of symbols until an error is ready to report
* Pass around fewer parameters when reporting

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


4 Files Affected:

- (modified) clang/include/clang/InstallAPI/DylibVerifier.h (+4) 
- (modified) clang/include/clang/InstallAPI/MachO.h (+2) 
- (modified) clang/lib/InstallAPI/DylibVerifier.cpp (+65-69) 
- (modified) clang/test/InstallAPI/diagnostics-cpp.test (+2-2) 


``diff
diff --git a/clang/include/clang/InstallAPI/DylibVerifier.h 
b/clang/include/clang/InstallAPI/DylibVerifier.h
index 8269715c7f2345..bbfa8711313e47 100644
--- a/clang/include/clang/InstallAPI/DylibVerifier.h
+++ b/clang/include/clang/InstallAPI/DylibVerifier.h
@@ -128,6 +128,10 @@ class DylibVerifier {
   /// Find matching dylib slice for target triple that is being parsed.
   void assignSlice(const Target &T);
 
+  /// Gather annotations for symbol for error reporting.
+  std::string getAnnotatedName(const Record *R, SymbolContext &SymCtx,
+   bool ValidSourceLoc = true);
+
   // Symbols in dylib.
   llvm::MachO::Records Dylib;
 
diff --git a/clang/include/clang/InstallAPI/MachO.h 
b/clang/include/clang/InstallAPI/MachO.h
index a77766511fa3e5..f0dea8bbd24ccd 100644
--- a/clang/include/clang/InstallAPI/MachO.h
+++ b/clang/include/clang/InstallAPI/MachO.h
@@ -26,11 +26,13 @@
 using SymbolFlags = llvm::MachO::SymbolFlags;
 using RecordLinkage = llvm::MachO::RecordLinkage;
 using Record = llvm::MachO::Record;
+using EncodeKind = llvm::MachO::EncodeKind;
 using GlobalRecord = llvm::MachO::GlobalRecord;
 using ObjCContainerRecord = llvm::MachO::ObjCContainerRecord;
 using ObjCInterfaceRecord = llvm::MachO::ObjCInterfaceRecord;
 using ObjCCategoryRecord = llvm::MachO::ObjCCategoryRecord;
 using ObjCIVarRecord = llvm::MachO::ObjCIVarRecord;
+using ObjCIFSymbolKind = llvm::MachO::ObjCIFSymbolKind;
 using Records = llvm::MachO::Records;
 using RecordsSlice = llvm::MachO::RecordsSlice;
 using BinaryAttrs = llvm::MachO::RecordsSlice::BinaryAttrs;
diff --git a/clang/lib/InstallAPI/DylibVerifier.cpp 
b/clang/lib/InstallAPI/DylibVerifier.cpp
index 700763b3fee0db..24e0d0addf2f46 100644
--- a/clang/lib/InstallAPI/DylibVerifier.cpp
+++ b/clang/lib/InstallAPI/DylibVerifier.cpp
@@ -10,9 +10,6 @@ namespace installapi {
 
 /// Metadata stored about a mapping of a declaration to a symbol.
 struct DylibVerifier::SymbolContext {
-  // Name to use for printing in diagnostics.
-  std::string PrettyPrintName{""};
-
   // Name to use for all querying and verification
   // purposes.
   std::string SymbolName{""};
@@ -30,11 +27,35 @@ struct DylibVerifier::SymbolContext {
   bool Inlined = false;
 };
 
-static std::string
-getAnnotatedName(const Record *R, EncodeKind Kind, StringRef Name,
- bool ValidSourceLoc = true,
- ObjCIFSymbolKind ObjCIF = ObjCIFSymbolKind::None) {
-  assert(!Name.empty() && "Need symbol name for printing");
+static bool isCppMangled(StringRef Name) {
+  // InstallAPI currently only supports itanium manglings.
+  return (Name.starts_with("_Z") || Name.starts_with("__Z") ||
+  Name.starts_with("___Z"));
+}
+
+static std::string demangle(StringRef Name) {
+  // InstallAPI currently only supports itanium manglings.
+  if (!isCppMangled(Name))
+return Name.str();
+  char *Result = llvm::itaniumDemangle(Name);
+  if (!Result)
+return Name.str();
+
+  std::string Demangled(Result);
+  free(Result);
+  return Demangled;
+}
+
+std::string DylibVerifier::getAnnotatedName(const Record *R,
+SymbolContext &SymCtx,
+bool ValidSourceLoc) {
+  assert(!SymCtx.SymbolName.empty() && "Expected symbol name");
+
+  const StringRef SymbolName = SymCtx.SymbolName;
+  std::string PrettyName =
+  (Demangle && (SymCtx.Kind == EncodeKind::GlobalSymbol))
+  ? demangle(SymbolName)
+  : SymbolName.str();
 
   std::string Annotation;
   if (R->isWeakDefined())
@@ -45,15 +66,16 @@ getAnnotatedName(const Record *R, EncodeKind Kind, 
StringRef Name,
 Annotation += "(tlv) ";
 
   // Check if symbol represents only part of a @interface declaration.
-  const bool IsAnnotatedObjCClass = ((ObjCIF != ObjCIFSymbolKind::None) &&
- (ObjCIF <= ObjCIFSymbolKind::EHType));
+  const bool IsAnnotatedObjCClass =
+  ((SymCtx.ObjCIFKind != ObjCIFSymbolKind::None) &&
+   (SymCtx.ObjCIFKind <= ObjCIFSymbolKind::EHType));
 
   if (IsAnnotatedObjCClass) {
-if (ObjCIF == ObjCIFSymbolKind::EHType)
+if (SymCtx.ObjCIFKind == ObjCIFSymbolKind::EHType)
   Annotation += "Exception Type of ";
-if (ObjCIF == ObjCIFSymbolKind::MetaClass)
+if (SymCtx.ObjCIFKind == ObjCIFSymbolKind::MetaClass)
   Annotation += "Metaclass of ";
-if (ObjCIF == ObjCIFSymbolKind::Class)
+if (S

[clang] [InstallAPI] Simplify & improve symbol printing for diagnostics (PR #85894)

2024-03-19 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida created 
https://github.com/llvm/llvm-project/pull/85894

* Defer mangling of symbols until an error is ready to report
* Pass around fewer parameters when reporting

>From f172f1c95c7011af4216b9e412fbb305d4f37e95 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Tue, 19 Mar 2024 21:32:29 -0700
Subject: [PATCH] [InstallAPI] Simplify & improve symbol printing for
 diagnostics

* Defer mangling of symbols until error is ready to report.
* Pass around less parameters when reporting
---
 .../include/clang/InstallAPI/DylibVerifier.h  |   4 +
 clang/include/clang/InstallAPI/MachO.h|   2 +
 clang/lib/InstallAPI/DylibVerifier.cpp| 134 +-
 clang/test/InstallAPI/diagnostics-cpp.test|   4 +-
 4 files changed, 73 insertions(+), 71 deletions(-)

diff --git a/clang/include/clang/InstallAPI/DylibVerifier.h 
b/clang/include/clang/InstallAPI/DylibVerifier.h
index 8269715c7f2345..bbfa8711313e47 100644
--- a/clang/include/clang/InstallAPI/DylibVerifier.h
+++ b/clang/include/clang/InstallAPI/DylibVerifier.h
@@ -128,6 +128,10 @@ class DylibVerifier {
   /// Find matching dylib slice for target triple that is being parsed.
   void assignSlice(const Target &T);
 
+  /// Gather annotations for symbol for error reporting.
+  std::string getAnnotatedName(const Record *R, SymbolContext &SymCtx,
+   bool ValidSourceLoc = true);
+
   // Symbols in dylib.
   llvm::MachO::Records Dylib;
 
diff --git a/clang/include/clang/InstallAPI/MachO.h 
b/clang/include/clang/InstallAPI/MachO.h
index a77766511fa3e5..f0dea8bbd24ccd 100644
--- a/clang/include/clang/InstallAPI/MachO.h
+++ b/clang/include/clang/InstallAPI/MachO.h
@@ -26,11 +26,13 @@
 using SymbolFlags = llvm::MachO::SymbolFlags;
 using RecordLinkage = llvm::MachO::RecordLinkage;
 using Record = llvm::MachO::Record;
+using EncodeKind = llvm::MachO::EncodeKind;
 using GlobalRecord = llvm::MachO::GlobalRecord;
 using ObjCContainerRecord = llvm::MachO::ObjCContainerRecord;
 using ObjCInterfaceRecord = llvm::MachO::ObjCInterfaceRecord;
 using ObjCCategoryRecord = llvm::MachO::ObjCCategoryRecord;
 using ObjCIVarRecord = llvm::MachO::ObjCIVarRecord;
+using ObjCIFSymbolKind = llvm::MachO::ObjCIFSymbolKind;
 using Records = llvm::MachO::Records;
 using RecordsSlice = llvm::MachO::RecordsSlice;
 using BinaryAttrs = llvm::MachO::RecordsSlice::BinaryAttrs;
diff --git a/clang/lib/InstallAPI/DylibVerifier.cpp 
b/clang/lib/InstallAPI/DylibVerifier.cpp
index 700763b3fee0db..24e0d0addf2f46 100644
--- a/clang/lib/InstallAPI/DylibVerifier.cpp
+++ b/clang/lib/InstallAPI/DylibVerifier.cpp
@@ -10,9 +10,6 @@ namespace installapi {
 
 /// Metadata stored about a mapping of a declaration to a symbol.
 struct DylibVerifier::SymbolContext {
-  // Name to use for printing in diagnostics.
-  std::string PrettyPrintName{""};
-
   // Name to use for all querying and verification
   // purposes.
   std::string SymbolName{""};
@@ -30,11 +27,35 @@ struct DylibVerifier::SymbolContext {
   bool Inlined = false;
 };
 
-static std::string
-getAnnotatedName(const Record *R, EncodeKind Kind, StringRef Name,
- bool ValidSourceLoc = true,
- ObjCIFSymbolKind ObjCIF = ObjCIFSymbolKind::None) {
-  assert(!Name.empty() && "Need symbol name for printing");
+static bool isCppMangled(StringRef Name) {
+  // InstallAPI currently only supports itanium manglings.
+  return (Name.starts_with("_Z") || Name.starts_with("__Z") ||
+  Name.starts_with("___Z"));
+}
+
+static std::string demangle(StringRef Name) {
+  // InstallAPI currently only supports itanium manglings.
+  if (!isCppMangled(Name))
+return Name.str();
+  char *Result = llvm::itaniumDemangle(Name);
+  if (!Result)
+return Name.str();
+
+  std::string Demangled(Result);
+  free(Result);
+  return Demangled;
+}
+
+std::string DylibVerifier::getAnnotatedName(const Record *R,
+SymbolContext &SymCtx,
+bool ValidSourceLoc) {
+  assert(!SymCtx.SymbolName.empty() && "Expected symbol name");
+
+  const StringRef SymbolName = SymCtx.SymbolName;
+  std::string PrettyName =
+  (Demangle && (SymCtx.Kind == EncodeKind::GlobalSymbol))
+  ? demangle(SymbolName)
+  : SymbolName.str();
 
   std::string Annotation;
   if (R->isWeakDefined())
@@ -45,15 +66,16 @@ getAnnotatedName(const Record *R, EncodeKind Kind, 
StringRef Name,
 Annotation += "(tlv) ";
 
   // Check if symbol represents only part of a @interface declaration.
-  const bool IsAnnotatedObjCClass = ((ObjCIF != ObjCIFSymbolKind::None) &&
- (ObjCIF <= ObjCIFSymbolKind::EHType));
+  const bool IsAnnotatedObjCClass =
+  ((SymCtx.ObjCIFKind != ObjCIFSymbolKind::None) &&
+   (SymCtx.ObjCIFKind <= ObjCIFSymbolKind::EHType));
 
   if (IsAnnotatedObjCClass) {
-if (ObjCIF == ObjCIFSymbolKind::EHType)
+if (SymCtx.ObjCIFKind == ObjCIFSymbolKin

[clang] [clang] Add `__has_extension(swiftcc)` support (PR #85347)

2024-03-19 Thread Yuta Saito via cfe-commits

https://github.com/kateinoigakukun updated 
https://github.com/llvm/llvm-project/pull/85347

>From 6ebb36306100c10a340c5434efcf54a526085a48 Mon Sep 17 00:00:00 2001
From: Yuta Saito 
Date: Fri, 15 Mar 2024 00:43:43 +
Subject: [PATCH] [clang] Add `__has_extension(swiftcc)` support

This patch adds `swiftcc` extension to check if the target supports Swift
calling convention as well as we do for `swiftasynccc`.
Also `swiftasynccc` is now considered to be a Clang extension rather than a
language standard feature to reflect the nature of the attribute.
---
 clang/docs/ReleaseNotes.rst|  7 +++
 clang/include/clang/Basic/AttrDocs.td  | 13 +
 clang/include/clang/Basic/Features.def |  5 -
 clang/test/Sema/swift-call-conv.c  | 14 +-
 4 files changed, 33 insertions(+), 6 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ba9de1ac98de08..b314de938f8345 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -210,6 +210,13 @@ Attribute Changes in Clang
   and each must be a positive integer when provided. The parameter ``x`` is 
required, while ``y`` and
   ``z`` are optional with default value of 1.
 
+- The ``swiftasynccc`` attribute is now considered to be a Clang extension
+  rather than a language standard feature. Please use
+  ``__has_extension(swiftasynccc)`` to check the availability of this attribute
+  for the target platform instead of ``__has_feature(swiftasynccc)``. Also,
+  added a new extension query ``__has_extension(swiftcc)`` corresponding to the
+  ``__attribute__((swiftcc))`` attribute.
+
 Improvements to Clang's diagnostics
 ---
 - Clang now applies syntax highlighting to the code snippets it
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index d61f96ade557d5..9de14f608fd114 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5137,10 +5137,11 @@ that does not. A single parameter may not have multiple 
ABI treatment
 attributes.
 
 Support for this feature is target-dependent, although it should be
-supported on every target that Swift supports. Query for this support
-with ``__has_attribute(swiftcall)``. This implies support for the
-``swift_context``, ``swift_error_result``, and ``swift_indirect_result``
-attributes.
+supported on every target that Swift supports. Query for this attribute
+with ``__has_attribute(swiftcall)``. Query if the target supports the
+calling convention with ``__has_extension(swiftcc)``. This implies
+support for the ``swift_context``, ``swift_error_result``, and
+``swift_indirect_result`` attributes.
   }];
 }
 
@@ -5187,6 +5188,10 @@ the following:
   semantically be performed after a guaranteed tail call, such as the
   non-trivial destruction of a local variable or temporary,
   then the program is ill-formed.
+
+Query for this attribute with ``__has_attribute(swiftasynccall)``. Query if
+the target supports the calling convention with
+``__has_extension(swiftasynccc)``.
   }];
 }
 
diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index eeed5f4751f2f4..726ead4b5ab5ab 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -102,7 +102,10 @@ FEATURE(thread_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::Thread))
 FEATURE(dataflow_sanitizer, LangOpts.Sanitize.has(SanitizerKind::DataFlow))
 FEATURE(scudo, LangOpts.Sanitize.hasOneOf(SanitizerKind::Scudo))
 FEATURE(ptrauth_intrinsics, LangOpts.PointerAuthIntrinsics)
-FEATURE(swiftasynccc,
+EXTENSION(swiftcc,
+  PP.getTargetInfo().checkCallingConvention(CC_Swift) ==
+  clang::TargetInfo::CCCR_OK)
+EXTENSION(swiftasynccc,
   PP.getTargetInfo().checkCallingConvention(CC_SwiftAsync) ==
   clang::TargetInfo::CCCR_OK)
 FEATURE(pragma_stdc_cx_limited_range, true)
diff --git a/clang/test/Sema/swift-call-conv.c 
b/clang/test/Sema/swift-call-conv.c
index 755c18f5183f85..2c9be840558481 100644
--- a/clang/test/Sema/swift-call-conv.c
+++ b/clang/test/Sema/swift-call-conv.c
@@ -1,7 +1,19 @@
 // RUN: %clang_cc1 -triple aarch64-unknown-windows-msvc -fsyntax-only %s 
-verify
 // RUN: %clang_cc1 -triple thumbv7-unknown-windows-msvc -fsyntax-only %s 
-verify
 // RUN: %clang_cc1 -triple x86_64-unknown-windows-msvc -fsyntax-only %s -verify
+// RISC-V does not support swiftcall
+// RUN: %clang_cc1 -triple riscv32-unknown-elf -fsyntax-only %s -verify
 
+#if __has_extension(swiftcc)
 // expected-no-diagnostics
-
+#else
+// expected-warning@+2 {{'__swiftcall__' calling convention is not supported 
for this target}}
+#endif
 void __attribute__((__swiftcall__)) f(void) {}
+
+#if __has_extension(swiftasynccc)
+// expected-no-diagnostics
+#else
+// expected-warning@+2 {{'__swiftasynccall__' calling convention is not 
supported for this target}}
+#endif
+void __attribute__((__swiftasynccall__)) g(void) {}


[clang] [HIP] Correctly omit bundling with the new driver (PR #85842)

2024-03-19 Thread Yaxun Liu via cfe-commits

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


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


[clang] [AArch64][PAC][clang][ELF] Support PAuth ABI compatibility tag (PR #85235)

2024-03-19 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,32 @@
+// Check that we can manually enable specific ptrauth features.
+
+// RUN: %clang -target aarch64 -c %s -### 2>&1 | FileCheck %s --check-prefix 
NONE
+// NONE: "-cc1"
+// NONE-NOT: "-fptrauth-intrinsics"
+// NONE-NOT: "-fptrauth-calls"
+// NONE-NOT: "-fptrauth-returns"
+// NONE-NOT: "-fptrauth-auth-traps"
+// NONE-NOT: "-fptrauth-vtable-pointer-address-discrimination"
+// NONE-NOT: "-fptrauth-vtable-pointer-type-discrimination"
+// NONE-NOT: "-fptrauth-init-fini"
+
+// RUN: %clang -target aarch64 -fptrauth-intrinsics -c %s -### 2>&1 | 
FileCheck %s --check-prefix INTRIN
+// INTRIN: "-cc1"{{.*}} {{.*}} "-fptrauth-intrinsics"

MaskRay wrote:

`{{.*}} {{.*}} ` => ` {{.*}}`

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


[clang] [AArch64][PAC][clang][ELF] Support PAuth ABI compatibility tag (PR #85235)

2024-03-19 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,32 @@
+// Check that we can manually enable specific ptrauth features.
+
+// RUN: %clang -target aarch64 -c %s -### 2>&1 | FileCheck %s --check-prefix 
NONE

MaskRay wrote:

`--target=` for new tests

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


[clang] [clang] Factor out OpenACC part of `Sema` (PR #84184)

2024-03-19 Thread Fangrui Song via cfe-commits

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

bazel-6.3.2 build --config=generic_clang @llvm-project//clang

build passes with this refactoring. Thanks

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


[clang] [CMake] Change GCC_INSTALL_PREFIX from warning to fatal error (PR #85891)

2024-03-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Fangrui Song (MaskRay)


Changes

unless USE_DEPRECATED_GCC_INSTALL_PREFIX (temporary escape hatch) is
set. Setting GCC_INSTALL_PREFIX leads to a warning for Clang 18.1
(#77537) and will be completely removed for Clang 20.

Link: 
discourse.llvm.org/t/add-gcc-install-dir-deprecate-gcc-toolchain-and-remove-gcc-install-prefix/65091
Link: 
discourse.llvm.org/t/correct-cmake-parameters-for-building-clang-and-lld-for-riscv/72833


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


2 Files Affected:

- (modified) clang/CMakeLists.txt (+3-2) 
- (modified) clang/docs/ReleaseNotes.rst (+3) 


``diff
diff --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index 47fc2e4886cfc2..761dab8c28c134 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -190,11 +190,12 @@ set(CLANG_RESOURCE_DIR "" CACHE STRING
 set(C_INCLUDE_DIRS "" CACHE STRING
   "Colon separated list of directories clang will search for headers.")
 
+set(USE_DEPRECATED_GCC_INSTALL_PREFIX OFF CACHE BOOL "Temporary workaround 
before GCC_INSTALL_PREFIX is completely removed")
 set(GCC_INSTALL_PREFIX "" CACHE PATH "Directory where gcc is installed." )
 set(DEFAULT_SYSROOT "" CACHE STRING
   "Default  to all compiler invocations for --sysroot=." )
-if(GCC_INSTALL_PREFIX)
-  message(WARNING "GCC_INSTALL_PREFIX is deprecated and will be removed. Use "
+if(GCC_INSTALL_PREFIX AND NOT USE_DEPRECATED_GCC_INSTALL_PREFIX)
+  message(FATAL_ERROR "GCC_INSTALL_PREFIX is deprecated and will be removed. 
Use "
 "configuration files 
(https://clang.llvm.org/docs/UsersManual.html#configuration-files)"
 "to specify the default --gcc-install-dir= or --gcc-triple=. 
--gcc-toolchain= is discouraged. "
 "See https://github.com/llvm/llvm-project/pull/77537 for detail.")
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0ce3cbe3266efd..862aec323899ce 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -37,6 +37,9 @@ These changes are ones which we think may surprise users when 
upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Setting the deprecated CMake variable ``GCC_INSTALL_PREFIX`` (which sets the
+  default ``--gcc-toolchain=``) now leads to a fatal error.
+
 C/C++ Language Potentially Breaking Changes
 ---
 

``




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


[clang] [CMake] Change GCC_INSTALL_PREFIX from warning to fatal error (PR #85891)

2024-03-19 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay created 
https://github.com/llvm/llvm-project/pull/85891

unless USE_DEPRECATED_GCC_INSTALL_PREFIX (temporary escape hatch) is
set. Setting GCC_INSTALL_PREFIX leads to a warning for Clang 18.1
(#77537) and will be completely removed for Clang 20.

Link: 
discourse.llvm.org/t/add-gcc-install-dir-deprecate-gcc-toolchain-and-remove-gcc-install-prefix/65091
Link: 
discourse.llvm.org/t/correct-cmake-parameters-for-building-clang-and-lld-for-riscv/72833


>From 14bf5c0a35de1b1eb2515cd5169b3b02034a2db4 Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Tue, 19 Mar 2024 20:14:57 -0700
Subject: [PATCH] [CMake] Change GCC_INSTALL_PREFIX from warning to fatal error

unless USE_DEPRECATED_GCC_INSTALL_PREFIX (temporary escape hatch) is
set. Setting GCC_INSTALL_PREFIX leads to a warning for Clang 18.1
(#77537) and will be completely removed for Clang 20.

Link: 
discourse.llvm.org/t/add-gcc-install-dir-deprecate-gcc-toolchain-and-remove-gcc-install-prefix/65091
Link: 
discourse.llvm.org/t/correct-cmake-parameters-for-building-clang-and-lld-for-riscv/72833
---
 clang/CMakeLists.txt| 5 +++--
 clang/docs/ReleaseNotes.rst | 3 +++
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index 47fc2e4886cfc2..761dab8c28c134 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -190,11 +190,12 @@ set(CLANG_RESOURCE_DIR "" CACHE STRING
 set(C_INCLUDE_DIRS "" CACHE STRING
   "Colon separated list of directories clang will search for headers.")
 
+set(USE_DEPRECATED_GCC_INSTALL_PREFIX OFF CACHE BOOL "Temporary workaround 
before GCC_INSTALL_PREFIX is completely removed")
 set(GCC_INSTALL_PREFIX "" CACHE PATH "Directory where gcc is installed." )
 set(DEFAULT_SYSROOT "" CACHE STRING
   "Default  to all compiler invocations for --sysroot=." )
-if(GCC_INSTALL_PREFIX)
-  message(WARNING "GCC_INSTALL_PREFIX is deprecated and will be removed. Use "
+if(GCC_INSTALL_PREFIX AND NOT USE_DEPRECATED_GCC_INSTALL_PREFIX)
+  message(FATAL_ERROR "GCC_INSTALL_PREFIX is deprecated and will be removed. 
Use "
 "configuration files 
(https://clang.llvm.org/docs/UsersManual.html#configuration-files)"
 "to specify the default --gcc-install-dir= or --gcc-triple=. 
--gcc-toolchain= is discouraged. "
 "See https://github.com/llvm/llvm-project/pull/77537 for detail.")
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0ce3cbe3266efd..862aec323899ce 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -37,6 +37,9 @@ These changes are ones which we think may surprise users when 
upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Setting the deprecated CMake variable ``GCC_INSTALL_PREFIX`` (which sets the
+  default ``--gcc-toolchain=``) now leads to a fatal error.
+
 C/C++ Language Potentially Breaking Changes
 ---
 

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


[clang] [Clang][Sema]: Allow flexible arrays in unions and alone in structs (PR #84428)

2024-03-19 Thread Kees Cook via cfe-commits


@@ -1,13 +1,158 @@
-// RUN: %clang_cc1 %s -verify=c -fsyntax-only
-// RUN: %clang_cc1 %s -verify -fsyntax-only -x c++
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c -fsyntax-only
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -x c++
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c,gnu -fsyntax-only 
-Wgnu-flexible-array-union-member -Wgnu-empty-struct
+// RUN: %clang_cc1 %s -verify=stock,c,microsoft -fsyntax-only 
-fms-compatibility -Wmicrosoft
 
 // The test checks that an attempt to initialize union with flexible array
 // member with an initializer list doesn't crash clang.
 
 
-union { char x[]; } r = {0}; // c-error {{flexible array member 'x' in a union 
is not allowed}}
+union { char x[]; } r = {0}; /* gnu-warning {{flexible array member 'x' in a 
union is a GNU extension}}
+microsoft-warning {{flexible array member 'x' 
in a union is a Microsoft extension}}
+  */
+struct _name1 {
+  int a;
+  union {
+int b;
+char x[]; /* gnu-warning {{flexible array member 'x' in a union is a GNU 
extension}}
+ microsoft-warning {{flexible array member 'x' in a union is a 
Microsoft extension}}
+   */
+  };
+} name1 = {
+  10,
+  42,/* initializes "b" */
+};
 
-// expected-no-diagnostics
+struct _name1i {
+  int a;
+  union {
+int b;
+char x[]; /* gnu-warning {{flexible array member 'x' in a union is a GNU 
extension}}
+ microsoft-warning {{flexible array member 'x' in a union is a 
Microsoft extension}}
+   */
+  };
+} name1i = {
+  .a = 10,
+  .b = 42,
+};
+
+/* Initialization of flexible array in a union is never allowed. */
+struct _name2 {
+  int a;
+  union {
+int b;
+char x[]; /* gnu-warning {{flexible array member 'x' in a union is a GNU 
extension}}
+ microsoft-warning {{flexible array member 'x' in a union is a 
Microsoft extension}}
+ stock-note {{initialized flexible array member 'x' is here}}
+   */
+  };
+} name2 = {
+  12,
+  13,
+  { 'c' },   /* stock-error {{initialization of flexible array member is not 
allowed}} */

kees wrote:

This seems to work:

```diff
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 011deed7a9a9..79cf2eed46fe 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -2437,6 +2437,7 @@ void InitListChecker::CheckStructUnionTypes(
   }
 
   if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
+  (RD->isUnion() && Field != RD->field_begin()) ||
   Index >= IList->getNumInits())
 return;
 
```

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


[clang] [llvm] [CodeGen][LLVM] Make the `va_list` related intrinsics generic. (PR #85460)

2024-03-19 Thread Alex Voicu via cfe-commits


@@ -1713,7 +1716,7 @@ def int_coro_subfn_addr : DefaultAttrsIntrinsic<
 
 ///===-- Other Intrinsics 
--===//
 //
-// TODO: We should introduce a new memory kind fo traps (and other side 
effects 
+// TODO: We should introduce a new memory kind fo traps (and other side effects

AlexVlx wrote:

Done.

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


[clang] [Clang][Sema]: Allow flexible arrays in unions and alone in structs (PR #84428)

2024-03-19 Thread Kees Cook via cfe-commits


@@ -1,13 +1,158 @@
-// RUN: %clang_cc1 %s -verify=c -fsyntax-only
-// RUN: %clang_cc1 %s -verify -fsyntax-only -x c++
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c -fsyntax-only
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -x c++
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c,gnu -fsyntax-only 
-Wgnu-flexible-array-union-member -Wgnu-empty-struct
+// RUN: %clang_cc1 %s -verify=stock,c,microsoft -fsyntax-only 
-fms-compatibility -Wmicrosoft
 
 // The test checks that an attempt to initialize union with flexible array
 // member with an initializer list doesn't crash clang.
 
 
-union { char x[]; } r = {0}; // c-error {{flexible array member 'x' in a union 
is not allowed}}
+union { char x[]; } r = {0}; /* gnu-warning {{flexible array member 'x' in a 
union is a GNU extension}}
+microsoft-warning {{flexible array member 'x' 
in a union is a Microsoft extension}}
+  */
+struct _name1 {
+  int a;
+  union {
+int b;
+char x[]; /* gnu-warning {{flexible array member 'x' in a union is a GNU 
extension}}
+ microsoft-warning {{flexible array member 'x' in a union is a 
Microsoft extension}}
+   */
+  };
+} name1 = {
+  10,
+  42,/* initializes "b" */
+};
 
-// expected-no-diagnostics
+struct _name1i {
+  int a;
+  union {
+int b;
+char x[]; /* gnu-warning {{flexible array member 'x' in a union is a GNU 
extension}}
+ microsoft-warning {{flexible array member 'x' in a union is a 
Microsoft extension}}
+   */
+  };
+} name1i = {
+  .a = 10,
+  .b = 42,
+};
+
+/* Initialization of flexible array in a union is never allowed. */
+struct _name2 {
+  int a;
+  union {
+int b;
+char x[]; /* gnu-warning {{flexible array member 'x' in a union is a GNU 
extension}}
+ microsoft-warning {{flexible array member 'x' in a union is a 
Microsoft extension}}
+ stock-note {{initialized flexible array member 'x' is here}}
+   */
+  };
+} name2 = {
+  12,
+  13,
+  { 'c' },   /* stock-error {{initialization of flexible array member is not 
allowed}} */

kees wrote:

Dang, this doesn't work: it can't initialize a flex array if it's the first (or 
only) thing in the union. Hmm.

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


[clang] e7175b0 - [HIP] do not link runtime for -r (#85675)

2024-03-19 Thread via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2024-03-19T23:03:57-04:00
New Revision: e7175b07047d1ba7b012f811064091f12ebf8a40

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

LOG: [HIP] do not link runtime for -r (#85675)

since it will cause duplicate symbols when the partially linked object
is linked again.

Added: 


Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/test/Driver/hip-partial-link.hip
clang/test/Driver/hip-runtime-libs-linux.hip

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 83015b0cb81a6e..4478865313636d 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2830,7 +2830,7 @@ void tools::addHIPRuntimeLibArgs(const ToolChain &TC, 
Compilation &C,
  llvm::opt::ArgStringList &CmdArgs) {
   if ((C.getActiveOffloadKinds() & Action::OFK_HIP) &&
   !Args.hasArg(options::OPT_nostdlib) &&
-  !Args.hasArg(options::OPT_no_hip_rt)) {
+  !Args.hasArg(options::OPT_no_hip_rt) && !Args.hasArg(options::OPT_r)) {
 TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
   } else {
 // Claim "no HIP libraries" arguments if any

diff  --git a/clang/test/Driver/hip-partial-link.hip 
b/clang/test/Driver/hip-partial-link.hip
index faa185972abc33..c8451ec81ed37e 100644
--- a/clang/test/Driver/hip-partial-link.hip
+++ b/clang/test/Driver/hip-partial-link.hip
@@ -47,7 +47,7 @@
 // OBJ:  D __hip_gpubin_handle_[[ID2]]
 
 // RUN: %clang -v --target=x86_64-unknown-linux-gnu --no-offload-new-driver \
-// RUN:   --hip-link -no-hip-rt -fgpu-rdc --offload-arch=gfx906 \
+// RUN:   --hip-link -fgpu-rdc --offload-arch=gfx906 \
 // RUN:   -fuse-ld=lld -nostdlib -r %t.main.o %t.lib.o -o %t.final.o \
 // RUN:   2>&1 | FileCheck -check-prefix=LINK-O %s
 // LINK-O-NOT: Found undefined HIP {{.*}}symbol

diff  --git a/clang/test/Driver/hip-runtime-libs-linux.hip 
b/clang/test/Driver/hip-runtime-libs-linux.hip
index 142582963c958f..a4cd2733114b69 100644
--- a/clang/test/Driver/hip-runtime-libs-linux.hip
+++ b/clang/test/Driver/hip-runtime-libs-linux.hip
@@ -43,6 +43,11 @@
 // RUN:   --rocm-path=%S/Inputs/rocm %t.o 2>&1 \
 // RUN:   | FileCheck -check-prefixes=NOHIPRT %s
 
+// Test HIP runtime lib is not linked with -r.
+// RUN: %clang -### --hip-link -r --target=x86_64-linux-gnu \
+// RUN:   --rocm-path=%S/Inputs/rocm %t.o 2>&1 \
+// RUN:   | FileCheck -check-prefixes=NOHIPRT %s
+
 // Test HIP runtime lib is linked without hip-link if there is HIP input file.
 // RUN: %clang -### --target=x86_64-linux-gnu -nogpuinc -nogpulib \
 // RUN:   --rocm-path=%S/Inputs/rocm %s 2>&1 \



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


[clang] [HIP] do not link runtime for -r (PR #85675)

2024-03-19 Thread Yaxun Liu via cfe-commits

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


[clang] [HIP] do not link runtime for -r (PR #85675)

2024-03-19 Thread Yaxun Liu via cfe-commits

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


[clang] [clang][c++20] Fix code coverage mapping crash with generalized NTTPs (PR #85837)

2024-03-19 Thread Andrey Ali Khan Bolshakov via cfe-commits

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


[clang] Fix code coverage mapping crash with generalized NTTPs (PR #85837)

2024-03-19 Thread Andrey Ali Khan Bolshakov via cfe-commits

https://github.com/bolshakov-a updated 
https://github.com/llvm/llvm-project/pull/85837

>From 398ad87c1e9669223def3561f4cdd72af11857c3 Mon Sep 17 00:00:00 2001
From: Bolshakov 
Date: Tue, 19 Mar 2024 19:05:36 +0300
Subject: [PATCH] [clang][c++20] Fix code coverage mapping crash with
 generalized NTTPs

Introduced in #78041, originally reported as #79957 and fixed partially
in #80050.

`OpaqueValueExpr` used with `TemplateArgument::StructuralValue` has no
corresponding source expression.

A test case with subobject-referring NTTP added.
---
 clang/lib/CodeGen/CoverageMappingGen.cpp | 3 ++-
 clang/test/CoverageMapping/templates.cpp | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 71215da362d3d0..3a87f935470673 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -2177,7 +2177,8 @@ struct CounterCoverageMappingBuilder
   }
 
   void VisitOpaqueValueExpr(const OpaqueValueExpr* OVE) {
-Visit(OVE->getSourceExpr());
+if (const Expr *SE = OVE->getSourceExpr())
+  Visit(SE);
   }
 };
 
diff --git a/clang/test/CoverageMapping/templates.cpp 
b/clang/test/CoverageMapping/templates.cpp
index 143e566a33cb85..7e7f2208f1145f 100644
--- a/clang/test/CoverageMapping/templates.cpp
+++ b/clang/test/CoverageMapping/templates.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -mllvm -emptyline-comment-coverage=false 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-emit-llvm-only -main-file-name templates.cpp %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++20 -mllvm -emptyline-comment-coverage=false 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-emit-llvm-only -main-file-name templates.cpp %s | FileCheck %s
 
 template
 void unused(T x) {
@@ -30,5 +30,6 @@ namespace structural_value_crash {
 
   void test() {
 tpl_fn();
+tpl_fn<&arr[1]>();
   }
 }

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


[clang] [llvm] [CodeGen][LLVM] Make the `va_list` related intrinsics generic. (PR #85460)

2024-03-19 Thread Alex Voicu via cfe-commits


@@ -0,0 +1,22 @@
+// REQUIRES: spirv-registered-target

AlexVlx wrote:

I was not certain and erred on the side of caution. You are correct (as far as 
I can tell), and have removed the requirement. Thank you for pointing it out!

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


[clang] [llvm] [CodeGen][LLVM] Make the `va_list` related intrinsics generic. (PR #85460)

2024-03-19 Thread Alex Voicu via cfe-commits


@@ -0,0 +1,22 @@
+// REQUIRES: spirv-registered-target
+// RUN: %clang_cc1 -triple spirv64-unknown-unknown -fcuda-is-device -emit-llvm 
-o - %s | FileCheck %s
+struct x {
+  double b;
+  long a;
+};
+
+void testva(int n, ...) {
+  __builtin_va_list ap;
+  __builtin_va_start(ap, n);
+  struct x t = __builtin_va_arg(ap, struct x);
+  __builtin_va_list ap2;
+  __builtin_va_copy(ap2, ap);
+  int v = __builtin_va_arg(ap2, int);
+  __builtin_va_end(ap2);
+  __builtin_va_end(ap);
+}
+
+// CHECK:  call void @llvm.va_start.p4(ptr addrspace(4) %ap{{.*}})

AlexVlx wrote:

Done.

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


[clang] [Clang][Sema]: Allow flexible arrays in unions and alone in structs (PR #84428)

2024-03-19 Thread Kees Cook via cfe-commits


@@ -1,13 +1,158 @@
-// RUN: %clang_cc1 %s -verify=c -fsyntax-only
-// RUN: %clang_cc1 %s -verify -fsyntax-only -x c++
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c -fsyntax-only
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -x c++
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c,gnu -fsyntax-only 
-Wgnu-flexible-array-union-member -Wgnu-empty-struct
+// RUN: %clang_cc1 %s -verify=stock,c,microsoft -fsyntax-only 
-fms-compatibility -Wmicrosoft
 
 // The test checks that an attempt to initialize union with flexible array
 // member with an initializer list doesn't crash clang.
 
 
-union { char x[]; } r = {0}; // c-error {{flexible array member 'x' in a union 
is not allowed}}
+union { char x[]; } r = {0}; /* gnu-warning {{flexible array member 'x' in a 
union is a GNU extension}}

kees wrote:

I added the `empty_union` codegen test for this. Do you mean I'm not checking 
for `{0}` explicitly? I will add that.

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


[clang] [Clang][Sema]: Allow flexible arrays in unions and alone in structs (PR #84428)

2024-03-19 Thread Kees Cook via cfe-commits


@@ -1,13 +1,158 @@
-// RUN: %clang_cc1 %s -verify=c -fsyntax-only
-// RUN: %clang_cc1 %s -verify -fsyntax-only -x c++
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c -fsyntax-only
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -x c++
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c,gnu -fsyntax-only 
-Wgnu-flexible-array-union-member -Wgnu-empty-struct
+// RUN: %clang_cc1 %s -verify=stock,c,microsoft -fsyntax-only 
-fms-compatibility -Wmicrosoft
 
 // The test checks that an attempt to initialize union with flexible array
 // member with an initializer list doesn't crash clang.
 
 
-union { char x[]; } r = {0}; // c-error {{flexible array member 'x' in a union 
is not allowed}}
+union { char x[]; } r = {0}; /* gnu-warning {{flexible array member 'x' in a 
union is a GNU extension}}
+microsoft-warning {{flexible array member 'x' 
in a union is a Microsoft extension}}
+  */
+struct _name1 {
+  int a;
+  union {
+int b;
+char x[]; /* gnu-warning {{flexible array member 'x' in a union is a GNU 
extension}}
+ microsoft-warning {{flexible array member 'x' in a union is a 
Microsoft extension}}
+   */
+  };
+} name1 = {
+  10,
+  42,/* initializes "b" */
+};
 
-// expected-no-diagnostics
+struct _name1i {
+  int a;
+  union {
+int b;
+char x[]; /* gnu-warning {{flexible array member 'x' in a union is a GNU 
extension}}
+ microsoft-warning {{flexible array member 'x' in a union is a 
Microsoft extension}}
+   */
+  };
+} name1i = {
+  .a = 10,
+  .b = 42,
+};
+
+/* Initialization of flexible array in a union is never allowed. */
+struct _name2 {
+  int a;
+  union {
+int b;
+char x[]; /* gnu-warning {{flexible array member 'x' in a union is a GNU 
extension}}
+ microsoft-warning {{flexible array member 'x' in a union is a 
Microsoft extension}}
+ stock-note {{initialized flexible array member 'x' is here}}
+   */
+  };
+} name2 = {
+  12,
+  13,
+  { 'c' },   /* stock-error {{initialization of flexible array member is not 
allowed}} */

kees wrote:

Prior to this PR, it wasn't possible to use a flex array in a union, so I'll 
include it here and recheck the entire test suite. Thanks for finding this! I 
had found the function, but hadn't yet figured out how the position was being 
walked. :)

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


[clang] [clang][RISCV] Enable RVV with function attribute __attribute__((target("arch=+v"))) (PR #83674)

2024-03-19 Thread Brandon Wu via cfe-commits


@@ -8927,8 +8927,13 @@ void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
 }
   }
 
-  if (T->isRVVSizelessBuiltinType())
-checkRVVTypeSupport(T, NewVD->getLocation(), cast(CurContext));
+  if (T->isRVVSizelessBuiltinType() && isa(CurContext)) {
+const FunctionDecl *FD = cast(CurContext);
+llvm::StringMap CallerFeatureMap;
+Context.getFunctionFeatureMap(CallerFeatureMap, FD);

4vtomat wrote:

However, if we can do something like that, we can get about 5x speedup with my 
rough measurement lol~

https://github.com/llvm/llvm-project/pull/83674
___
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-03-19 Thread Akira Hatanaka via cfe-commits

https://github.com/ahatanak updated 
https://github.com/llvm/llvm-project/pull/79230

>From 678cd8ea37f1d02c70fd09b7107542c8301c3bd2 Mon Sep 17 00:00:00 2001
From: Akira Hatanaka 
Date: Tue, 16 Jan 2024 13:18:09 -0800
Subject: [PATCH 01/11] Add support for builtin_verbose_trap

The builtin causes the program to stop its execution abnormally and shows a
human-readable description of the reason for the termination when a debugger is
attached or in a symbolicated crash log.

The motivation for the builtin is explained in the following RFC:

https://discourse.llvm.org/t/rfc-adding-builtin-verbose-trap-string-literal/75845
---
 clang/docs/LanguageExtensions.rst | 48 ++
 clang/include/clang/AST/Expr.h|  5 ++
 clang/include/clang/Basic/Builtins.td |  6 +++
 .../clang/Basic/DiagnosticSemaKinds.td|  2 +
 clang/lib/AST/ExprConstant.cpp| 18 +--
 clang/lib/CodeGen/CGBuiltin.cpp   | 12 +
 clang/lib/CodeGen/CGDebugInfo.cpp | 42 
 clang/lib/CodeGen/CGDebugInfo.h   | 20 
 clang/lib/Sema/SemaChecking.cpp   | 22 +
 .../CodeGenCXX/debug-info-verbose-trap.cpp| 49 +++
 clang/test/SemaCXX/verbose-trap.cpp   | 28 +++
 11 files changed, 249 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/debug-info-verbose-trap.cpp
 create mode 100644 clang/test/SemaCXX/verbose-trap.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index c1420079f75118..4526bc2df53e42 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -3379,6 +3379,54 @@ Query for this feature with 
``__has_builtin(__builtin_debugtrap)``.
 
 Query for this feature with ``__has_builtin(__builtin_trap)``.
 
+``__builtin_verbose_trap``
+--
+
+``__builtin_verbose_trap`` causes the program to stop its execution abnormally
+and shows a human-readable description of the reason for the termination when a
+debugger is attached or in a symbolicated crash log.
+
+**Syntax**:
+
+.. code-block:: c++
+
+__builtin_verbose_trap(const char *reason)
+
+**Description**
+
+``__builtin_verbose_trap`` is lowered to the ` ``llvm.trap`` 
`_ builtin.
+Additionally, clang emits debug metadata that represents an artificial inline
+frame whose name encodes the string passed to the builtin, prefixed by a 
"magic"
+prefix.
+
+For example, consider the following code:
+
+.. code-block:: c++
+
+void foo(int* p) {
+  if (p == nullptr)
+__builtin_verbose_trap("Argument_must_not_be_null");
+}
+
+The debug metadata would look as if it were produced for the following code:
+
+.. code-block:: c++
+
+__attribute__((always_inline))
+inline void "__llvm_verbose_trap: Argument_must_not_be_null"() {
+  __builtin_trap();
+}
+
+void foo(int* p) {
+  if (p == nullptr)
+"__llvm_verbose_trap: Argument_must_not_be_null"();
+}
+
+However, the LLVM IR would not actually contain a call to the artificial
+function — it only exists in the debug metadata.
+
+Query for this feature with ``__has_builtin(__builtin_verbose_trap)``.
+
 ``__builtin_nondeterministic_value``
 
 
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 59f0aee2c0cedd..68447b19a4a107 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -775,6 +775,11 @@ class Expr : public ValueStmt {
  const Expr *PtrExpression, ASTContext &Ctx,
  EvalResult &Status) const;
 
+  /// If the current Expr can be evaluated to a pointer to a null-terminated
+  /// constant string, return the constant string (without the terminating 
null)
+  /// in Result. Return true if it succeeds.
+  bool tryEvaluateString(std::string &Result, ASTContext &Ctx) const;
+
   /// Enumeration used to describe the kind of Null pointer constant
   /// returned from \c isNullPointerConstant().
   enum NullPointerConstantKind {
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 22e616e6cde599..217c09e85a55cc 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1096,6 +1096,12 @@ def Trap : Builtin {
   let Prototype = "void()";
 }
 
+def VerboseTrap : Builtin {
+  let Spellings = ["__builtin_verbose_trap"];
+  let Attributes = [NoThrow, NoReturn];
+  let Prototype = "void(char const*)";
+}
+
 def Debugtrap : Builtin {
   let Spellings = ["__builtin_debugtrap"];
   let Attributes = [NoThrow];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a1c32abb4dcd88..40482a964b39d5 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic

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

2024-03-19 Thread Akira Hatanaka via cfe-commits


@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -triple arm64-apple-ios -std=c++20 -emit-llvm 
-debug-info-kind=limited %s -o - | FileCheck %s

ahatanak wrote:

https://llvm.org/docs/TestingGuide.html#best-practices-for-regression-tests 
recommends we run a minimal set of passes. As @pogo59 said, I think we should 
add a separate LLVM test if we want to test the merging behavior.

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] [X86][Headers] Specify result of NaN comparisons (PR #85862)

2024-03-19 Thread Phoebe Wang via cfe-commits


@@ -207,6 +207,8 @@ _mm256_div_ps(__m256 __a, __m256 __b)
 /// Compares two 256-bit vectors of [4 x double] and returns the greater
 ///of each pair of values.
 ///
+///If either value in a comparison is NaN, returns the value from \a __b.

phoebewang wrote:

Is it worth to mention the ±0 comparison?

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


[clang] [X86_64] fix arg pass error in struct. (PR #85394)

2024-03-19 Thread Longsheng Mou via cfe-commits

CoTinker wrote:

Thanks, I'll modify it according to this.

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


[clang] [X86_64] fix arg pass error in struct. (PR #85394)

2024-03-19 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

I think the logic the code is using is that t67 is actually properly aligned: 
it's a type with size 8 and alignment 4, so everything is fine.  If that's not 
right, we should tweak the relevant logic (around line 2104).

Specifically checking whether a type crosses an 8-byte boundary seems wrong; 
the only relevant text I can find in the standard is just "if the size of an 
object is larger than eight eightbytes, or it contains unaligned fields, it has 
class MEMORY."

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


[clang] [InstallAPI] Verify that declarations in headers map to exports found in dylib (PR #85348)

2024-03-19 Thread Cyndy Ishida via cfe-commits

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


[clang] 936519f - [InstallAPI] Verify that declarations in headers map to exports found in dylib (#85348)

2024-03-19 Thread via cfe-commits

Author: Cyndy Ishida
Date: 2024-03-19T18:36:46-07:00
New Revision: 936519f25cb4fabc19f1241e838e938926801156

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

LOG: [InstallAPI] Verify that declarations in headers map to exports found in 
dylib (#85348)

* This completes support for verifying every declaration found in a
header is discovered in the dylib. Diagnostics are reported for each
class for differences that are representable in TBD files.

* This patch also now captures unavailable attributes that depend on
target triples. This is needed for proper tbd file generation.

Added: 
clang/test/InstallAPI/availability.test
clang/test/InstallAPI/diagnostics-cpp.test
clang/test/InstallAPI/hiddens.test

Modified: 
clang/include/clang/AST/Availability.h
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
clang/include/clang/InstallAPI/DylibVerifier.h
clang/include/clang/InstallAPI/Frontend.h
clang/include/clang/InstallAPI/MachO.h
clang/lib/AST/Availability.cpp
clang/lib/InstallAPI/DylibVerifier.cpp
clang/lib/InstallAPI/Visitor.cpp
clang/tools/clang-installapi/ClangInstallAPI.cpp
clang/tools/clang-installapi/Options.cpp
clang/tools/diagtool/DiagnosticNames.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Availability.h 
b/clang/include/clang/AST/Availability.h
index 5cfbaf0cdfbd21..26ae622e5b4496 100644
--- a/clang/include/clang/AST/Availability.h
+++ b/clang/include/clang/AST/Availability.h
@@ -67,6 +67,7 @@ struct AvailabilityInfo {
   VersionTuple Introduced;
   VersionTuple Deprecated;
   VersionTuple Obsoleted;
+  bool Unavailable = false;
   bool UnconditionallyDeprecated = false;
   bool UnconditionallyUnavailable = false;
 
@@ -78,6 +79,12 @@ struct AvailabilityInfo {
   /// Check if the symbol has been obsoleted.
   bool isObsoleted() const { return !Obsoleted.empty(); }
 
+  /// Check if the symbol is unavailable unconditionally or
+  /// on the active platform and os version.
+  bool isUnavailable() const {
+return Unavailable || isUnconditionallyUnavailable();
+  }
+
   /// Check if the symbol is unconditionally deprecated.
   ///
   /// i.e. \code __attribute__((deprecated)) \endcode
@@ -91,9 +98,10 @@ struct AvailabilityInfo {
   }
 
   AvailabilityInfo(StringRef Domain, VersionTuple I, VersionTuple D,
-   VersionTuple O, bool UD, bool UU)
+   VersionTuple O, bool U, bool UD, bool UU)
   : Domain(Domain), Introduced(I), Deprecated(D), Obsoleted(O),
-UnconditionallyDeprecated(UD), UnconditionallyUnavailable(UU) {}
+Unavailable(U), UnconditionallyDeprecated(UD),
+UnconditionallyUnavailable(UU) {}
 
   friend bool operator==(const AvailabilityInfo &Lhs,
  const AvailabilityInfo &Rhs);
@@ -105,10 +113,10 @@ struct AvailabilityInfo {
 inline bool operator==(const AvailabilityInfo &Lhs,
const AvailabilityInfo &Rhs) {
   return std::tie(Lhs.Introduced, Lhs.Deprecated, Lhs.Obsoleted,
-  Lhs.UnconditionallyDeprecated,
+  Lhs.Unavailable, Lhs.UnconditionallyDeprecated,
   Lhs.UnconditionallyUnavailable) ==
  std::tie(Rhs.Introduced, Rhs.Deprecated, Rhs.Obsoleted,
-  Rhs.UnconditionallyDeprecated,
+  Rhs.Unavailable, Rhs.UnconditionallyDeprecated,
   Rhs.UnconditionallyUnavailable);
 }
 

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index f5ff89111d1110..dee555f783cc45 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1508,3 +1508,7 @@ def ReadOnlyPlacementChecks : 
DiagGroup<"read-only-types">;
 // Warnings and fixes to support the "safe buffers" programming model.
 def UnsafeBufferUsageInContainer : 
DiagGroup<"unsafe-buffer-usage-in-container">;
 def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage", 
[UnsafeBufferUsageInContainer]>;
+
+// Warnings and notes InstallAPI verification.
+def InstallAPIViolation : DiagGroup<"installapi-violation">;
+

diff  --git a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td 
b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
index 31be4f09cf3a1c..f99a5fca64cb46 100644
--- a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
+++ b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
@@ -17,4 +17,27 @@ def err_no_install_name : Error<"no install name specified: 
add -install_name ;
 } // end of command line category.
 
+let CategoryName = "Verification" in {
+def warn_target: Warning<"violations found for %0">, 
InGroup;
+def err_library_missing_symbol : Error<"declaration has ex

[clang] [clang][NFC] Add documentation for `CastExpr::path()`. (PR #85623)

2024-03-19 Thread John McCall via cfe-commits

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


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


[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #81545)

2024-03-19 Thread William Junda Huang via cfe-commits

https://github.com/huangjd updated 
https://github.com/llvm/llvm-project/pull/81545

>From f2c82758e1cba7773e41d941d2812c829c339675 Mon Sep 17 00:00:00 2001
From: William Huang 
Date: Mon, 12 Feb 2024 02:27:13 -0500
Subject: [PATCH 1/8] Add option to generate additional info for expression
 containing pointer of pointers.

Such expression does correspond to a variable in the source code thus
does not have a debug location. However the user may want to collect
sampling counter for memory accesses to analyze usage frequency of class
members. By enabling -fdebug_info_for_pointer_type a psuedo variable and
its debug info is generated in place whenever there's an intermediate
expression with pointer access.
---
 clang/include/clang/Basic/DebugOptions.def |  4 ++
 clang/include/clang/Driver/Options.td  |  4 ++
 clang/lib/CodeGen/CGDebugInfo.cpp  | 16 +
 clang/lib/CodeGen/CGDebugInfo.h|  6 ++
 clang/lib/CodeGen/CGDecl.cpp   |  4 ++
 clang/lib/CodeGen/CGExpr.cpp   | 79 ++
 clang/lib/CodeGen/CodeGenFunction.h|  5 ++
 clang/lib/Driver/ToolChains/Clang.cpp  |  3 +
 8 files changed, 121 insertions(+)

diff --git a/clang/include/clang/Basic/DebugOptions.def 
b/clang/include/clang/Basic/DebugOptions.def
index 7cd3edf08a17ea..6dd09f46842077 100644
--- a/clang/include/clang/Basic/DebugOptions.def
+++ b/clang/include/clang/Basic/DebugOptions.def
@@ -129,6 +129,10 @@ DEBUGOPT(CodeViewCommandLine, 1, 0)
 /// Whether emit extra debug info for sample pgo profile collection.
 DEBUGOPT(DebugInfoForProfiling, 1, 0)
 
+/// Whether to generate pseudo variables and their debug info for intermediate
+/// pointer accesses.
+DEBUGOPT(DebugInfoForPointerType, 1, 0)
+
 /// Whether to emit .debug_gnu_pubnames section instead of .debug_pubnames.
 DEBUGOPT(DebugNameTable, 2, 0)
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 7f4fa33748faca..96b22d3f7640dd 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1675,6 +1675,10 @@ defm debug_info_for_profiling : 
BoolFOption<"debug-info-for-profiling",
   PosFlag,
   NegFlag>;
+def fdebug_info_for_pointer_type : Flag<["-"], "fdebug-info-for-pointer-type">,
+  Group, Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Generate pseudo variables and their debug info for intermediate 
pointer accesses">,
+  MarshallingInfoFlag>;
 def fprofile_instr_generate : Flag<["-"], "fprofile-instr-generate">,
 Group, Visibility<[ClangOption, CLOption]>,
 HelpText<"Generate instrumented code to collect execution counts into 
default.profraw file (overridden by '=' form of option or LLVM_PROFILE_FILE env 
var)">;
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 0f3f684d61dc94..6ce40da22dc97d 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -5636,6 +5636,22 @@ void 
CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
   Var->addDebugInfo(GVE);
 }
 
+void CGDebugInfo::EmitPseudoVariable(llvm::AllocaInst *Alloca, QualType Ty,
+ SourceLocation Loc) {
+  llvm::DIFile *Unit = getOrCreateFile(Loc);
+  unsigned Line = getLineNumber(Loc);
+  unsigned Column = getColumnNumber(Loc);
+  llvm::DILocalVariable *D = DBuilder.createAutoVariable(
+  LexicalBlockStack.back(), Alloca->getName(), getOrCreateFile(Loc), Line,
+  getOrCreateType(Ty, Unit));
+  llvm::DILocation *DIL =
+  llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
+LexicalBlockStack.back(), CurInlinedAt);
+  SmallVector Expr;
+  DBuilder.insertDeclare(Alloca, D, DBuilder.createExpression(Expr), DIL,
+ Alloca->getParent());
+}
+
 void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
   const GlobalDecl GD) {
 
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 7b60e94555d060..a2c484f50b2bc5 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -529,6 +529,12 @@ class CGDebugInfo {
   /// Emit information about an external variable.
   void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
 
+  /// Emit debug information for a pseudo variable assigned to the value of an
+  /// intermediate expression, so that a performance counter can track the 
usage
+  /// of a specific expression of interest.
+  void EmitPseudoVariable(llvm::AllocaInst *Alloca, QualType Ty,
+  SourceLocation Loc);
+
   /// Emit information about global variable alias.
   void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl);
 
diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index bbe14ef4c17244..5f7b2529179003 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -793,6 +793,10 @@ void CodeGenFunct

[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #81545)

2024-03-19 Thread William Junda Huang via cfe-commits

huangjd wrote:

> Reading LLVM IR lit CHECK lines from clang codegen is a bit difficult - could 
> you include some simple examples (perhaps from the new clang tests in this 
> patch) showing the DWARF output just as comments in this review for something 
> more easily glanceable?

Attached is the output of the following command 

`clang ~/llvm-project/clang/test/CodeGenCXX/debug-info-ptr-to-ptr.cpp  
-fdebug-info-for-pointer-type -g2 -S -O3  -o /tmp/debug-info-ptr-to-ptr.txt`

[debug-info-ptr-to-ptr.txt](https://github.com/llvm/llvm-project/files/14659111/debug-info-ptr-to-ptr.txt)


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


[clang] [X86_64] fix empty structure vaarg in c++ (PR #77907)

2024-03-19 Thread Eli Friedman via cfe-commits


@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -x c -o - %s | 
FileCheck %s
+
+typedef struct { struct {} a; } empty;
+
+// CHECK-LABEL: define{{.*}} void @{{.*}}empty_record_test{{.*}}()
+empty empty_record_test(void) {
+// CHECK: [[RET:%[a-z]+]] = alloca %struct.empty, align 1

efriedma-quic wrote:

This test doesn't really make it obvious that this is working the way you want; 
I mean, the existence of TMP sort of hints at it, but it's not comprehensive.

I'd suggest:

- Make the va_list an argument to the function, instead of declaring it as a 
local.
- Consider autogenerating the CHECK lines using update_cc_test_checks.py

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


[clang] [X86_64] fix empty structure vaarg in c++ (PR #77907)

2024-03-19 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic commented:

Code change looks fine; the regression test needs a few tweaks.

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


[clang] [X86_64] fix empty structure vaarg in c++ (PR #77907)

2024-03-19 Thread Eli Friedman via cfe-commits

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


[clang] [Sema] Don't drop weak_import from a declaration that follows a declaration directly contained in a linkage-specification (PR #85886)

2024-03-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Akira Hatanaka (ahatanak)


Changes

Only drop it if the declaration follows a definition. I believe this is what 
33e022650adee965c65f9aea086ee74f3fd1bad5 was trying to do.

rdar://61865848

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaDecl.cpp (+1-2) 
- (modified) clang/test/SemaCXX/attr-weak.cpp (+7) 


``diff
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5850cd0ab6b9aa..2e45f1191273a4 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -4613,8 +4613,7 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult 
&Previous) {
   mergeDeclAttributes(New, Old);
   // Warn if an already-declared variable is made a weak_import in a subsequent
   // declaration
-  if (New->hasAttr() &&
-  Old->getStorageClass() == SC_None &&
+  if (New->hasAttr() && Old->isThisDeclarationADefinition() &&
   !Old->hasAttr()) {
 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
 Diag(Old->getLocation(), diag::note_previous_declaration);
diff --git a/clang/test/SemaCXX/attr-weak.cpp b/clang/test/SemaCXX/attr-weak.cpp
index f065bfd9483f8a..a2c5fd4abd35f6 100644
--- a/clang/test/SemaCXX/attr-weak.cpp
+++ b/clang/test/SemaCXX/attr-weak.cpp
@@ -55,3 +55,10 @@ constexpr bool weak_method_is_non_null = 
&WithWeakMember::weak_method != nullptr
 // virtual member function is present.
 constexpr bool virtual_weak_method_is_non_null = 
&WithWeakMember::virtual_weak_method != nullptr; // expected-error {{must be 
initialized by a constant expression}}
 // expected-note@-1 {{comparison against pointer to weak member 
'WithWeakMember::virtual_weak_method' can only be performed at runtime}}
+
+// Check that no warnings are emitted.
+extern "C" int g0;
+extern int g0 __attribute__((weak_import));
+
+extern "C" int g1 = 0; // expected-note {{previous definition is here}}
+extern int g1 __attribute__((weak_import)); // expected-warning {{attribute 
declaration must precede definition}}

``




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


[clang] [Sema] Don't drop weak_import from a declaration that follows a declaration directly contained in a linkage-specification (PR #85886)

2024-03-19 Thread Akira Hatanaka via cfe-commits

https://github.com/ahatanak created 
https://github.com/llvm/llvm-project/pull/85886

Only drop it if the declaration follows a definition. I believe this is what 
33e022650adee965c65f9aea086ee74f3fd1bad5 was trying to do.

rdar://61865848

>From 1ccbc2e2a3bdf127f5baeb22123c67428da4e656 Mon Sep 17 00:00:00 2001
From: Akira Hatanaka 
Date: Tue, 19 Mar 2024 15:50:00 -0700
Subject: [PATCH] [Sema] Don't drop weak_import from a declaration that follows
 a declaration directly contained in a linkage-specification

Only drop it if the declaration follows a definition. I believe this is
what 33e022650adee965c65f9aea086ee74f3fd1bad5 was trying to do.

rdar://61865848
---
 clang/lib/Sema/SemaDecl.cpp  | 3 +--
 clang/test/SemaCXX/attr-weak.cpp | 7 +++
 2 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5850cd0ab6b9aa..2e45f1191273a4 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -4613,8 +4613,7 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult 
&Previous) {
   mergeDeclAttributes(New, Old);
   // Warn if an already-declared variable is made a weak_import in a subsequent
   // declaration
-  if (New->hasAttr() &&
-  Old->getStorageClass() == SC_None &&
+  if (New->hasAttr() && Old->isThisDeclarationADefinition() &&
   !Old->hasAttr()) {
 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
 Diag(Old->getLocation(), diag::note_previous_declaration);
diff --git a/clang/test/SemaCXX/attr-weak.cpp b/clang/test/SemaCXX/attr-weak.cpp
index f065bfd9483f8a..a2c5fd4abd35f6 100644
--- a/clang/test/SemaCXX/attr-weak.cpp
+++ b/clang/test/SemaCXX/attr-weak.cpp
@@ -55,3 +55,10 @@ constexpr bool weak_method_is_non_null = 
&WithWeakMember::weak_method != nullptr
 // virtual member function is present.
 constexpr bool virtual_weak_method_is_non_null = 
&WithWeakMember::virtual_weak_method != nullptr; // expected-error {{must be 
initialized by a constant expression}}
 // expected-note@-1 {{comparison against pointer to weak member 
'WithWeakMember::virtual_weak_method' can only be performed at runtime}}
+
+// Check that no warnings are emitted.
+extern "C" int g0;
+extern int g0 __attribute__((weak_import));
+
+extern "C" int g1 = 0; // expected-note {{previous definition is here}}
+extern int g1 __attribute__((weak_import)); // expected-warning {{attribute 
declaration must precede definition}}

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


[clang] [InstallAPI] Verify that declarations in headers map to exports found in dylib (PR #85348)

2024-03-19 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/85348

>From d45081b0270f20a1313a35bd4ae12343e265ce7b Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Wed, 13 Mar 2024 18:57:14 -0700
Subject: [PATCH 1/5] [InstallAPI] Verify that declarations in header map to
 symbols found in dylib

* This patch completes support for verifying every declaration found in a
header is discovered in the dylib. Diagnostics are reported for each
class for differences that is representable in TBD files.

* This patch also now captures unavailable attributes that depend on target 
triples. This is needed for proper tbd file generation.
---
 clang/include/clang/AST/Availability.h|  13 +-
 .../clang/Basic/DiagnosticInstallAPIKinds.td  |  23 +
 .../include/clang/InstallAPI/DylibVerifier.h  |  57 +-
 clang/include/clang/InstallAPI/Frontend.h |   3 +
 clang/include/clang/InstallAPI/MachO.h|   1 +
 clang/lib/AST/Availability.cpp|   6 +-
 clang/lib/InstallAPI/DylibVerifier.cpp| 326 -
 clang/lib/InstallAPI/Visitor.cpp  |   2 +-
 clang/test/InstallAPI/availability.test   | 626 ++
 clang/test/InstallAPI/diagnostics-cpp.test| 461 +
 clang/test/InstallAPI/hiddens.test| 262 
 .../clang-installapi/ClangInstallAPI.cpp  |   6 +-
 clang/tools/clang-installapi/Options.cpp  |   4 +-
 13 files changed, 1766 insertions(+), 24 deletions(-)
 create mode 100644 clang/test/InstallAPI/availability.test
 create mode 100644 clang/test/InstallAPI/diagnostics-cpp.test
 create mode 100644 clang/test/InstallAPI/hiddens.test

diff --git a/clang/include/clang/AST/Availability.h 
b/clang/include/clang/AST/Availability.h
index 5cfbaf0cdfbd21..2ccc607d4b63dc 100644
--- a/clang/include/clang/AST/Availability.h
+++ b/clang/include/clang/AST/Availability.h
@@ -67,6 +67,7 @@ struct AvailabilityInfo {
   VersionTuple Introduced;
   VersionTuple Deprecated;
   VersionTuple Obsoleted;
+  bool Unavailable = false;
   bool UnconditionallyDeprecated = false;
   bool UnconditionallyUnavailable = false;
 
@@ -78,6 +79,9 @@ struct AvailabilityInfo {
   /// Check if the symbol has been obsoleted.
   bool isObsoleted() const { return !Obsoleted.empty(); }
 
+  /// Check if the symbol is unavailable for the active platform and os 
version.
+  bool isUnavailable() const { return Unavailable; }
+
   /// Check if the symbol is unconditionally deprecated.
   ///
   /// i.e. \code __attribute__((deprecated)) \endcode
@@ -91,9 +95,10 @@ struct AvailabilityInfo {
   }
 
   AvailabilityInfo(StringRef Domain, VersionTuple I, VersionTuple D,
-   VersionTuple O, bool UD, bool UU)
+   VersionTuple O, bool U, bool UD, bool UU)
   : Domain(Domain), Introduced(I), Deprecated(D), Obsoleted(O),
-UnconditionallyDeprecated(UD), UnconditionallyUnavailable(UU) {}
+Unavailable(U), UnconditionallyDeprecated(UD),
+UnconditionallyUnavailable(UU) {}
 
   friend bool operator==(const AvailabilityInfo &Lhs,
  const AvailabilityInfo &Rhs);
@@ -105,10 +110,10 @@ struct AvailabilityInfo {
 inline bool operator==(const AvailabilityInfo &Lhs,
const AvailabilityInfo &Rhs) {
   return std::tie(Lhs.Introduced, Lhs.Deprecated, Lhs.Obsoleted,
-  Lhs.UnconditionallyDeprecated,
+  Lhs.Unavailable, Lhs.UnconditionallyDeprecated,
   Lhs.UnconditionallyUnavailable) ==
  std::tie(Rhs.Introduced, Rhs.Deprecated, Rhs.Obsoleted,
-  Rhs.UnconditionallyDeprecated,
+  Rhs.Unavailable, Rhs.UnconditionallyDeprecated,
   Rhs.UnconditionallyUnavailable);
 }
 
diff --git a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td 
b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
index 31be4f09cf3a1c..5ed2e23425dc5f 100644
--- a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
+++ b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
@@ -17,4 +17,27 @@ def err_no_install_name : Error<"no install name specified: 
add -install_name ;
 } // end of command line category.
 
+let CategoryName = "Verification" in {
+def warn_target: Warning<"violations found for %0">;
+def err_library_missing_symbol : Error<"declaration has external linkage, but 
dynamic library doesn't have symbol '%0'">;
+def warn_library_missing_symbol : Warning<"declaration has external linkage, 
but dynamic library doesn't have symbol '%0'">;
+def err_library_hidden_symbol : Error<"declaration has external linkage, but 
symbol has internal linkage in dynamic library '%0'">;
+def warn_library_hidden_symbol : Warning<"declaration has external linkage, 
but symbol has internal linkage in dynamic library '%0'">;
+def warn_header_hidden_symbol : Warning<"symbol exported in dynamic library, 
but marked hidden in declaration '%0'">;
+def err_header_hidden_symbol : Error<"symbol exported in dynami

[clang] [Clang][Sema]: Allow flexible arrays in unions and alone in structs (PR #84428)

2024-03-19 Thread Eli Friedman via cfe-commits


@@ -1,13 +1,158 @@
-// RUN: %clang_cc1 %s -verify=c -fsyntax-only
-// RUN: %clang_cc1 %s -verify -fsyntax-only -x c++
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility
-// RUN: %clang_cc1 %s -verify -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c -fsyntax-only
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -x c++
+// RUN: %clang_cc1 %s -verify=stock,cpp -fsyntax-only -fms-compatibility -x c++
+// RUN: %clang_cc1 %s -verify=stock,c,gnu -fsyntax-only 
-Wgnu-flexible-array-union-member -Wgnu-empty-struct
+// RUN: %clang_cc1 %s -verify=stock,c,microsoft -fsyntax-only 
-fms-compatibility -Wmicrosoft
 
 // The test checks that an attempt to initialize union with flexible array
 // member with an initializer list doesn't crash clang.
 
 
-union { char x[]; } r = {0}; // c-error {{flexible array member 'x' in a union 
is not allowed}}
+union { char x[]; } r = {0}; /* gnu-warning {{flexible array member 'x' in a 
union is a GNU extension}}

efriedma-quic wrote:

I still don't see a testcase that covers this case

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


[clang] [llvm] [CodeGen][LLVM] Make the `va_list` related intrinsics generic. (PR #85460)

2024-03-19 Thread Alex Voicu via cfe-commits


@@ -0,0 +1,22 @@
+// REQUIRES: spirv-registered-target
+// RUN: %clang_cc1 -triple spirv64-unknown-unknown -fcuda-is-device -emit-llvm 
-o - %s | FileCheck %s
+struct x {

AlexVlx wrote:

Done.

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


[clang] 6f31cf5 - Revert "[clang-format][NFC] Eliminate the IsCpp parameter in all functions (#84599)"

2024-03-19 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2024-03-19T18:06:59-07:00
New Revision: 6f31cf51dfdc2c317ba8149d57d2ffb583403833

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

LOG: Revert "[clang-format][NFC] Eliminate the IsCpp parameter in all functions 
(#84599)"

This reverts c3a1eb6207d8 (and the related commit f3c5278efa3b) which makes
cleanupAroundReplacements() no longer thread-safe.

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/Format.cpp
clang/lib/Format/FormatToken.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/lib/Format/QualifierAlignmentFixer.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/TokenAnnotator.h
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index b3de317f16336c..6ccc81909368ef 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -232,9 +232,7 @@ ContinuationIndenter::ContinuationIndenter(const 
FormatStyle &Style,
 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
   Whitespaces(Whitespaces), Encoding(Encoding),
   BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
-  CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {
-  assert(IsCpp == Style.isCpp());
-}
+  CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
 
 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
 unsigned FirstStartColumn,
@@ -399,7 +397,7 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   }
   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
-State.Line->First->isNot(TT_AttributeSquare) && IsCpp &&
+State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
 // FIXME: This is a temporary workaround for the case where 
clang-format
 // sets BreakBeforeParameter to avoid bin packing and this creates a
 // completely unnecessary line break after a template type that isn't
@@ -670,8 +668,8 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   auto &CurrentState = State.Stack.back();
 
   bool DisallowLineBreaksOnThisLine =
-  Style.LambdaBodyIndentation == FormatStyle::LBI_Signature && IsCpp &&
-  [&Current] {
+  Style.LambdaBodyIndentation == FormatStyle::LBI_Signature &&
+  Style.isCpp() && [&Current] {
 // Deal with lambda arguments in C++. The aim here is to ensure that we
 // don't over-indent lambda function bodies when lambdas are passed as
 // arguments to function calls. We do this by ensuring that either all
@@ -1085,7 +1083,7 @@ unsigned 
ContinuationIndenter::addTokenOnNewLine(LineState &State,
   // Any break on this level means that the parent level has been broken
   // and we need to avoid bin packing there.
   bool NestedBlockSpecialCase =
-  (!IsCpp && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
+  (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
   (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 89813badc8ec20..63ec3a88978dd9 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3827,15 +3827,13 @@ tooling::Replacements sortUsingDeclarations(const 
FormatStyle &Style,
 }
 
 LangOptions getFormattingLangOpts(const FormatStyle &Style) {
-  IsCpp = Style.isCpp();
+  LangOptions LangOpts;
 
   FormatStyle::LanguageStandard LexingStd = Style.Standard;
   if (LexingStd == FormatStyle::LS_Auto)
 LexingStd = FormatStyle::LS_Latest;
   if (LexingStd == FormatStyle::LS_Latest)
 LexingStd = FormatStyle::LS_Cpp20;
-
-  LangOptions LangOpts;
   LangOpts.CPlusPlus = 1;
   LangOpts.CPlusPlus11 = LexingStd >= FormatStyle::LS_Cpp11;
   LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
@@ -3846,8 +3844,10 @@ LangOptions getFormattingLangOpts(const FormatStyle 
&Style) {
   // the sequence "<::" will be unconditionally treated as "[:".
   // Cf. Lexer::LexTokenInternal.
   LangOpts.Digraphs = LexingStd >= FormatStyle::LS_Cpp11;
+
   LangOpts.LineComment = 1;
-  LangOpts.CXXOperatorNames = IsCpp;
+  bool AlternativeOp

[clang] [clang-format] Fix FormatToken::isSimpleTypeSpecifier() (PR #85564)

2024-03-19 Thread Owen Pan via cfe-commits

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


[clang] [clang][RISCV] Enable RVV with function attribute __attribute__((target("arch=+v"))) (PR #83674)

2024-03-19 Thread Michael Maitland via cfe-commits

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


[clang] [clang][RISCV] Enable RVV with function attribute __attribute__((target("arch=+v"))) (PR #83674)

2024-03-19 Thread Michael Maitland via cfe-commits

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


[clang] [clang][RISCV] Enable RVV with function attribute __attribute__((target("arch=+v"))) (PR #83674)

2024-03-19 Thread Michael Maitland via cfe-commits


@@ -8927,8 +8927,13 @@ void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
 }
   }
 
-  if (T->isRVVSizelessBuiltinType())
-checkRVVTypeSupport(T, NewVD->getLocation(), cast(CurContext));
+  if (T->isRVVSizelessBuiltinType() && isa(CurContext)) {
+const FunctionDecl *FD = cast(CurContext);
+llvm::StringMap CallerFeatureMap;
+Context.getFunctionFeatureMap(CallerFeatureMap, FD);

michaelmaitland wrote:

Would it make sense to store a `Map` so 
`RISCVTargetInfo::initFeatureMap` only builds the feature map one time per 
FunctionDecl?

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


[clang] f5f3d5d - [Clang][Sema] Fix a crash in lambda instantiation (#85565)

2024-03-19 Thread via cfe-commits

Author: Qizhi Hu
Date: 2024-03-20T08:33:30+08:00
New Revision: f5f3d5d6534f0a38c771119653dac3330c9f207f

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

LOG: [Clang][Sema] Fix a crash in lambda instantiation (#85565)

Fix https://github.com/llvm/llvm-project/issues/85343
When build lambda expression in lambda instantiation, `ThisType` is
required in `Sema::CheckCXXThisCapture` to build `this` capture. Set
`this` type by import `Sema::CXXThisScopeRAII` and it will be used later
in lambda expression transformation.

Co-authored-by: huqizhi <836744...@qq.com>

Added: 
clang/test/Sema/PR85343.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/TreeTransform.h

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5ddad61e27c909..0ce3cbe3266efd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -401,6 +401,7 @@ Bug Fixes to C++ Support
   expression references to an entity declared outside of the lambda. (#GH64808)
 - Clang's __builtin_bit_cast will now produce a constant value for records 
with empty bases. See:
   (#GH82383)
+- Fix a crash when instantiating a lambda that captures ``this`` outside of 
its context. Fixes (#GH85343).
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 2d22692f3ab750..f2f7d7ab9c7c38 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -13714,6 +13714,16 @@ TreeTransform::TransformLambdaExpr(LambdaExpr 
*E) {
 
 // Capturing 'this' is trivial.
 if (C->capturesThis()) {
+  // If this is a lambda that is part of a default member initialiser
+  // and which we're instantiating outside the class that 'this' is
+  // supposed to refer to, adjust the type of 'this' accordingly.
+  //
+  // Otherwise, leave the type of 'this' as-is.
+  Sema::CXXThisScopeRAII ThisScope(
+  getSema(),
+  dyn_cast_if_present(
+  getSema().getFunctionLevelDeclContext()),
+  Qualifiers());
   getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
 /*BuildAndDiagnose*/ true, nullptr,
 C->getCaptureKind() == LCK_StarThis);

diff  --git a/clang/test/Sema/PR85343.cpp b/clang/test/Sema/PR85343.cpp
new file mode 100644
index 00..d90ef19d423455
--- /dev/null
+++ b/clang/test/Sema/PR85343.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -std=c++14 -verify %s
+// expected-no-diagnostics
+
+template  auto ab() -> c ;
+
+template  struct e {};
+
+template  struct ac {
+  template  static e()(ab))> i;
+  decltype(i) j;
+};
+
+struct d {
+  template 
+  d(f) { 
+ac a;
+  }
+};
+struct a {
+  d b = [=](auto) { (void)[this] {}; };
+};
+void b() { new a; }



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


[clang] [Clang][Sema] Fix a crash in lambda instantiation (PR #85565)

2024-03-19 Thread Qizhi Hu via cfe-commits

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


[clang] [llvm] [InstCombine] Canonicalize `(sitofp x)` -> `(uitofp x)` if `x >= 0` (PR #82404)

2024-03-19 Thread via cfe-commits

goldsteinn wrote:

Ill revert this. I'll re-post if I get around to adding a flag.
Any chance you can still create a repro of the bug your seeing for if I re-post?

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


[clang] [llvm] [InstCombine] Canonicalize `(sitofp x)` -> `(uitofp x)` if `x >= 0` (PR #82404)

2024-03-19 Thread via cfe-commits

asmok-g wrote:

Heads up: we noticed at google that this is causing the following test to fail:

https://github.com/google/swiftshader/blob/master/tests/ReactorUnitTests/ReactorUnitTests.cpp#L1312

I need to put a more proper reproducer, but thought that at least posting the 
heads-up might be faster to unblock us and maybe the problem is clear. I see 
that adding a flag vs reverting is already brought up in the last comment, 
what's the plan for that ?


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


[clang] [lld] [llvm] [IR] Change representation of getelementptr inrange (PR #84341)

2024-03-19 Thread Nicolai Hähnle via cfe-commits

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


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


[clang] [lld] [llvm] [IR] Change representation of getelementptr inrange (PR #84341)

2024-03-19 Thread Nicolai Hähnle via cfe-commits


@@ -47,28 +47,66 @@ static bool splitGlobal(GlobalVariable &GV) {
   if (!Init)
 return false;
 
-  // Verify that each user of the global is an inrange getelementptr constant.
-  // From this it follows that any loads from or stores to that global must use
-  // a pointer derived from an inrange getelementptr constant, which is
-  // sufficient to allow us to apply the splitting transform.
+  const DataLayout &DL = GV.getParent()->getDataLayout();
+  const StructLayout *SL = DL.getStructLayout(Init->getType());
+  ArrayRef MemberOffsets = SL->getMemberOffsets();
+  unsigned IndexWidth = DL.getIndexTypeSizeInBits(GV.getType());
+
+  // Verify that each user of the global is an inrange getelementptr constant,
+  // and collect information on how it relates to the global.
+  struct GEPInfo {
+GEPOperator *GEP;
+unsigned MemberIndex;
+APInt MemberRelativeOffset;
+
+GEPInfo(GEPOperator *GEP, unsigned MemberIndex, APInt MemberRelativeOffset)
+: GEP(GEP), MemberIndex(MemberIndex),
+  MemberRelativeOffset(std::move(MemberRelativeOffset)) {}
+  };
+  SmallVector Infos;
   for (User *U : GV.users()) {
-if (!isa(U))
+auto *GEP = dyn_cast(U);
+if (!GEP)
   return false;
 
-auto *GEP = dyn_cast(U);
-if (!GEP || !GEP->getInRangeIndex() || *GEP->getInRangeIndex() != 1 ||
-!isa(GEP->getOperand(1)) ||
-!cast(GEP->getOperand(1))->isZero() ||
-!isa(GEP->getOperand(2)))
+std::optional InRange = GEP->getInRange();
+if (!InRange)
+  return false;
+
+APInt Offset(IndexWidth, 0);
+if (!GEP->accumulateConstantOffset(DL, Offset))
+  return false;
+
+// Determine source-relative inrange.
+ConstantRange SrcInRange = InRange->sextOrTrunc(IndexWidth).add(Offset);
+
+// Check that the GEP offset is in the range (treating upper bound as
+// inclusive here).
+if (!SrcInRange.contains(Offset) && SrcInRange.getUpper() != Offset)
+  return false;
+
+// Find which struct member the range corresponds to.
+if (SrcInRange.getLower().uge(SL->getSizeInBytes()))
   return false;
+
+unsigned MemberIndex =
+SL->getElementContainingOffset(SrcInRange.getLower().getZExtValue());

nhaehnle wrote:

You're right, I missed that it's an unsigned comparison.

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


[clang] [llvm] [openmp] [OpenMP] Increment kernel args version, used by runtime for detecting dyn_ptr. (PR #85363)

2024-03-19 Thread via cfe-commits

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


[clang] [llvm] [Clang][ARM][AArch64] Alway emit protection attributes for functions. (PR #82819)

2024-03-19 Thread Daniel Kiss via cfe-commits

https://github.com/DanielKristofKiss updated 
https://github.com/llvm/llvm-project/pull/82819

>From 5973486010ffe387789e8129d53a2b9d0cc4ca69 Mon Sep 17 00:00:00 2001
From: Daniel Kiss 
Date: Mon, 22 Jan 2024 11:33:15 +0100
Subject: [PATCH 1/2] Emit attributes for functions always.

Branch protection, sign return address, guarded control stack flags are
only emitted as module flags if not specified per function.

The inliner might inline functions with different set of flags as it
doesn't see the flags.

In case of LTO build the module flags get merged with the `min` rule which means
if one of the modules is not build with PAC/BTI then the features will be turned
off on all functions due to the functions takes the branch-protection and
sign-return-address features from the module flags. The sign-return-address is
function level option therefore it is expected functions from files that are
compiled with -mbranch-protection=pac-ret to be protected but in LTO case this
might not happen. This patch adds the flags to functions in case of an LTO build
therefore they don't need to rely on the module flag.
---
 clang/include/clang/Basic/TargetInfo.h| 44 +--
 clang/lib/CodeGen/Targets/AArch64.cpp | 43 ++
 clang/lib/CodeGen/Targets/ARM.cpp |  8 ++--
 .../CodeGen/aarch64-branch-protection-attr.c  | 26 +--
 .../CodeGen/aarch64-sign-return-address.c | 12 +++--
 clang/test/CodeGen/aarch64-targetattr.c   |  2 +-
 .../CodeGen/arm-branch-protection-attr-1.c| 12 ++---
 .../CodeGen/arm-branch-protection-attr-2.c| 13 --
 .../test/Frontend/arm-branch-protection-lto.c | 22 ++
 .../SelectionDAG/SelectionDAGBuilder.cpp  | 12 +
 llvm/lib/IR/Verifier.cpp  | 21 -
 llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp |  6 +--
 .../AArch64/AArch64MachineFunctionInfo.cpp| 39 +++-
 .../lib/Target/ARM/ARMMachineFunctionInfo.cpp | 22 +-
 llvm/lib/Transforms/IPO/LowerTypeTests.cpp|  6 ++-
 ...ranch-target-enforcement-indirect-calls.ll | 18 
 .../CodeGen/AArch64/bti-branch-relaxation.ll  |  2 +-
 llvm/test/CodeGen/AArch64/kcfi-bti.ll |  7 +--
 ...machine-outliner-2fixup-blr-terminator.mir |  2 +-
 .../CodeGen/AArch64/machine-outliner-bti.mir  |  2 +-
 .../AArch64/machine-outliner-outline-bti.ll   |  4 +-
 .../AArch64/note-gnu-property-pac-bti-0.ll|  2 +-
 .../AArch64/note-gnu-property-pac-bti-4.ll|  4 +-
 .../AArch64/pacbti-llvm-generated-funcs-1.ll  |  4 +-
 .../AArch64/pacbti-llvm-generated-funcs-2.ll  |  4 +-
 .../CodeGen/AArch64/pacbti-module-attrs.ll| 12 ++---
 .../AArch64/patchable-function-entry-bti.ll   | 10 ++---
 .../CodeGen/AArch64/setjmp-bti-outliner.ll| 15 +++
 llvm/test/CodeGen/AArch64/setjmp-bti.ll   |  6 +--
 .../AArch64/sign-return-address-pauth-lr.ll   | 36 +++
 .../CodeGen/AArch64/sign-return-address.ll|  8 ++--
 llvm/test/CodeGen/AArch64/wineh-bti.ll|  7 +--
 llvm/test/CodeGen/AArch64/wineh-pac.ll|  7 +--
 llvm/test/CodeGen/ARM/setjmp-bti-basic.ll |  5 +--
 llvm/test/CodeGen/ARM/setjmp-bti-outliner.ll  |  7 +--
 llvm/test/CodeGen/Thumb2/bti-entry-blocks.ll  |  7 +--
 .../CodeGen/Thumb2/bti-indirect-branches.ll   |  9 ++--
 llvm/test/CodeGen/Thumb2/bti-outliner-1.ll|  9 ++--
 llvm/test/CodeGen/Thumb2/bti-outliner-2.ll| 12 ++---
 .../CodeGen/Thumb2/bti-outliner-cost-2.ll |  6 +--
 .../test/CodeGen/Thumb2/bti-pac-replace-1.mir |  8 +---
 llvm/test/CodeGen/Thumb2/bti-pac-replace-2.ll |  7 +--
 llvm/test/CodeGen/Thumb2/jump-table-bti.ll| 10 ++---
 llvm/test/CodeGen/Thumb2/pacbti-m-basic.ll|  6 +--
 .../Thumb2/pacbti-m-indirect-tail-call.ll |  2 +-
 .../CodeGen/Thumb2/pacbti-m-outliner-1.ll |  2 +-
 .../CodeGen/Thumb2/pacbti-m-outliner-3.ll |  2 +-
 .../CodeGen/Thumb2/pacbti-m-outliner-4.ll |  6 +--
 .../CodeGen/Thumb2/pacbti-m-outliner-5.ll |  4 +-
 .../test/CodeGen/Thumb2/pacbti-m-overalign.ll |  2 +-
 .../test/CodeGen/Thumb2/pacbti-m-stack-arg.ll |  4 +-
 .../Thumb2/pacbti-m-unsupported-arch.ll   |  8 +---
 .../test/CodeGen/Thumb2/pacbti-m-varargs-1.ll |  4 +-
 .../test/CodeGen/Thumb2/pacbti-m-varargs-2.ll |  4 +-
 llvm/test/CodeGen/Thumb2/pacbti-m-vla.ll  |  2 +-
 .../AArch64/link-branch-target-enforcement.ll |  2 +-
 .../Inline/inline-sign-return-address.ll  | 13 +++---
 .../LowerTypeTests/function-arm-thumb.ll  |  2 +-
 .../LowerTypeTests/function-thumb-bti.ll  |  4 +-
 .../Transforms/LowerTypeTests/function.ll |  4 +-
 60 files changed, 277 insertions(+), 312 deletions(-)
 create mode 100644 clang/test/Frontend/arm-branch-protection-lto.c

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 374595edd2ce4a..5f6f5bbba8e56a 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -32,7 +32,9 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/AD

[clang] [llvm] [Clang][ARM][AArch64] Alway emit protection attributes for functions. (PR #82819)

2024-03-19 Thread Daniel Kiss via cfe-commits

DanielKristofKiss wrote:

#83154 merged into this one as no test would pass without that.
todo:
update #83153  with the new semantic.
#84494 and #84804 to be merged into 1 PR  and add support this semantic.

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


[clang] [llvm] [Clang][ARM][AArch64] Alway emit protection attributes for functions. (PR #82819)

2024-03-19 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 d4fb50d3e5fdf4aba4981371af53aa8fbbd6bf20 
5973486010ffe387789e8129d53a2b9d0cc4ca69 -- 
clang/test/Frontend/arm-branch-protection-lto.c 
clang/include/clang/Basic/TargetInfo.h clang/lib/CodeGen/Targets/AArch64.cpp 
clang/lib/CodeGen/Targets/ARM.cpp 
clang/test/CodeGen/aarch64-branch-protection-attr.c 
clang/test/CodeGen/aarch64-sign-return-address.c 
clang/test/CodeGen/aarch64-targetattr.c 
clang/test/CodeGen/arm-branch-protection-attr-1.c 
clang/test/CodeGen/arm-branch-protection-attr-2.c 
llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp llvm/lib/IR/Verifier.cpp 
llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp 
llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp 
llvm/lib/Target/ARM/ARMMachineFunctionInfo.cpp 
llvm/lib/Transforms/IPO/LowerTypeTests.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/IR/Verifier.cpp b/llvm/lib/IR/Verifier.cpp
index 5e673c72fc..c5746ea764 100644
--- a/llvm/lib/IR/Verifier.cpp
+++ b/llvm/lib/IR/Verifier.cpp
@@ -2324,7 +2324,8 @@ void Verifier::verifyFunctionAttrs(FunctionType *FT, 
AttributeList Attrs,
   CheckFailed("invalid value for 'sign-return-address-key' attribute: " + 
S,
   V);
 if (auto AA = Attrs.getFnAttr("sign-return-address"); !AA.isValid()) {
-  CheckFailed("invalid value for 'sign-return-address-key' present without 
sign-return-address ");
+  CheckFailed("invalid value for 'sign-return-address-key' present without 
"
+  "sign-return-address ");
 }
   }
 
@@ -2345,8 +2346,8 @@ void Verifier::verifyFunctionAttrs(FunctionType *FT, 
AttributeList Attrs,
   if (auto A = Attrs.getFnAttr("guarded-control-stack"); A.isValid()) {
 StringRef S = A.getValueAsString();
 if (S != "")
-  CheckFailed(
-  "invalid value for 'guarded-control-stack' attribute: " + S, V);
+  CheckFailed("invalid value for 'guarded-control-stack' attribute: " + S,
+  V);
   }
 
   if (auto A = Attrs.getFnAttr("vector-function-abi-variant"); A.isValid()) {
diff --git a/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp 
b/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
index 4869dbb1f6..eac3429e9e 100644
--- a/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
@@ -80,10 +80,8 @@ AArch64FunctionInfo::AArch64FunctionInfo(const Function &F,
   IsMTETagged = F.hasFnAttribute(Attribute::SanitizeMemTag);
 
   // BTI/PAuthLR are set on the function attribute.
-  BranchTargetEnforcement =
-  F.hasFnAttribute("branch-target-enforcement");
-  BranchProtectionPAuthLR =
-  F.hasFnAttribute("branch-protection-pauth-lr");
+  BranchTargetEnforcement = F.hasFnAttribute("branch-target-enforcement");
+  BranchProtectionPAuthLR = F.hasFnAttribute("branch-protection-pauth-lr");
 
   // The default stack probe size is 4096 if the function has no
   // stack-probe-size attribute. This is a safe default because it is the

``




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


[clang] [llvm] [Clang][ARM][AArch64] Alway emit protection attributes for functions. (PR #82819)

2024-03-19 Thread Daniel Kiss via cfe-commits

https://github.com/DanielKristofKiss updated 
https://github.com/llvm/llvm-project/pull/82819

>From 5973486010ffe387789e8129d53a2b9d0cc4ca69 Mon Sep 17 00:00:00 2001
From: Daniel Kiss 
Date: Mon, 22 Jan 2024 11:33:15 +0100
Subject: [PATCH] Emit attributes for functions always.

Branch protection, sign return address, guarded control stack flags are
only emitted as module flags if not specified per function.

The inliner might inline functions with different set of flags as it
doesn't see the flags.

In case of LTO build the module flags get merged with the `min` rule which means
if one of the modules is not build with PAC/BTI then the features will be turned
off on all functions due to the functions takes the branch-protection and
sign-return-address features from the module flags. The sign-return-address is
function level option therefore it is expected functions from files that are
compiled with -mbranch-protection=pac-ret to be protected but in LTO case this
might not happen. This patch adds the flags to functions in case of an LTO build
therefore they don't need to rely on the module flag.
---
 clang/include/clang/Basic/TargetInfo.h| 44 +--
 clang/lib/CodeGen/Targets/AArch64.cpp | 43 ++
 clang/lib/CodeGen/Targets/ARM.cpp |  8 ++--
 .../CodeGen/aarch64-branch-protection-attr.c  | 26 +--
 .../CodeGen/aarch64-sign-return-address.c | 12 +++--
 clang/test/CodeGen/aarch64-targetattr.c   |  2 +-
 .../CodeGen/arm-branch-protection-attr-1.c| 12 ++---
 .../CodeGen/arm-branch-protection-attr-2.c| 13 --
 .../test/Frontend/arm-branch-protection-lto.c | 22 ++
 .../SelectionDAG/SelectionDAGBuilder.cpp  | 12 +
 llvm/lib/IR/Verifier.cpp  | 21 -
 llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp |  6 +--
 .../AArch64/AArch64MachineFunctionInfo.cpp| 39 +++-
 .../lib/Target/ARM/ARMMachineFunctionInfo.cpp | 22 +-
 llvm/lib/Transforms/IPO/LowerTypeTests.cpp|  6 ++-
 ...ranch-target-enforcement-indirect-calls.ll | 18 
 .../CodeGen/AArch64/bti-branch-relaxation.ll  |  2 +-
 llvm/test/CodeGen/AArch64/kcfi-bti.ll |  7 +--
 ...machine-outliner-2fixup-blr-terminator.mir |  2 +-
 .../CodeGen/AArch64/machine-outliner-bti.mir  |  2 +-
 .../AArch64/machine-outliner-outline-bti.ll   |  4 +-
 .../AArch64/note-gnu-property-pac-bti-0.ll|  2 +-
 .../AArch64/note-gnu-property-pac-bti-4.ll|  4 +-
 .../AArch64/pacbti-llvm-generated-funcs-1.ll  |  4 +-
 .../AArch64/pacbti-llvm-generated-funcs-2.ll  |  4 +-
 .../CodeGen/AArch64/pacbti-module-attrs.ll| 12 ++---
 .../AArch64/patchable-function-entry-bti.ll   | 10 ++---
 .../CodeGen/AArch64/setjmp-bti-outliner.ll| 15 +++
 llvm/test/CodeGen/AArch64/setjmp-bti.ll   |  6 +--
 .../AArch64/sign-return-address-pauth-lr.ll   | 36 +++
 .../CodeGen/AArch64/sign-return-address.ll|  8 ++--
 llvm/test/CodeGen/AArch64/wineh-bti.ll|  7 +--
 llvm/test/CodeGen/AArch64/wineh-pac.ll|  7 +--
 llvm/test/CodeGen/ARM/setjmp-bti-basic.ll |  5 +--
 llvm/test/CodeGen/ARM/setjmp-bti-outliner.ll  |  7 +--
 llvm/test/CodeGen/Thumb2/bti-entry-blocks.ll  |  7 +--
 .../CodeGen/Thumb2/bti-indirect-branches.ll   |  9 ++--
 llvm/test/CodeGen/Thumb2/bti-outliner-1.ll|  9 ++--
 llvm/test/CodeGen/Thumb2/bti-outliner-2.ll| 12 ++---
 .../CodeGen/Thumb2/bti-outliner-cost-2.ll |  6 +--
 .../test/CodeGen/Thumb2/bti-pac-replace-1.mir |  8 +---
 llvm/test/CodeGen/Thumb2/bti-pac-replace-2.ll |  7 +--
 llvm/test/CodeGen/Thumb2/jump-table-bti.ll| 10 ++---
 llvm/test/CodeGen/Thumb2/pacbti-m-basic.ll|  6 +--
 .../Thumb2/pacbti-m-indirect-tail-call.ll |  2 +-
 .../CodeGen/Thumb2/pacbti-m-outliner-1.ll |  2 +-
 .../CodeGen/Thumb2/pacbti-m-outliner-3.ll |  2 +-
 .../CodeGen/Thumb2/pacbti-m-outliner-4.ll |  6 +--
 .../CodeGen/Thumb2/pacbti-m-outliner-5.ll |  4 +-
 .../test/CodeGen/Thumb2/pacbti-m-overalign.ll |  2 +-
 .../test/CodeGen/Thumb2/pacbti-m-stack-arg.ll |  4 +-
 .../Thumb2/pacbti-m-unsupported-arch.ll   |  8 +---
 .../test/CodeGen/Thumb2/pacbti-m-varargs-1.ll |  4 +-
 .../test/CodeGen/Thumb2/pacbti-m-varargs-2.ll |  4 +-
 llvm/test/CodeGen/Thumb2/pacbti-m-vla.ll  |  2 +-
 .../AArch64/link-branch-target-enforcement.ll |  2 +-
 .../Inline/inline-sign-return-address.ll  | 13 +++---
 .../LowerTypeTests/function-arm-thumb.ll  |  2 +-
 .../LowerTypeTests/function-thumb-bti.ll  |  4 +-
 .../Transforms/LowerTypeTests/function.ll |  4 +-
 60 files changed, 277 insertions(+), 312 deletions(-)
 create mode 100644 clang/test/Frontend/arm-branch-protection-lto.c

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 374595edd2ce4a..5f6f5bbba8e56a 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -32,7 +32,9 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/St

[clang] clang driver: enable fast unaligned access for Android on RISCV64 (PR #85704)

2024-03-19 Thread via cfe-commits


@@ -167,6 +167,10 @@ void riscv::getRISCVTargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
 Features.push_back("-relax");
   }
 
+  // Android requires fast unaligned access on RISCV64.

pirama-arumuga-nainar wrote:

I think the concern is that `-target riscv64-linux-android -mstrict-align` will 
add `+fast-unaligned-access` and `-fast-unaligned-access` - which would not be 
handled correctly by `unifyTargetFeatures`.

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


[clang] [FMV] Emit the resolver along with the default version definition. (PR #84405)

2024-03-19 Thread Jon Roelofs via cfe-commits

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

All three LGTM.

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


[clang] [InstallAPI] Verify that declarations in headers map to exports found in dylib (PR #85348)

2024-03-19 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/85348

>From d45081b0270f20a1313a35bd4ae12343e265ce7b Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Wed, 13 Mar 2024 18:57:14 -0700
Subject: [PATCH 1/4] [InstallAPI] Verify that declarations in header map to
 symbols found in dylib

* This patch completes support for verifying every declaration found in a
header is discovered in the dylib. Diagnostics are reported for each
class for differences that is representable in TBD files.

* This patch also now captures unavailable attributes that depend on target 
triples. This is needed for proper tbd file generation.
---
 clang/include/clang/AST/Availability.h|  13 +-
 .../clang/Basic/DiagnosticInstallAPIKinds.td  |  23 +
 .../include/clang/InstallAPI/DylibVerifier.h  |  57 +-
 clang/include/clang/InstallAPI/Frontend.h |   3 +
 clang/include/clang/InstallAPI/MachO.h|   1 +
 clang/lib/AST/Availability.cpp|   6 +-
 clang/lib/InstallAPI/DylibVerifier.cpp| 326 -
 clang/lib/InstallAPI/Visitor.cpp  |   2 +-
 clang/test/InstallAPI/availability.test   | 626 ++
 clang/test/InstallAPI/diagnostics-cpp.test| 461 +
 clang/test/InstallAPI/hiddens.test| 262 
 .../clang-installapi/ClangInstallAPI.cpp  |   6 +-
 clang/tools/clang-installapi/Options.cpp  |   4 +-
 13 files changed, 1766 insertions(+), 24 deletions(-)
 create mode 100644 clang/test/InstallAPI/availability.test
 create mode 100644 clang/test/InstallAPI/diagnostics-cpp.test
 create mode 100644 clang/test/InstallAPI/hiddens.test

diff --git a/clang/include/clang/AST/Availability.h 
b/clang/include/clang/AST/Availability.h
index 5cfbaf0cdfbd21..2ccc607d4b63dc 100644
--- a/clang/include/clang/AST/Availability.h
+++ b/clang/include/clang/AST/Availability.h
@@ -67,6 +67,7 @@ struct AvailabilityInfo {
   VersionTuple Introduced;
   VersionTuple Deprecated;
   VersionTuple Obsoleted;
+  bool Unavailable = false;
   bool UnconditionallyDeprecated = false;
   bool UnconditionallyUnavailable = false;
 
@@ -78,6 +79,9 @@ struct AvailabilityInfo {
   /// Check if the symbol has been obsoleted.
   bool isObsoleted() const { return !Obsoleted.empty(); }
 
+  /// Check if the symbol is unavailable for the active platform and os 
version.
+  bool isUnavailable() const { return Unavailable; }
+
   /// Check if the symbol is unconditionally deprecated.
   ///
   /// i.e. \code __attribute__((deprecated)) \endcode
@@ -91,9 +95,10 @@ struct AvailabilityInfo {
   }
 
   AvailabilityInfo(StringRef Domain, VersionTuple I, VersionTuple D,
-   VersionTuple O, bool UD, bool UU)
+   VersionTuple O, bool U, bool UD, bool UU)
   : Domain(Domain), Introduced(I), Deprecated(D), Obsoleted(O),
-UnconditionallyDeprecated(UD), UnconditionallyUnavailable(UU) {}
+Unavailable(U), UnconditionallyDeprecated(UD),
+UnconditionallyUnavailable(UU) {}
 
   friend bool operator==(const AvailabilityInfo &Lhs,
  const AvailabilityInfo &Rhs);
@@ -105,10 +110,10 @@ struct AvailabilityInfo {
 inline bool operator==(const AvailabilityInfo &Lhs,
const AvailabilityInfo &Rhs) {
   return std::tie(Lhs.Introduced, Lhs.Deprecated, Lhs.Obsoleted,
-  Lhs.UnconditionallyDeprecated,
+  Lhs.Unavailable, Lhs.UnconditionallyDeprecated,
   Lhs.UnconditionallyUnavailable) ==
  std::tie(Rhs.Introduced, Rhs.Deprecated, Rhs.Obsoleted,
-  Rhs.UnconditionallyDeprecated,
+  Rhs.Unavailable, Rhs.UnconditionallyDeprecated,
   Rhs.UnconditionallyUnavailable);
 }
 
diff --git a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td 
b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
index 31be4f09cf3a1c..5ed2e23425dc5f 100644
--- a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
+++ b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
@@ -17,4 +17,27 @@ def err_no_install_name : Error<"no install name specified: 
add -install_name ;
 } // end of command line category.
 
+let CategoryName = "Verification" in {
+def warn_target: Warning<"violations found for %0">;
+def err_library_missing_symbol : Error<"declaration has external linkage, but 
dynamic library doesn't have symbol '%0'">;
+def warn_library_missing_symbol : Warning<"declaration has external linkage, 
but dynamic library doesn't have symbol '%0'">;
+def err_library_hidden_symbol : Error<"declaration has external linkage, but 
symbol has internal linkage in dynamic library '%0'">;
+def warn_library_hidden_symbol : Warning<"declaration has external linkage, 
but symbol has internal linkage in dynamic library '%0'">;
+def warn_header_hidden_symbol : Warning<"symbol exported in dynamic library, 
but marked hidden in declaration '%0'">;
+def err_header_hidden_symbol : Error<"symbol exported in dynami

[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-19 Thread Vassil Vassilev via cfe-commits

vgvassilev wrote:

> Not entirely certain what you're asking, but MSVC CRT does have a definition 
> for sized delete:
> 
> ```
> _CRT_SECURITYCRITICAL_ATTRIBUTE
> void __CRTDECL operator delete(void* const block, size_t const) noexcept
> {
> operator delete(block);
> }
> ```
> 
> in `crt\src\vcruntime\delete_scalar_size.cpp`

In that case for this test (or likely the entire interpreter library) we will 
have export that symbol with the linker. Something similar is done here: 
https://github.com/llvm/llvm-project/pull/84769/files#diff-d7f5dca2bd540f1b18ba90a66497b6b12e40fd07058b70f0fdec638c8e97406eR14-R71
 as part of #84769. Unfortunately, this is the only reliable way as of today to 
export crt symbols to the JIT. cc: @lhames, @fsfod.


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


[clang] [InstallAPI] Verify that declarations in headers map to exports found in dylib (PR #85348)

2024-03-19 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/85348

>From d45081b0270f20a1313a35bd4ae12343e265ce7b Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Wed, 13 Mar 2024 18:57:14 -0700
Subject: [PATCH 1/3] [InstallAPI] Verify that declarations in header map to
 symbols found in dylib

* This patch completes support for verifying every declaration found in a
header is discovered in the dylib. Diagnostics are reported for each
class for differences that is representable in TBD files.

* This patch also now captures unavailable attributes that depend on target 
triples. This is needed for proper tbd file generation.
---
 clang/include/clang/AST/Availability.h|  13 +-
 .../clang/Basic/DiagnosticInstallAPIKinds.td  |  23 +
 .../include/clang/InstallAPI/DylibVerifier.h  |  57 +-
 clang/include/clang/InstallAPI/Frontend.h |   3 +
 clang/include/clang/InstallAPI/MachO.h|   1 +
 clang/lib/AST/Availability.cpp|   6 +-
 clang/lib/InstallAPI/DylibVerifier.cpp| 326 -
 clang/lib/InstallAPI/Visitor.cpp  |   2 +-
 clang/test/InstallAPI/availability.test   | 626 ++
 clang/test/InstallAPI/diagnostics-cpp.test| 461 +
 clang/test/InstallAPI/hiddens.test| 262 
 .../clang-installapi/ClangInstallAPI.cpp  |   6 +-
 clang/tools/clang-installapi/Options.cpp  |   4 +-
 13 files changed, 1766 insertions(+), 24 deletions(-)
 create mode 100644 clang/test/InstallAPI/availability.test
 create mode 100644 clang/test/InstallAPI/diagnostics-cpp.test
 create mode 100644 clang/test/InstallAPI/hiddens.test

diff --git a/clang/include/clang/AST/Availability.h 
b/clang/include/clang/AST/Availability.h
index 5cfbaf0cdfbd21..2ccc607d4b63dc 100644
--- a/clang/include/clang/AST/Availability.h
+++ b/clang/include/clang/AST/Availability.h
@@ -67,6 +67,7 @@ struct AvailabilityInfo {
   VersionTuple Introduced;
   VersionTuple Deprecated;
   VersionTuple Obsoleted;
+  bool Unavailable = false;
   bool UnconditionallyDeprecated = false;
   bool UnconditionallyUnavailable = false;
 
@@ -78,6 +79,9 @@ struct AvailabilityInfo {
   /// Check if the symbol has been obsoleted.
   bool isObsoleted() const { return !Obsoleted.empty(); }
 
+  /// Check if the symbol is unavailable for the active platform and os 
version.
+  bool isUnavailable() const { return Unavailable; }
+
   /// Check if the symbol is unconditionally deprecated.
   ///
   /// i.e. \code __attribute__((deprecated)) \endcode
@@ -91,9 +95,10 @@ struct AvailabilityInfo {
   }
 
   AvailabilityInfo(StringRef Domain, VersionTuple I, VersionTuple D,
-   VersionTuple O, bool UD, bool UU)
+   VersionTuple O, bool U, bool UD, bool UU)
   : Domain(Domain), Introduced(I), Deprecated(D), Obsoleted(O),
-UnconditionallyDeprecated(UD), UnconditionallyUnavailable(UU) {}
+Unavailable(U), UnconditionallyDeprecated(UD),
+UnconditionallyUnavailable(UU) {}
 
   friend bool operator==(const AvailabilityInfo &Lhs,
  const AvailabilityInfo &Rhs);
@@ -105,10 +110,10 @@ struct AvailabilityInfo {
 inline bool operator==(const AvailabilityInfo &Lhs,
const AvailabilityInfo &Rhs) {
   return std::tie(Lhs.Introduced, Lhs.Deprecated, Lhs.Obsoleted,
-  Lhs.UnconditionallyDeprecated,
+  Lhs.Unavailable, Lhs.UnconditionallyDeprecated,
   Lhs.UnconditionallyUnavailable) ==
  std::tie(Rhs.Introduced, Rhs.Deprecated, Rhs.Obsoleted,
-  Rhs.UnconditionallyDeprecated,
+  Rhs.Unavailable, Rhs.UnconditionallyDeprecated,
   Rhs.UnconditionallyUnavailable);
 }
 
diff --git a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td 
b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
index 31be4f09cf3a1c..5ed2e23425dc5f 100644
--- a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
+++ b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
@@ -17,4 +17,27 @@ def err_no_install_name : Error<"no install name specified: 
add -install_name ;
 } // end of command line category.
 
+let CategoryName = "Verification" in {
+def warn_target: Warning<"violations found for %0">;
+def err_library_missing_symbol : Error<"declaration has external linkage, but 
dynamic library doesn't have symbol '%0'">;
+def warn_library_missing_symbol : Warning<"declaration has external linkage, 
but dynamic library doesn't have symbol '%0'">;
+def err_library_hidden_symbol : Error<"declaration has external linkage, but 
symbol has internal linkage in dynamic library '%0'">;
+def warn_library_hidden_symbol : Warning<"declaration has external linkage, 
but symbol has internal linkage in dynamic library '%0'">;
+def warn_header_hidden_symbol : Warning<"symbol exported in dynamic library, 
but marked hidden in declaration '%0'">;
+def err_header_hidden_symbol : Error<"symbol exported in dynami

[clang] [llvm] [DebugInfo] Use DW_op_bit_piece for structured bindings of bitfields (PR #85665)

2024-03-19 Thread Adrian Prantl via cfe-commits


@@ -8,8 +8,8 @@ struct S0 {
 // CHECK-LABEL: define dso_local void @_Z3fS0v
 // CHECK:alloca %struct.S0, align 4
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S0, align 4
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression())
-// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 2))
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression(DW_OP_bit_piece, 16, 0))

adrian-prantl wrote:

The SROA support doesn't need to hold up this patch of course, I'm just 
mentioning it.

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


[clang] [llvm] [DebugInfo] Use DW_op_bit_piece for structured bindings of bitfields (PR #85665)

2024-03-19 Thread Adrian Prantl via cfe-commits


@@ -8,8 +8,8 @@ struct S0 {
 // CHECK-LABEL: define dso_local void @_Z3fS0v
 // CHECK:alloca %struct.S0, align 4
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S0, align 4
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression())
-// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 2))
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression(DW_OP_bit_piece, 16, 0))

adrian-prantl wrote:

Regardless of which variant we choose, we probably need to add explicit support 
for it to SROA.cpp to make sure it gets translated correctly when the alloca 
gets split up again.

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


[clang] [llvm] [DebugInfo] Use DW_op_bit_piece for structured bindings of bitfields (PR #85665)

2024-03-19 Thread Adrian Prantl via cfe-commits


@@ -8,8 +8,8 @@ struct S0 {
 // CHECK-LABEL: define dso_local void @_Z3fS0v
 // CHECK:alloca %struct.S0, align 4
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S0, align 4
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression())
-// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 2))
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression(DW_OP_bit_piece, 16, 0))

adrian-prantl wrote:

https://dwarfstd.org/issues/191025.1.html
https://dwarfstd.org/issues/161206.2.html

I think you are right about the semantics of `DW_OP_bit_piece`.
I also think I misunderstood the problem the first time around.

Here a and b are not fragments of a large struct, but we want to express the 
opposite. They point into the same alloca. Here's incorrect ToT output:


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


[clang] [llvm] [DebugInfo] Use DW_op_bit_piece for structured bindings of bitfields (PR #85665)

2024-03-19 Thread Adrian Prantl via cfe-commits


@@ -8,8 +8,8 @@ struct S0 {
 // CHECK-LABEL: define dso_local void @_Z3fS0v
 // CHECK:alloca %struct.S0, align 4
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S0, align 4
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression())
-// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 2))
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression(DW_OP_bit_piece, 16, 0))

adrian-prantl wrote:

So we could add DW_OP_bit_piece to LLVM, or we could emit
```
!DIExpression()
!DIExpression(DW_OP_shr 8)
```
Which, I believe, would be supported by LLVM today without any modifications?

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


[clang] [llvm] [DebugInfo] Use DW_op_bit_piece for structured bindings of bitfields (PR #85665)

2024-03-19 Thread Adrian Prantl via cfe-commits


@@ -8,8 +8,8 @@ struct S0 {
 // CHECK-LABEL: define dso_local void @_Z3fS0v
 // CHECK:alloca %struct.S0, align 4
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S0, align 4
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression())
-// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_B:![0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 2))
+// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S0_A:![0-9]+]], metadata !DIExpression(DW_OP_bit_piece, 16, 0))

adrian-prantl wrote:

```
  %0 = alloca %struct.anon, align 4
  store i32 0, ptr %retval, align 4
  tail call void @llvm.dbg.declare(metadata ptr %0, metadata !23, metadata 
!DIExpression()), !dbg !25
  tail call void @llvm.dbg.declare(metadata ptr %0, metadata !26, metadata 
!DIExpression(DW_OP_plus_uconst, 1)), !dbg !27

...
!23 = !DILocalVariable(name: "a", scope: !18, file: !5, line: 2, type: !24)
!26 = !DILocalVariable(name: "b", scope: !18, file: !5, line: 2, type: !24)
```

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


[clang] [InstallAPI] Verify that declarations in headers map to exports found in dylib (PR #85348)

2024-03-19 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/85348

>From d45081b0270f20a1313a35bd4ae12343e265ce7b Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Wed, 13 Mar 2024 18:57:14 -0700
Subject: [PATCH 1/3] [InstallAPI] Verify that declarations in header map to
 symbols found in dylib

* This patch completes support for verifying every declaration found in a
header is discovered in the dylib. Diagnostics are reported for each
class for differences that is representable in TBD files.

* This patch also now captures unavailable attributes that depend on target 
triples. This is needed for proper tbd file generation.
---
 clang/include/clang/AST/Availability.h|  13 +-
 .../clang/Basic/DiagnosticInstallAPIKinds.td  |  23 +
 .../include/clang/InstallAPI/DylibVerifier.h  |  57 +-
 clang/include/clang/InstallAPI/Frontend.h |   3 +
 clang/include/clang/InstallAPI/MachO.h|   1 +
 clang/lib/AST/Availability.cpp|   6 +-
 clang/lib/InstallAPI/DylibVerifier.cpp| 326 -
 clang/lib/InstallAPI/Visitor.cpp  |   2 +-
 clang/test/InstallAPI/availability.test   | 626 ++
 clang/test/InstallAPI/diagnostics-cpp.test| 461 +
 clang/test/InstallAPI/hiddens.test| 262 
 .../clang-installapi/ClangInstallAPI.cpp  |   6 +-
 clang/tools/clang-installapi/Options.cpp  |   4 +-
 13 files changed, 1766 insertions(+), 24 deletions(-)
 create mode 100644 clang/test/InstallAPI/availability.test
 create mode 100644 clang/test/InstallAPI/diagnostics-cpp.test
 create mode 100644 clang/test/InstallAPI/hiddens.test

diff --git a/clang/include/clang/AST/Availability.h 
b/clang/include/clang/AST/Availability.h
index 5cfbaf0cdfbd21..2ccc607d4b63dc 100644
--- a/clang/include/clang/AST/Availability.h
+++ b/clang/include/clang/AST/Availability.h
@@ -67,6 +67,7 @@ struct AvailabilityInfo {
   VersionTuple Introduced;
   VersionTuple Deprecated;
   VersionTuple Obsoleted;
+  bool Unavailable = false;
   bool UnconditionallyDeprecated = false;
   bool UnconditionallyUnavailable = false;
 
@@ -78,6 +79,9 @@ struct AvailabilityInfo {
   /// Check if the symbol has been obsoleted.
   bool isObsoleted() const { return !Obsoleted.empty(); }
 
+  /// Check if the symbol is unavailable for the active platform and os 
version.
+  bool isUnavailable() const { return Unavailable; }
+
   /// Check if the symbol is unconditionally deprecated.
   ///
   /// i.e. \code __attribute__((deprecated)) \endcode
@@ -91,9 +95,10 @@ struct AvailabilityInfo {
   }
 
   AvailabilityInfo(StringRef Domain, VersionTuple I, VersionTuple D,
-   VersionTuple O, bool UD, bool UU)
+   VersionTuple O, bool U, bool UD, bool UU)
   : Domain(Domain), Introduced(I), Deprecated(D), Obsoleted(O),
-UnconditionallyDeprecated(UD), UnconditionallyUnavailable(UU) {}
+Unavailable(U), UnconditionallyDeprecated(UD),
+UnconditionallyUnavailable(UU) {}
 
   friend bool operator==(const AvailabilityInfo &Lhs,
  const AvailabilityInfo &Rhs);
@@ -105,10 +110,10 @@ struct AvailabilityInfo {
 inline bool operator==(const AvailabilityInfo &Lhs,
const AvailabilityInfo &Rhs) {
   return std::tie(Lhs.Introduced, Lhs.Deprecated, Lhs.Obsoleted,
-  Lhs.UnconditionallyDeprecated,
+  Lhs.Unavailable, Lhs.UnconditionallyDeprecated,
   Lhs.UnconditionallyUnavailable) ==
  std::tie(Rhs.Introduced, Rhs.Deprecated, Rhs.Obsoleted,
-  Rhs.UnconditionallyDeprecated,
+  Rhs.Unavailable, Rhs.UnconditionallyDeprecated,
   Rhs.UnconditionallyUnavailable);
 }
 
diff --git a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td 
b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
index 31be4f09cf3a1c..5ed2e23425dc5f 100644
--- a/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
+++ b/clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
@@ -17,4 +17,27 @@ def err_no_install_name : Error<"no install name specified: 
add -install_name ;
 } // end of command line category.
 
+let CategoryName = "Verification" in {
+def warn_target: Warning<"violations found for %0">;
+def err_library_missing_symbol : Error<"declaration has external linkage, but 
dynamic library doesn't have symbol '%0'">;
+def warn_library_missing_symbol : Warning<"declaration has external linkage, 
but dynamic library doesn't have symbol '%0'">;
+def err_library_hidden_symbol : Error<"declaration has external linkage, but 
symbol has internal linkage in dynamic library '%0'">;
+def warn_library_hidden_symbol : Warning<"declaration has external linkage, 
but symbol has internal linkage in dynamic library '%0'">;
+def warn_header_hidden_symbol : Warning<"symbol exported in dynamic library, 
but marked hidden in declaration '%0'">;
+def err_header_hidden_symbol : Error<"symbol exported in dynami

[clang] [CLANG] Full support of complex multiplication and division. (PR #81514)

2024-03-19 Thread Zahira Ammarguellat via cfe-commits

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


[clang] [Clang] Coroutines: Properly Check if `await_suspend` return type convertible to `std::coroutine_handle<>` (PR #85684)

2024-03-19 Thread Yuxuan Chen via cfe-commits

https://github.com/yuxuanchen1997 updated 
https://github.com/llvm/llvm-project/pull/85684

>From 08de54f02038795924a6e5fdbcf51a496fcedf56 Mon Sep 17 00:00:00 2001
From: Yuxuan Chen 
Date: Mon, 18 Mar 2024 10:45:20 -0700
Subject: [PATCH] Check if Coroutine await_suspend type returns the right type

---
 .../clang/Basic/DiagnosticSemaKinds.td|  2 +-
 clang/include/clang/Sema/Sema.h   |  2 +
 clang/lib/Sema/SemaCoroutine.cpp  | 75 +++--
 clang/lib/Sema/SemaExprCXX.cpp| 84 +--
 clang/test/SemaCXX/coroutines.cpp | 28 +--
 5 files changed, 116 insertions(+), 75 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 8e97902564af08..f99170445c76b6 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11701,7 +11701,7 @@ def err_coroutine_promise_new_requires_nothrow : Error<
 def note_coroutine_promise_call_implicitly_required : Note<
   "call to %0 implicitly required by coroutine function here">;
 def err_await_suspend_invalid_return_type : Error<
-  "return type of 'await_suspend' is required to be 'void' or 'bool' (have %0)"
+  "return type of 'await_suspend' is required to be 'void' or 'bool' or 
convertible to 'std::coroutine_handle<>' (have %0)"
 >;
 def note_await_ready_no_bool_conversion : Note<
   "return type of 'await_ready' is required to be contextually convertible to 
'bool'"
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 95ea5ebc7f1ac1..4976ff96b03d5b 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -7011,6 +7011,8 @@ class Sema final {
   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
 ArrayRef Args,
 SourceLocation RParenLoc);
+  bool EvaluateBinaryTypeTrait(TypeTrait BTT, QualType LhsT, QualType RhsT,
+   SourceLocation KeyLoc);
 
   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
   /// pseudo-functions.
diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp
index 736632857efc36..fbe230737404fa 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -331,16 +331,12 @@ static ExprResult buildMemberCall(Sema &S, Expr *Base, 
SourceLocation Loc,
 // coroutine.
 static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
SourceLocation Loc) {
-  if (RetType->isReferenceType())
-return nullptr;
+  assert(!RetType->isReferenceType() &&
+ "Should have diagnosed reference types.");
   Type const *T = RetType.getTypePtr();
   if (!T->isClassType() && !T->isStructureType())
 return nullptr;
 
-  // FIXME: Add convertability check to coroutine_handle<>. Possibly via
-  // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
-  // a private function in SemaExprCXX.cpp
-
   ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", std::nullopt);
   if (AddressExpr.isInvalid())
 return nullptr;
@@ -358,6 +354,14 @@ static Expr *maybeTailCall(Sema &S, QualType RetType, Expr 
*E,
   return S.MaybeCreateExprWithCleanups(JustAddress);
 }
 
+static bool isConvertibleToCoroutineHandle(Sema &S, QualType Ty,
+   SourceLocation Loc) {
+  QualType ErasedHandleType =
+  lookupCoroutineHandleType(S, S.Context.VoidTy, Loc);
+  return S.EvaluateBinaryTypeTrait(BTT_IsConvertible, Ty, ErasedHandleType,
+   Loc);
+}
+
 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
 /// expression.
 /// The generated AST tries to clean up temporary objects as early as
@@ -418,39 +422,60 @@ static ReadySuspendResumeResult buildCoawaitCalls(Sema 
&S, VarDecl *CoroPromise,
 return Calls;
   }
   Expr *CoroHandle = CoroHandleRes.get();
-  CallExpr *AwaitSuspend = cast_or_null(
-  BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
+  auto *AwaitSuspend = [&]() -> CallExpr * {
+auto *SubExpr = BuildSubExpr(ACT::ACT_Suspend, "await_suspend", 
CoroHandle);
+if (!SubExpr)
+  return nullptr;
+if (auto *E = dyn_cast(SubExpr)) {
+  // This happens when await_suspend return type is not trivially
+  // destructible. This doesn't happen for the permitted return types of
+  // such function. Diagnose it later.
+  return cast_or_null(E->getSubExpr());
+} else {
+  return cast_or_null(SubExpr);
+}
+  }();
+
   if (!AwaitSuspend)
 return Calls;
+
   if (!AwaitSuspend->getType()->isDependentType()) {
+auto InvalidAwaitSuspendReturnType = [&](QualType RetType) {
+  // non-class prvalues always have cv-unqualified types
+  S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
+ diag::err_await_suspend_invalid_

[clang] [AArch64][PAC][clang][ELF] Support PAuth ABI compatibility tag (PR #85235)

2024-03-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Daniil Kovalev (kovdan01)


Changes

Depends on #85231

Emit PAuth ABI compatibility tag values as llvm module flags:
- `aarch64-elf-pauthabi-platform`
- `aarch64-elf-pauthabi-version`

For platform 0x1002 (llvm_linux), the version value bits correspond to the 
following LangOptions defined in #85232:

- bit 0: `PointerAuthIntrinsics`;
- bit 1: `PointerAuthCalls`;
- bit 2: `PointerAuthReturns`;
- bit 3: `PointerAuthAuthTraps`;
- bit 4: `PointerAuthVTPtrAddressDiscrimination`;
- bit 5: `PointerAuthVTPtrTypeDiscrimination`;
- bit 6: `PointerAuthInitFini`.

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


9 Files Affected:

- (modified) clang/include/clang/Basic/Features.def (+6) 
- (modified) clang/include/clang/Basic/LangOptions.def (+6) 
- (modified) clang/include/clang/Driver/Options.td (+18) 
- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+31) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+27) 
- (modified) clang/lib/Frontend/CompilerInvocation.cpp (+20) 
- (added) clang/test/CodeGen/aarch64-elf-pauthabi.c (+61) 
- (added) clang/test/Driver/ptrauth.c (+32) 
- (modified) clang/test/Preprocessor/ptrauth_feature.c (+105-2) 


``diff
diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index eeed5f4751f2f4..1c6236aa4f9748 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -102,6 +102,12 @@ FEATURE(thread_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::Thread))
 FEATURE(dataflow_sanitizer, LangOpts.Sanitize.has(SanitizerKind::DataFlow))
 FEATURE(scudo, LangOpts.Sanitize.hasOneOf(SanitizerKind::Scudo))
 FEATURE(ptrauth_intrinsics, LangOpts.PointerAuthIntrinsics)
+FEATURE(ptrauth_calls, LangOpts.PointerAuthCalls)
+FEATURE(ptrauth_returns, LangOpts.PointerAuthReturns)
+FEATURE(ptrauth_vtable_pointer_address_discrimination, 
LangOpts.PointerAuthVTPtrAddressDiscrimination)
+FEATURE(ptrauth_vtable_pointer_type_discrimination, 
LangOpts.PointerAuthVTPtrTypeDiscrimination)
+FEATURE(ptrauth_member_function_pointer_type_discrimination, 
LangOpts.PointerAuthCalls)
+FEATURE(ptrauth_init_fini, LangOpts.PointerAuthInitFini)
 FEATURE(swiftasynccc,
   PP.getTargetInfo().checkCallingConvention(CC_SwiftAsync) ==
   clang::TargetInfo::CCCR_OK)
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 8ef6700ecdc78e..4b99e70298462f 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -162,6 +162,12 @@ LANGOPT(RelaxedTemplateTemplateArgs, 1, 0, "C++17 relaxed 
matching of template t
 LANGOPT(ExperimentalLibrary, 1, 0, "enable unstable and experimental library 
features")
 
 LANGOPT(PointerAuthIntrinsics, 1, 0, "pointer authentication intrinsics")
+LANGOPT(PointerAuthCalls  , 1, 0, "function pointer authentication")
+LANGOPT(PointerAuthReturns, 1, 0, "return pointer authentication")
+LANGOPT(PointerAuthAuthTraps, 1, 0, "pointer authentication failure traps")
+LANGOPT(PointerAuthVTPtrAddressDiscrimination, 1, 0, "incorporate address 
discrimination in authenticated vtable pointers")
+LANGOPT(PointerAuthVTPtrTypeDiscrimination, 1, 0, "incorporate type 
discrimination in authenticated vtable pointers")
+LANGOPT(PointerAuthInitFini, 1, 0, "sign function pointers in init/fini 
arrays")
 
 LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for 
all language standard modes")
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 29c226f4bd8da7..e624eed2a15316 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4110,8 +4110,26 @@ let Group = f_Group in {
   let Visibility = [ClangOption,CC1Option] in {
 def fptrauth_intrinsics : Flag<["-"], "fptrauth-intrinsics">,
   HelpText<"Enable pointer authentication intrinsics">;
+def fptrauth_calls : Flag<["-"], "fptrauth-calls">,
+  HelpText<"Enable signing and authentication of all indirect calls">;
+def fptrauth_returns : Flag<["-"], "fptrauth-returns">,
+  HelpText<"Enable signing and authentication of return addresses">;
+def fptrauth_auth_traps : Flag<["-"], "fptrauth-auth-traps">,
+  HelpText<"Enable traps on authentication failures">;
+def fptrauth_vtable_pointer_address_discrimination : Flag<["-"], 
"fptrauth-vtable-pointer-address-discrimination">,
+  HelpText<"Enable address discrimination of vtable pointers">;
+def fptrauth_vtable_pointer_type_discrimination : Flag<["-"], 
"fptrauth-vtable-pointer-type-discrimination">,
+  HelpText<"Enable type discrimination of vtable pointers">;
+def fptrauth_init_fini : Flag<["-"], "fptrauth-init-fini">,
+  HelpText<"Enable signing of function pointers in init/fini arrays">;
   }
   def fno_ptrauth_intrinsics : Flag<["-"], "fno-ptrauth-intrinsics">;
+  def fno_ptrauth_calls : Flag<["-"], 

[clang] [AArch64][PAC][clang][ELF] Support PAuth ABI compatibility tag (PR #85235)

2024-03-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Daniil Kovalev (kovdan01)


Changes

Depends on #85231

Emit PAuth ABI compatibility tag values as llvm module flags:
- `aarch64-elf-pauthabi-platform`
- `aarch64-elf-pauthabi-version`

For platform 0x1002 (llvm_linux), the version value bits correspond to the 
following LangOptions defined in #85232:

- bit 0: `PointerAuthIntrinsics`;
- bit 1: `PointerAuthCalls`;
- bit 2: `PointerAuthReturns`;
- bit 3: `PointerAuthAuthTraps`;
- bit 4: `PointerAuthVTPtrAddressDiscrimination`;
- bit 5: `PointerAuthVTPtrTypeDiscrimination`;
- bit 6: `PointerAuthInitFini`.

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


9 Files Affected:

- (modified) clang/include/clang/Basic/Features.def (+6) 
- (modified) clang/include/clang/Basic/LangOptions.def (+6) 
- (modified) clang/include/clang/Driver/Options.td (+18) 
- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+31) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+27) 
- (modified) clang/lib/Frontend/CompilerInvocation.cpp (+20) 
- (added) clang/test/CodeGen/aarch64-elf-pauthabi.c (+61) 
- (added) clang/test/Driver/ptrauth.c (+32) 
- (modified) clang/test/Preprocessor/ptrauth_feature.c (+105-2) 


``diff
diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index eeed5f4751f2f4..1c6236aa4f9748 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -102,6 +102,12 @@ FEATURE(thread_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::Thread))
 FEATURE(dataflow_sanitizer, LangOpts.Sanitize.has(SanitizerKind::DataFlow))
 FEATURE(scudo, LangOpts.Sanitize.hasOneOf(SanitizerKind::Scudo))
 FEATURE(ptrauth_intrinsics, LangOpts.PointerAuthIntrinsics)
+FEATURE(ptrauth_calls, LangOpts.PointerAuthCalls)
+FEATURE(ptrauth_returns, LangOpts.PointerAuthReturns)
+FEATURE(ptrauth_vtable_pointer_address_discrimination, 
LangOpts.PointerAuthVTPtrAddressDiscrimination)
+FEATURE(ptrauth_vtable_pointer_type_discrimination, 
LangOpts.PointerAuthVTPtrTypeDiscrimination)
+FEATURE(ptrauth_member_function_pointer_type_discrimination, 
LangOpts.PointerAuthCalls)
+FEATURE(ptrauth_init_fini, LangOpts.PointerAuthInitFini)
 FEATURE(swiftasynccc,
   PP.getTargetInfo().checkCallingConvention(CC_SwiftAsync) ==
   clang::TargetInfo::CCCR_OK)
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 8ef6700ecdc78e..4b99e70298462f 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -162,6 +162,12 @@ LANGOPT(RelaxedTemplateTemplateArgs, 1, 0, "C++17 relaxed 
matching of template t
 LANGOPT(ExperimentalLibrary, 1, 0, "enable unstable and experimental library 
features")
 
 LANGOPT(PointerAuthIntrinsics, 1, 0, "pointer authentication intrinsics")
+LANGOPT(PointerAuthCalls  , 1, 0, "function pointer authentication")
+LANGOPT(PointerAuthReturns, 1, 0, "return pointer authentication")
+LANGOPT(PointerAuthAuthTraps, 1, 0, "pointer authentication failure traps")
+LANGOPT(PointerAuthVTPtrAddressDiscrimination, 1, 0, "incorporate address 
discrimination in authenticated vtable pointers")
+LANGOPT(PointerAuthVTPtrTypeDiscrimination, 1, 0, "incorporate type 
discrimination in authenticated vtable pointers")
+LANGOPT(PointerAuthInitFini, 1, 0, "sign function pointers in init/fini 
arrays")
 
 LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for 
all language standard modes")
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 29c226f4bd8da7..e624eed2a15316 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4110,8 +4110,26 @@ let Group = f_Group in {
   let Visibility = [ClangOption,CC1Option] in {
 def fptrauth_intrinsics : Flag<["-"], "fptrauth-intrinsics">,
   HelpText<"Enable pointer authentication intrinsics">;
+def fptrauth_calls : Flag<["-"], "fptrauth-calls">,
+  HelpText<"Enable signing and authentication of all indirect calls">;
+def fptrauth_returns : Flag<["-"], "fptrauth-returns">,
+  HelpText<"Enable signing and authentication of return addresses">;
+def fptrauth_auth_traps : Flag<["-"], "fptrauth-auth-traps">,
+  HelpText<"Enable traps on authentication failures">;
+def fptrauth_vtable_pointer_address_discrimination : Flag<["-"], 
"fptrauth-vtable-pointer-address-discrimination">,
+  HelpText<"Enable address discrimination of vtable pointers">;
+def fptrauth_vtable_pointer_type_discrimination : Flag<["-"], 
"fptrauth-vtable-pointer-type-discrimination">,
+  HelpText<"Enable type discrimination of vtable pointers">;
+def fptrauth_init_fini : Flag<["-"], "fptrauth-init-fini">,
+  HelpText<"Enable signing of function pointers in init/fini arrays">;
   }
   def fno_ptrauth_intrinsics : Flag<["-"], "fno-ptrauth-intrinsics">;
+  def fno_ptrauth_calls : Flag<["-"], "

  1   2   3   4   5   >