[llvm] [clang] [RISCV] Add Zicfiss support to the shadow call stack implementation. (PR #68075)

2024-01-07 Thread Yeting Kuo via cfe-commits


@@ -151,9 +155,10 @@ Usage
 
 To enable ShadowCallStack, just pass the ``-fsanitize=shadow-call-stack`` flag
 to both compile and link command lines. On aarch64, you also need to pass
-``-ffixed-x18`` unless your target already reserves ``x18``. On RISC-V, ``x3``
-(``gp``) is always reserved. It is, however, important to disable GP relaxation
-in the linker. This can be done with the ``--no-relax-gp`` flag in GNU ld.
+``-ffixed-x18`` unless your target already reserves ``x18``. On RISC-V with 
software
+shadow stack, ``x3`` (``gp``) is always reserved. It is, however, important to
+disable GP relaxation in the linker. This can be done with the 
``--no-relax-gp``
+flag in GNU ld.

yetingk wrote:

Done. Thank you for your suggestion.

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


[llvm] [clang] [RISCV] Add Zicfiss support to the shadow call stack implementation. (PR #68075)

2024-01-07 Thread Yeting Kuo via cfe-commits


@@ -57,11 +57,14 @@ compiled application or the operating system. Integrating 
the runtime into
 the operating system should be preferred since otherwise all thread creation
 and destruction would need to be intercepted by the application.
 
-The instrumentation makes use of the platform register ``x18`` on AArch64 and
-``x3`` (``gp``) on RISC-V. For simplicity we will refer to this as the
-``SCSReg``. On some platforms, ``SCSReg`` is reserved, and on others, it is
-designated as a scratch register.  This generally means that any code that may
-run on the same thread as code compiled with ShadowCallStack must either target
+The instrumentation makes use of the platform register ``x18`` on AArch64,
+``x3`` (``gp``) on RISC-V with software shadow stack and ``ssp`` on RISC-V with
+hardware shadow stack, which needs `Zicfiss`_ and 
``-mno-forced-sw-shadow-stack``
+(default option). ``-mforced-sw-shadow-stack`` make risc-v backend generate
+software shadow stack with `Zicfiss`_ when shadow stack enabled.

yetingk wrote:

Done. Thank you for your suggestion.

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


[clang] [Serialization] Load Specializations Lazily (1/2) (PR #76774)

2024-01-07 Thread Chuanqi Xu via cfe-commits


@@ -1249,3 +1249,5 @@ void ODRHash::AddQualType(QualType T) {
 void ODRHash::AddBoolean(bool Value) {
   Bools.push_back(Value);
 }
+
+void ODRHash::AddInteger(unsigned Value) { ID.AddInteger(Value); }

ChuanqiXu9 wrote:

I had this 
https://github.com/llvm/llvm-project/commit/9b808a4beb8e6c8255b412fdd6f5a3e20cbcf270#diff-e88c8434346144fdf335c14c17a112759af7a4e81957efcaca635a08b9f13a29R110-R116.

Do you mean I need to put that into a namespace?

I tried to create alias arguments for template template arguments. But the 
tests can't pass before the current patch.

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


[clang] [clang][Interp] Implement integral->complex casts (PR #75590)

2024-01-07 Thread Timm Baeder via cfe-commits

tbaederr wrote:

Ping

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


[clang] [Serialization] Load Specializations Lazily (1/2) (PR #76774)

2024-01-07 Thread Jonas Hahnfeld via cfe-commits


@@ -1249,3 +1249,5 @@ void ODRHash::AddQualType(QualType T) {
 void ODRHash::AddBoolean(bool Value) {
   Bools.push_back(Value);
 }
+
+void ODRHash::AddInteger(unsigned Value) { ID.AddInteger(Value); }

hahnjo wrote:

That test does not exercise an alias argument to a template template argument. 
IIRC the code you code is only active for typenames. Also see the test in 
https://reviews.llvm.org/D153003 that exercises different spellings of the 
semantically equivalent type `NS::A` inside a namespace.

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


[clang] Fix crash with modules and constexpr destructor (PR #69076)

2024-01-07 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> Well, this patch is up since almost three months now (!). Sure, we can keep 
> carrying a similar fix downstream, but ideally I would really like to get rid 
> of as many local changes as possible. That's not possible without proper 
> review, but the current situation is quite unsatisfactory...

Yeah, fully understood. I have a lot of similar experiences... 1~2 weeks is not 
long in comparing with 3 months.

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


[clang] [clang][Interp] IndirectMember initializers (PR #69900)

2024-01-07 Thread Timm Baeder via cfe-commits

tbaederr wrote:

Ping

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


[clang] c15e583 - [clang][Interp] Fix nullptr array dereferencing (#75798)

2024-01-07 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-01-08T08:33:15+01:00
New Revision: c15e5836d49763e43736d13eb4b873e01dcc9ef0

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

LOG: [clang][Interp] Fix nullptr array dereferencing (#75798)

The attached test case would cause an assertion failure in Pointer.h
when operating on a null pointer.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h
clang/test/AST/Interp/arrays.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index a82d1c3c7c622a..21ea2503b94bff 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -290,10 +290,10 @@ bool CheckInitialized(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 }
 
 bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
-  if (!CheckDummy(S, OpPC, Ptr))
-return false;
   if (!CheckLive(S, OpPC, Ptr, AK_Read))
 return false;
+  if (!CheckDummy(S, OpPC, Ptr))
+return false;
   if (!CheckExtern(S, OpPC, Ptr))
 return false;
   if (!CheckRange(S, OpPC, Ptr, AK_Read))

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 828d4ea35526d6..c05dea0cc55d3c 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1813,9 +1813,6 @@ inline bool ArrayElemPtr(InterpState &S, CodePtr OpPC) {
   const T &Offset = S.Stk.pop();
   const Pointer &Ptr = S.Stk.peek();
 
-  if (!CheckArray(S, OpPC, Ptr))
-return false;
-
   if (!OffsetHelper(S, OpPC, Offset, Ptr))
 return false;
 
@@ -1843,9 +1840,6 @@ inline bool ArrayElemPtrPop(InterpState &S, CodePtr OpPC) 
{
   const T &Offset = S.Stk.pop();
   const Pointer &Ptr = S.Stk.pop();
 
-  if (!CheckArray(S, OpPC, Ptr))
-return false;
-
   if (!OffsetHelper(S, OpPC, Offset, Ptr))
 return false;
 

diff  --git a/clang/test/AST/Interp/arrays.cpp 
b/clang/test/AST/Interp/arrays.cpp
index c455731e76699f..4aa10da55dd3ae 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -72,6 +72,14 @@ constexpr int getElementFromEnd(const int *Arr, int size, 
int index) {
 static_assert(getElementFromEnd(data, 5, 0) == 1, "");
 static_assert(getElementFromEnd(data, 5, 4) == 5, "");
 
+constexpr int getFirstElem(const int *a) {
+  return a[0]; // expected-note {{read of dereferenced null pointer}} \
+   // ref-note {{read of dereferenced null pointer}}
+}
+static_assert(getFirstElem(nullptr) == 1, ""); // expected-error {{not an 
integral constant expression}} \
+   // expected-note {{in call to}} 
\
+   // ref-error {{not an integral 
constant expression}} \
+   // ref-note {{in call to}}
 
 constexpr static int arr[2] = {1,2};
 constexpr static int arr2[2] = {3,4};



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


[clang] [clang][Interp] Fix nullptr array dereferencing (PR #75798)

2024-01-07 Thread Timm Baeder via cfe-commits

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


[clang] Fix crash with modules and constexpr destructor (PR #69076)

2024-01-07 Thread Jonas Hahnfeld via cfe-commits

hahnjo wrote:

Well, this patch is up since almost three months now (!). Sure, we can keep 
carrying a similar fix downstream, but ideally I would really like to get rid 
of as many local changes as possible. That's not possible without proper 
review, but the current situation is quite unsatisfactory...

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


[clang] Fix crash with modules and constexpr destructor (PR #69076)

2024-01-07 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> Ping, is this ok to be accepted and landed?

If it is not hurry, I prefer to wait @cor3ntin to have a look. But given the 
scale of the patch, it should be good too to land it in 2 weeks if there is no 
other comments.

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


[clang] Fix crash with modules and constexpr destructor (PR #69076)

2024-01-07 Thread Chuanqi Xu via cfe-commits


@@ -15754,10 +15754,18 @@ bool Expr::EvaluateAsInitializer(APValue &Value, 
const ASTContext &Ctx,
 LValue LVal;
 LVal.set(VD);
 
-if (!EvaluateInPlace(Value, Info, LVal, this,
- /*AllowNonLiteralTypes=*/true) ||
-EStatus.HasSideEffects)
-  return false;
+{
+  // C++23 [intro.execution]/p5
+  // A full-expression is ... an init-declarator ([dcl.decl]) or a
+  // mem-initializer.
+  // So we need to make sure temporary objects are destroyed after having
+  // evaluated the expression (per C++23 [class.temporary]/p4).

ChuanqiXu9 wrote:

```suggestion
  // evaluated the expression (per C++23 [class.temporary]/p4).
  //
  // FIXME: Otherwise this may break test/Modules/pr68702.cpp. because the 
serialization code 
  // calls ParmVarDecl::getDefaultArg() which strips the outermost 
FullExpr, such as ExprWithCleanups. 
```

I mean the reason why this is related to modules. I feel the analysis is 
valuable.

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


[clang] [Sema] Add -Wc++11-narrowing-const-reference (PR #76094)

2024-01-07 Thread Fangrui Song via cfe-commits


@@ -10410,40 +10410,53 @@ static void DiagnoseNarrowingInInitList(Sema &S,
 // No narrowing occurred.
 return;
 
-  case NK_Type_Narrowing:
+  case NK_Type_Narrowing: {
 // This was a floating-to-integer conversion, which is always considered a
 // narrowing conversion even if the value is a constant and can be
 // represented exactly as an integer.
-S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
-? diag::ext_init_list_type_narrowing
-: diag::warn_init_list_type_narrowing)
+QualType T = EntityType.getNonReferenceType();
+S.Diag(PostInit->getBeginLoc(),
+   NarrowingErrs(S.getLangOpts())

MaskRay wrote:

I created https://github.com/llvm/llvm-project/pull/77278 to simplify the code.

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


[clang] [Sema] Add -Wc++11-narrowing-const-reference (PR #76094)

2024-01-07 Thread Fangrui Song via cfe-commits


@@ -6158,12 +6158,24 @@ def err_illegal_initializer_type : Error<"illegal 
initializer type %0">;
 def ext_init_list_type_narrowing : ExtWarn<
   "type %0 cannot be narrowed to %1 in initializer list">,
   InGroup, DefaultError, SFINAEFailure;
+// *_narrowing_const_reference diagnostics have the same messages, but are
+// controlled by -Wc++11-narrowing-const-reference for narrowing involving a
+// const reference.

MaskRay wrote:

I created #77278 to simplify the code.

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


[clang] [Sema] Clean up -Wc++11-narrowing-const-reference code after #76094. NFC (PR #77278)

2024-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Fangrui Song (MaskRay)


Changes



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


2 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3-7) 
- (modified) clang/lib/Sema/SemaInit.cpp (+24-28) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d150e08d5f5ea8..a97182cad5d513 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6160,23 +6160,19 @@ def err_illegal_initializer_type : Error<"illegal 
initializer type %0">;
 def ext_init_list_type_narrowing : ExtWarn<
   "type %0 cannot be narrowed to %1 in initializer list">,
   InGroup, DefaultError, SFINAEFailure;
-// *_narrowing_const_reference diagnostics have the same messages, but are
-// controlled by -Wc++11-narrowing-const-reference for narrowing involving a
-// const reference.
 def ext_init_list_type_narrowing_const_reference : ExtWarn<
-  "type %0 cannot be narrowed to %1 in initializer list">,
+  ext_init_list_type_narrowing.Summary>,
   InGroup, DefaultError, SFINAEFailure;
 def ext_init_list_variable_narrowing : ExtWarn<
   "non-constant-expression cannot be narrowed from type %0 to %1 in "
   "initializer list">, InGroup, DefaultError, SFINAEFailure;
 def ext_init_list_variable_narrowing_const_reference : ExtWarn<
-  "non-constant-expression cannot be narrowed from type %0 to %1 in "
-  "initializer list">, InGroup, DefaultError, 
SFINAEFailure;
+  ext_init_list_variable_narrowing.Summary>, 
InGroup, DefaultError, SFINAEFailure;
 def ext_init_list_constant_narrowing : ExtWarn<
   "constant expression evaluates to %0 which cannot be narrowed to type %1">,
   InGroup, DefaultError, SFINAEFailure;
 def ext_init_list_constant_narrowing_const_reference : ExtWarn<
-  "constant expression evaluates to %0 which cannot be narrowed to type %1">,
+  ext_init_list_constant_narrowing.Summary>,
   InGroup, DefaultError, SFINAEFailure;
 def warn_init_list_type_narrowing : Warning<
   "type %0 cannot be narrowed to %1 in initializer list in C++11">,
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index e469e420f14f03..408ee5f775804b 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10377,11 +10377,6 @@ void InitializationSequence::dump() const {
   dump(llvm::errs());
 }
 
-static bool NarrowingErrs(const LangOptions &L) {
-  return L.CPlusPlus11 &&
- (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
-}
-
 static void DiagnoseNarrowingInInitList(Sema &S,
 const ImplicitConversionSequence &ICS,
 QualType PreNarrowingType,
@@ -10402,6 +10397,19 @@ static void DiagnoseNarrowingInInitList(Sema &S,
 return;
   }
 
+  auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
+  unsigned ConstRefDiagID, unsigned WarnDiagID) {
+unsigned DiagID;
+auto &L = S.getLangOpts();
+if (L.CPlusPlus11 &&
+(!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
+  DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
+else
+  DiagID = WarnDiagID;
+return S.Diag(PostInit->getBeginLoc(), DiagID)
+   << PostInit->getSourceRange();
+  };
+
   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
   APValue ConstantValue;
   QualType ConstantType;
@@ -10417,13 +10425,9 @@ static void DiagnoseNarrowingInInitList(Sema &S,
 // narrowing conversion even if the value is a constant and can be
 // represented exactly as an integer.
 QualType T = EntityType.getNonReferenceType();
-S.Diag(PostInit->getBeginLoc(),
-   NarrowingErrs(S.getLangOpts())
-   ? (T == EntityType
-  ? diag::ext_init_list_type_narrowing
-  : diag::ext_init_list_type_narrowing_const_reference)
-   : diag::warn_init_list_type_narrowing)
-<< PostInit->getSourceRange()
+MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
+ diag::ext_init_list_type_narrowing_const_reference,
+ diag::warn_init_list_type_narrowing)
 << PreNarrowingType.getLocalUnqualifiedType()
 << T.getLocalUnqualifiedType();
 break;
@@ -10431,14 +10435,10 @@ static void DiagnoseNarrowingInInitList(Sema &S,
 
   case NK_Constant_Narrowing: {
 // A constant value was narrowed.
-QualType T = EntityType.getNonReferenceType();
-S.Diag(PostInit->getBeginLoc(),
-   NarrowingErrs(S.getLangOpts())
-   ? (T == EntityType
-  ? diag::ext_init_list_constant_narrowing
-  : diag::ext_init_list_constant_narrowing_const_reference)
-   : diag::warn_init_list_constant_narrowing)
-<< PostInit->getSourceRange()
+MakeDiag(

[clang] [Sema] Clean up -Wc++11-narrowing-const-reference code after #76094. NFC (PR #77278)

2024-01-07 Thread Fangrui Song via cfe-commits

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

None

>From 70441f463f7dbb73b1185db46ef20a86289eb246 Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Sun, 7 Jan 2024 23:24:02 -0800
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 .../clang/Basic/DiagnosticSemaKinds.td| 10 ++--
 clang/lib/Sema/SemaInit.cpp   | 52 +--
 2 files changed, 27 insertions(+), 35 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d150e08d5f5ea8..a97182cad5d513 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6160,23 +6160,19 @@ def err_illegal_initializer_type : Error<"illegal 
initializer type %0">;
 def ext_init_list_type_narrowing : ExtWarn<
   "type %0 cannot be narrowed to %1 in initializer list">,
   InGroup, DefaultError, SFINAEFailure;
-// *_narrowing_const_reference diagnostics have the same messages, but are
-// controlled by -Wc++11-narrowing-const-reference for narrowing involving a
-// const reference.
 def ext_init_list_type_narrowing_const_reference : ExtWarn<
-  "type %0 cannot be narrowed to %1 in initializer list">,
+  ext_init_list_type_narrowing.Summary>,
   InGroup, DefaultError, SFINAEFailure;
 def ext_init_list_variable_narrowing : ExtWarn<
   "non-constant-expression cannot be narrowed from type %0 to %1 in "
   "initializer list">, InGroup, DefaultError, SFINAEFailure;
 def ext_init_list_variable_narrowing_const_reference : ExtWarn<
-  "non-constant-expression cannot be narrowed from type %0 to %1 in "
-  "initializer list">, InGroup, DefaultError, 
SFINAEFailure;
+  ext_init_list_variable_narrowing.Summary>, 
InGroup, DefaultError, SFINAEFailure;
 def ext_init_list_constant_narrowing : ExtWarn<
   "constant expression evaluates to %0 which cannot be narrowed to type %1">,
   InGroup, DefaultError, SFINAEFailure;
 def ext_init_list_constant_narrowing_const_reference : ExtWarn<
-  "constant expression evaluates to %0 which cannot be narrowed to type %1">,
+  ext_init_list_constant_narrowing.Summary>,
   InGroup, DefaultError, SFINAEFailure;
 def warn_init_list_type_narrowing : Warning<
   "type %0 cannot be narrowed to %1 in initializer list in C++11">,
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index e469e420f14f03..408ee5f775804b 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10377,11 +10377,6 @@ void InitializationSequence::dump() const {
   dump(llvm::errs());
 }
 
-static bool NarrowingErrs(const LangOptions &L) {
-  return L.CPlusPlus11 &&
- (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
-}
-
 static void DiagnoseNarrowingInInitList(Sema &S,
 const ImplicitConversionSequence &ICS,
 QualType PreNarrowingType,
@@ -10402,6 +10397,19 @@ static void DiagnoseNarrowingInInitList(Sema &S,
 return;
   }
 
+  auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
+  unsigned ConstRefDiagID, unsigned WarnDiagID) {
+unsigned DiagID;
+auto &L = S.getLangOpts();
+if (L.CPlusPlus11 &&
+(!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
+  DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
+else
+  DiagID = WarnDiagID;
+return S.Diag(PostInit->getBeginLoc(), DiagID)
+   << PostInit->getSourceRange();
+  };
+
   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
   APValue ConstantValue;
   QualType ConstantType;
@@ -10417,13 +10425,9 @@ static void DiagnoseNarrowingInInitList(Sema &S,
 // narrowing conversion even if the value is a constant and can be
 // represented exactly as an integer.
 QualType T = EntityType.getNonReferenceType();
-S.Diag(PostInit->getBeginLoc(),
-   NarrowingErrs(S.getLangOpts())
-   ? (T == EntityType
-  ? diag::ext_init_list_type_narrowing
-  : diag::ext_init_list_type_narrowing_const_reference)
-   : diag::warn_init_list_type_narrowing)
-<< PostInit->getSourceRange()
+MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
+ diag::ext_init_list_type_narrowing_const_reference,
+ diag::warn_init_list_type_narrowing)
 << PreNarrowingType.getLocalUnqualifiedType()
 << T.getLocalUnqualifiedType();
 break;
@@ -10431,14 +10435,10 @@ static void DiagnoseNarrowingInInitList(Sema &S,
 
   case NK_Constant_Narrowing: {
 // A constant value was narrowed.
-QualType T = EntityType.getNonReferenceType();
-S.Diag(PostInit->getBeginLoc(),
-   NarrowingErrs(S.ge

[clang] Fix crash with modules and constexpr destructor (PR #69076)

2024-01-07 Thread Jonas Hahnfeld via cfe-commits

hahnjo wrote:

Ping, is this ok to be accepted and landed?

> So personally I am fine with the current workaround with a `FIXME`.

You mean next to the comment I already added referring to the C++ standard? Can 
you formulate what I should put there?

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


[libunwind] [flang] [lldb] [libcxx] [clang] [libc] [compiler-rt] [llvm] [clang-tools-extra] [lld] [libc++][test] try to directly create socket file in /tmp when filepath is too long (PR #77058)

2024-01-07 Thread Wu Yingcong via cfe-commits

https://github.com/yingcong-wu updated 
https://github.com/llvm/llvm-project/pull/77058

>From 202fb858344d102bd5199cd749bb15195dbce558 Mon Sep 17 00:00:00 2001
From: "Wu, Yingcong" 
Date: Fri, 5 Jan 2024 00:48:34 -0800
Subject: [PATCH 1/7] try to directly create file in /tmp when filepath is too
 long

---
 libcxx/test/support/filesystem_test_helper.h | 15 ++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/libcxx/test/support/filesystem_test_helper.h 
b/libcxx/test/support/filesystem_test_helper.h
index a049efe03d844e..271b2bb5cafe23 100644
--- a/libcxx/test/support/filesystem_test_helper.h
+++ b/libcxx/test/support/filesystem_test_helper.h
@@ -18,6 +18,7 @@
 #include 
 #include 
 #include  // for printf
+#include 
 #include 
 #include 
 #include 
@@ -324,10 +325,22 @@ struct scoped_test_env
 
 ::sockaddr_un address;
 address.sun_family = AF_UNIX;
+
+// If file.size() is too big, try to create a file directly inside
+// /tmp to make sure file path is short enough.
+if (file.size() <= sizeof(address.sun_path) && utils::exists("/tmp")) {
+fs::path const tmp = "/tmp";
+std::size_t i  = 
std::hash()(std::to_string(std::time(nullptr)));
+fs::path p = tmp / ("libcxx-socket-" + file + "-" + 
std::to_string(i));
+while (utils::exists(p.string())) {
+  p = tmp / ("libcxx-socket-" + file + "-" + std::to_string(++i));
+}
+file = p.string();
+}
 assert(file.size() <= sizeof(address.sun_path));
 ::strncpy(address.sun_path, file.c_str(), sizeof(address.sun_path));
 int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
-::bind(fd, reinterpret_cast<::sockaddr*>(&address), sizeof(address));
+assert(::bind(fd, reinterpret_cast<::sockaddr*>(&address), 
sizeof(address)) == 0);
 return file;
 }
 #endif

>From 5d64d75bf7ad8422eb54594fa8cc8dfda7f14e4e Mon Sep 17 00:00:00 2001
From: "Wu, Yingcong" 
Date: Fri, 5 Jan 2024 01:13:24 -0800
Subject: [PATCH 2/7] format

---
 libcxx/test/support/filesystem_test_helper.h | 14 +++---
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/libcxx/test/support/filesystem_test_helper.h 
b/libcxx/test/support/filesystem_test_helper.h
index 271b2bb5cafe23..d33fcf5497f084 100644
--- a/libcxx/test/support/filesystem_test_helper.h
+++ b/libcxx/test/support/filesystem_test_helper.h
@@ -329,13 +329,13 @@ struct scoped_test_env
 // If file.size() is too big, try to create a file directly inside
 // /tmp to make sure file path is short enough.
 if (file.size() <= sizeof(address.sun_path) && utils::exists("/tmp")) {
-fs::path const tmp = "/tmp";
-std::size_t i  = 
std::hash()(std::to_string(std::time(nullptr)));
-fs::path p = tmp / ("libcxx-socket-" + file + "-" + 
std::to_string(i));
-while (utils::exists(p.string())) {
-  p = tmp / ("libcxx-socket-" + file + "-" + std::to_string(++i));
-}
-file = p.string();
+  fs::path const tmp = "/tmp";
+  std::size_t i  = 
std::hash()(std::to_string(std::time(nullptr)));
+  fs::path p = tmp / ("libcxx-socket-" + file + "-" + 
std::to_string(i));
+  while (utils::exists(p.string())) {
+p = tmp / ("libcxx-socket-" + file + "-" + std::to_string(++i));
+  }
+  file = p.string();
 }
 assert(file.size() <= sizeof(address.sun_path));
 ::strncpy(address.sun_path, file.c_str(), sizeof(address.sun_path));

>From ec6ff976d4e338fb1cd219409ee47b75b3b6a324 Mon Sep 17 00:00:00 2001
From: "Wu, Yingcong" 
Date: Fri, 5 Jan 2024 01:59:22 -0800
Subject: [PATCH 3/7] fix error

---
 libcxx/test/support/filesystem_test_helper.h | 12 ++--
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/libcxx/test/support/filesystem_test_helper.h 
b/libcxx/test/support/filesystem_test_helper.h
index d33fcf5497f084..001625d97775f8 100644
--- a/libcxx/test/support/filesystem_test_helper.h
+++ b/libcxx/test/support/filesystem_test_helper.h
@@ -321,27 +321,27 @@ struct scoped_test_env
   // allow tests to call this unguarded.
 #if !defined(__FreeBSD__) && !defined(__APPLE__) && !defined(_WIN32)
 std::string create_socket(std::string file) {
-file = sanitize_path(std::move(file));
+std::string socket_file = sanitize_path(file);
 
 ::sockaddr_un address;
 address.sun_family = AF_UNIX;
 
 // If file.size() is too big, try to create a file directly inside
 // /tmp to make sure file path is short enough.
-if (file.size() <= sizeof(address.sun_path) && utils::exists("/tmp")) {
+if (socket_file.size() <= sizeof(address.sun_path) && 
utils::exists("/tmp")) {
   fs::path const tmp = "/tmp";
   std::size_t i  = 
std::hash()(std::to_string(std::time(nullptr)));
 

[llvm] [clang-tools-extra] [clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-07 Thread Freddy Ye via cfe-commits

FreddyLeaf wrote:

ping for review.

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


[clang] [lld] [flang] [llvm] [AMDGPU] Introduce Code Object V6 (PR #76954)

2024-01-07 Thread Pierre van Houtryve via cfe-commits

https://github.com/Pierre-vh updated 
https://github.com/llvm/llvm-project/pull/76954

>From dc666323870118020c0fd386d19d8306d4c853e1 Mon Sep 17 00:00:00 2001
From: pvanhout 
Date: Thu, 4 Jan 2024 14:12:00 +0100
Subject: [PATCH 1/2] [AMDGPU] Introduce Code Object V6

Introduce Code Object V6 in Clang, LLD, Flang and LLVM.
This is the same as V5 except a new "generic version" flag can be present in 
EFLAGS. This is related to new generic targets that'll be added in a follow-up 
patch. It's also likely V6 will have new changes (possibly new metadata 
entries) added later.

Docs change are not included, I'm planning to do them in a follow-up patch all 
at once (when generic targets land too).
---
 clang/include/clang/Driver/Options.td |   4 +-
 clang/lib/CodeGen/CGBuiltin.cpp   |   6 +-
 clang/lib/Driver/ToolChains/CommonArgs.cpp|   2 +-
 .../amdgpu-code-object-version-linking.cu |  37 +++
 .../CodeGenCUDA/amdgpu-code-object-version.cu |   4 +
 .../test/CodeGenCUDA/amdgpu-workgroup-size.cu |   4 +
 .../amdgcn/bitcode/oclc_abi_version_600.bc|   0
 clang/test/Driver/hip-code-object-version.hip |  12 +
 clang/test/Driver/hip-device-libs.hip |  18 +-
 flang/lib/Frontend/CompilerInvocation.cpp |   2 +
 flang/test/Lower/AMD/code-object-version.f90  |   3 +-
 lld/ELF/Arch/AMDGPU.cpp   |  22 ++
 lld/test/ELF/amdgpu-tid.s |  16 ++
 llvm/include/llvm/BinaryFormat/ELF.h  |  12 +-
 llvm/include/llvm/Support/AMDGPUMetadata.h|   5 +
 llvm/include/llvm/Support/ScopedPrinter.h |   4 +-
 llvm/include/llvm/Target/TargetOptions.h  |   1 +
 llvm/lib/ObjectYAML/ELFYAML.cpp   |   6 +
 llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp   |   3 +
 .../AMDGPU/AMDGPUHSAMetadataStreamer.cpp  |  10 +
 .../Target/AMDGPU/AMDGPUHSAMetadataStreamer.h |  11 +-
 .../MCTargetDesc/AMDGPUTargetStreamer.cpp |  27 +++
 .../MCTargetDesc/AMDGPUTargetStreamer.h   |   1 +
 .../Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp|  13 +
 llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h |   5 +-
 ...licit-kernarg-backend-usage-global-isel.ll |   2 +
 .../AMDGPU/call-graph-register-usage.ll   |   1 +
 .../AMDGPU/codegen-internal-only-func.ll  |   2 +
 llvm/test/CodeGen/AMDGPU/elf-header-osabi.ll  |   4 +
 .../enable-scratch-only-dynamic-stack.ll  |   1 +
 .../AMDGPU/implicit-kernarg-backend-usage.ll  |   2 +
 .../AMDGPU/implicitarg-offset-attributes.ll   |  46 
 .../AMDGPU/llvm.amdgcn.implicitarg.ptr.ll |   1 +
 llvm/test/CodeGen/AMDGPU/non-entry-alloca.ll  |   1 +
 llvm/test/CodeGen/AMDGPU/recursion.ll |   1 +
 .../AMDGPU/resource-usage-dead-function.ll|   1 +
 .../AMDGPU/tid-mul-func-xnack-all-any.ll  |   6 +
 .../tid-mul-func-xnack-all-not-supported.ll   |   6 +
 .../AMDGPU/tid-mul-func-xnack-all-off.ll  |   6 +
 .../AMDGPU/tid-mul-func-xnack-all-on.ll   |   6 +
 .../AMDGPU/tid-mul-func-xnack-any-off-1.ll|   6 +
 .../AMDGPU/tid-mul-func-xnack-any-off-2.ll|   6 +
 .../AMDGPU/tid-mul-func-xnack-any-on-1.ll |   6 +
 .../AMDGPU/tid-mul-func-xnack-any-on-2.ll |   6 +
 .../tid-one-func-xnack-not-supported.ll   |   6 +
 .../CodeGen/AMDGPU/tid-one-func-xnack-off.ll  |   6 +
 .../CodeGen/AMDGPU/tid-one-func-xnack-on.ll   |   6 +
 .../MC/AMDGPU/hsa-v5-uses-dynamic-stack.s |   5 +
 llvm/tools/llvm-readobj/ELFDumper.cpp | 222 --
 49 files changed, 448 insertions(+), 135 deletions(-)
 create mode 100644 
clang/test/Driver/Inputs/rocm/amdgcn/bitcode/oclc_abi_version_600.bc

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 2b93ddf033499c..0bfe0e7739960e 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4753,9 +4753,9 @@ defm amdgpu_ieee : BoolOption<"m", "amdgpu-ieee",
 def mcode_object_version_EQ : Joined<["-"], "mcode-object-version=">, 
Group,
   HelpText<"Specify code object ABI version. Defaults to 4. (AMDGPU only)">,
   Visibility<[ClangOption, FlangOption, CC1Option, FC1Option]>,
-  Values<"none,4,5">,
+  Values<"none,4,5,6">,
   NormalizedValuesScope<"llvm::CodeObjectVersionKind">,
-  NormalizedValues<["COV_None", "COV_4", "COV_5"]>,
+  NormalizedValues<["COV_None", "COV_4", "COV_5", "COV_6"]>,
   MarshallingInfoEnum, "COV_4">;
 
 defm cumode : SimpleMFlag<"cumode",
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index f71dbf1729a1d6..be86731ed912ea 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -17481,9 +17481,9 @@ Value *EmitAMDGPUImplicitArgPtr(CodeGenFunction &CGF) {
 // \p Index is 0, 1, and 2 for x, y, and z dimension, respectively.
 /// Emit code based on Code Object ABI version.
 /// COV_4: Emit code to use dispatch ptr
-/// COV_5: Emit code to use implicitarg ptr
+/// COV_5+   : Emit code to use implicitarg ptr
 /// COV_NONE : Emit code to load a global variable "__oclc_ABI_versi

[clang] [Serialization] Load Specializations Lazily (1/2) (PR #76774)

2024-01-07 Thread Chuanqi Xu via cfe-commits


@@ -1249,3 +1249,5 @@ void ODRHash::AddQualType(QualType T) {
 void ODRHash::AddBoolean(bool Value) {
   Bools.push_back(Value);
 }
+
+void ODRHash::AddInteger(unsigned Value) { ID.AddInteger(Value); }

ChuanqiXu9 wrote:

The secret why ODRHash can handle this may live in 
https://github.com/llvm/llvm-project/blob/fe1364f1e7ac0c4d0f9a4b15189485782241190d/clang/lib/AST/ODRHash.cpp#L868-L910.
 We've already done the work to strip the types. 

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


[clang] [Serialization] Load Specializations Lazily (1/2) (PR #76774)

2024-01-07 Thread Chuanqi Xu via cfe-commits


@@ -1249,3 +1249,5 @@ void ODRHash::AddQualType(QualType T) {
 void ODRHash::AddBoolean(bool Value) {
   Bools.push_back(Value);
 }
+
+void ODRHash::AddInteger(unsigned Value) { ID.AddInteger(Value); }

ChuanqiXu9 wrote:

I tried to add a test case to show the problem in 
https://github.com/llvm/llvm-project/commit/9b808a4beb8e6c8255b412fdd6f5a3e20cbcf270.
 But the current patch works well for that. While I agree the ODRHash may be 
too aggressive for the problem we're solving, I don't want to write things that 
can't be well tested. I am wondering if we can proceed by leaving a FIXME here 
if we can't find good test in time? Or maybe we can add an option 
`-fload-specialization-lazily`, then we can regress smoothly if there are any 
problems.

@hahnjo @vgvassilev 

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


[clang] 9b808a4 - [NFC] [Modules] Add a test case for selecting specializations with aliased template args

2024-01-07 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2024-01-08T14:46:11+08:00
New Revision: 9b808a4beb8e6c8255b412fdd6f5a3e20cbcf270

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

LOG: [NFC] [Modules] Add a test case for selecting specializations with aliased 
template args

This a test for https://github.com/llvm/llvm-project/pull/76774. In the
review comments, we're concerning about the case that ODRHash may
produce the different hash values for semantical same template
arguments. For example, if the template argument in a specialization is
not qualified and the semantical same template argument in the instantiation
point is qualified, we should be able to select that template
specialization. And this patch tests this behavior: we should be able to select
the correct specialization with semantical same template arguments.

Added: 
clang/test/Modules/explicit-specializations.cppm

Modified: 


Removed: 




diff  --git a/clang/test/Modules/explicit-specializations.cppm 
b/clang/test/Modules/explicit-specializations.cppm
new file mode 100644
index 00..914144018e8808
--- /dev/null
+++ b/clang/test/Modules/explicit-specializations.cppm
@@ -0,0 +1,133 @@
+// Testing that the compiler can select the correct template specialization
+// from 
diff erent template aliasing.
+//
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t
+//
+// RUN: %clang_cc1 -std=c++20 %t/a.cppm -emit-module-interface -o %t/a.pcm
+// RUN: %clang_cc1 -std=c++20 %t/b.cpp -fprebuilt-module-path=%t \
+// RUN: -fsyntax-only -verify
+
+//--- a.cppm
+
+// For template type parameters
+export module a;
+export template 
+struct S {
+static constexpr bool selected = false;
+};
+
+export struct A {};
+
+export template <>
+struct S {
+static constexpr bool selected = true;
+};
+
+export using B = A;
+
+// For template template parameters
+
+export template  typename C>
+struct V {
+static constexpr bool selected = false;
+};
+
+export template <>
+struct V {
+static constexpr bool selected = true;
+};
+
+// For template non type parameters
+export template 
+struct Numbers {
+static constexpr bool selected = false;
+static constexpr int value = X;
+};
+
+export template<>
+struct Numbers<43> {
+static constexpr bool selected = true;
+static constexpr int value = 43;
+};
+
+export template 
+struct Pointers {
+static constexpr bool selected = false;
+};
+
+export int IntegralValue = 0;
+export template<>
+struct Pointers<&IntegralValue> {
+static constexpr bool selected = true;
+};
+
+export template 
+struct NullPointers {
+static constexpr bool selected = false;
+};
+
+export template<>
+struct NullPointers {
+static constexpr bool selected = true;
+};
+
+export template
+struct Array {
+static constexpr bool selected = false;
+};
+
+export int array[5];
+export template<>
+struct Array {
+static constexpr bool selected = true;
+};
+
+//--- b.cpp
+// expected-no-diagnostics
+import a;
+
+// Testing for 
diff erent qualifiers
+static_assert(S::selected);
+static_assert(S<::B>::selected);
+static_assert(::S::selected);
+static_assert(::S<::B>::selected);
+typedef A C;
+static_assert(S::selected);
+static_assert(S<::C>::selected);
+static_assert(::S::selected);
+static_assert(::S<::C>::selected);
+
+namespace D {
+C getAType();
+typedef C E;
+}
+
+static_assert(S::selected);
+static_assert(S::selected);
+
+// Testing we can select the correct specialization for 
diff erent
+// template template argument alising.
+
+static_assert(V::selected);
+static_assert(V<::S>::selected);
+static_assert(::V::selected);
+static_assert(::V<::S>::selected);
+
+// Testing for template non type parameters
+static_assert(Numbers<43>::selected);
+static_assert(Numbers<21 * 2 + 1>::selected);
+static_assert(Numbers<42 + 1>::selected);
+static_assert(Numbers<44 - 1>::selected);
+static_assert(Numbers::value>::selected);
+static_assert(!Numbers<44>::selected);
+
+static_assert(Pointers<&IntegralValue>::selected);
+static_assert(!Pointers::selected);
+static_assert(NullPointers::selected);
+static_assert(!NullPointers<(void*)&IntegralValue>::selected);
+
+static_assert(Array::selected);
+int another_array[5];
+static_assert(!Array::selected);



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


[clang] [llvm] [RISCV] Deduplicate RISCVISAInfo::toFeatures/toFeatureVector. NFC (PR #76942)

2024-01-07 Thread Luke Lau via cfe-commits


@@ -466,35 +466,35 @@ bool RISCVISAInfo::compareExtension(const std::string 
&LHS,
   return LHS < RHS;
 }
 
-void RISCVISAInfo::toFeatures(
-std::vector &Features,
-llvm::function_ref StrAlloc,
-bool AddAllExtensions) const {
-  for (auto const &Ext : Exts) {
-StringRef ExtName = Ext.first;
-
-if (ExtName == "i")
+std::vector RISCVISAInfo::toFeatures(bool AddAllExtensions,
+  bool IgnoreUnknown) const {
+  std::vector Features;
+  for (const auto &[ExtName, _] : Exts) {
+if (ExtName == "i") // i is not recognized in clang -cc1

lukel97 wrote:

This was just copied from the previous function, but would non-RISCV developers 
need to read RISCVISAInfo.cpp? (Still happy to add a link to the spec if you 
would prefer)

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


[clang] [llvm] [RISCV] Add Zicfiss support to the shadow call stack implementation. (PR #68075)

2024-01-07 Thread Yeting Kuo via cfe-commits

https://github.com/yetingk updated 
https://github.com/llvm/llvm-project/pull/68075

>From faed2ea0b0cd7dc207e0886be8cb1647343793d4 Mon Sep 17 00:00:00 2001
From: Yeting Kuo 
Date: Tue, 3 Oct 2023 16:08:06 +0800
Subject: [PATCH 1/6] [RISCV] Implement shadow stack on shadow stack mode with
 Zicfiss.

There are two shadow stack implements with Zicfiss in [spec] now.
In Shadow stack mode, programs still store the return address to regular 
address.
In Control stack mode, programs only store the return address to shadow stack.
This patch only supports the shadow stack mode.

[spec]: 
https://github.com/riscv/riscv-cfi/blob/main/cfi_backward.adoc#push-to-and-pop-from-the-shadow-stack
---
 llvm/lib/Target/RISCV/RISCVFrameLowering.cpp |  14 +-
 llvm/test/CodeGen/RISCV/shadowcallstack.ll   | 130 +++
 2 files changed, 142 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp 
b/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
index 8dfea6d3862057..6f043ade98f409 100644
--- a/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
+++ b/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
@@ -51,9 +51,14 @@ static void emitSCSPrologue(MachineFunction &MF, 
MachineBasicBlock &MBB,
   CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
 return;
 
+  const RISCVInstrInfo *TII = STI.getInstrInfo();
+  if (STI.hasFeature(RISCV::FeatureStdExtZicfiss)) {
+BuildMI(MBB, MI, DL, TII->get(RISCV::SSPUSH)).addReg(RAReg);
+return;
+  }
+
   Register SCSPReg = RISCVABI::getSCSPReg();
 
-  const RISCVInstrInfo *TII = STI.getInstrInfo();
   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
   int64_t SlotSize = STI.getXLen() / 8;
   // Store return address to shadow call stack
@@ -106,9 +111,14 @@ static void emitSCSEpilogue(MachineFunction &MF, 
MachineBasicBlock &MBB,
   CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
 return;
 
+  const RISCVInstrInfo *TII = STI.getInstrInfo();
+  if (STI.hasFeature(RISCV::FeatureStdExtZicfiss)) {
+BuildMI(MBB, MI, DL, TII->get(RISCV::SSPOPCHK)).addReg(RAReg);
+return;
+  }
+
   Register SCSPReg = RISCVABI::getSCSPReg();
 
-  const RISCVInstrInfo *TII = STI.getInstrInfo();
   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
   int64_t SlotSize = STI.getXLen() / 8;
   // Load return address from shadow call stack
diff --git a/llvm/test/CodeGen/RISCV/shadowcallstack.ll 
b/llvm/test/CodeGen/RISCV/shadowcallstack.ll
index b41b87aaf4d0d8..1861d2e36227c3 100644
--- a/llvm/test/CodeGen/RISCV/shadowcallstack.ll
+++ b/llvm/test/CodeGen/RISCV/shadowcallstack.ll
@@ -3,6 +3,10 @@
 ; RUN:   | FileCheck %s --check-prefix=RV32
 ; RUN: llc -mtriple=riscv64 -verify-machineinstrs < %s \
 ; RUN:   | FileCheck %s --check-prefix=RV64
+; RUN: llc -mtriple=riscv32 -mattr=+experimental-zicfiss -verify-machineinstrs 
< %s \
+; RUN:   | FileCheck %s --check-prefix=RV32-ZICFISS
+; RUN: llc -mtriple=riscv64 -mattr=+experimental-zicfiss -verify-machineinstrs 
< %s \
+; RUN:   | FileCheck %s --check-prefix=RV64-ZICFISS
 
 define void @f1() shadowcallstack {
 ; RV32-LABEL: f1:
@@ -12,6 +16,14 @@ define void @f1() shadowcallstack {
 ; RV64-LABEL: f1:
 ; RV64:   # %bb.0:
 ; RV64-NEXT:ret
+;
+; RV32-ZICFISS-LABEL: f1:
+; RV32-ZICFISS:   # %bb.0:
+; RV32-ZICFISS-NEXT:ret
+;
+; RV64-ZICFISS-LABEL: f1:
+; RV64-ZICFISS:   # %bb.0:
+; RV64-ZICFISS-NEXT:ret
   ret void
 }
 
@@ -25,6 +37,14 @@ define void @f2() shadowcallstack {
 ; RV64-LABEL: f2:
 ; RV64:   # %bb.0:
 ; RV64-NEXT:tail foo
+;
+; RV32-ZICFISS-LABEL: f2:
+; RV32-ZICFISS:   # %bb.0:
+; RV32-ZICFISS-NEXT:tail foo
+;
+; RV64-ZICFISS-LABEL: f2:
+; RV64-ZICFISS:   # %bb.0:
+; RV64-ZICFISS-NEXT:tail foo
   tail call void @foo()
   ret void
 }
@@ -65,6 +85,32 @@ define i32 @f3() shadowcallstack {
 ; RV64-NEXT:addi gp, gp, -8
 ; RV64-NEXT:.cfi_restore gp
 ; RV64-NEXT:ret
+;
+; RV32-ZICFISS-LABEL: f3:
+; RV32-ZICFISS:   # %bb.0:
+; RV32-ZICFISS-NEXT:sspush ra
+; RV32-ZICFISS-NEXT:addi sp, sp, -16
+; RV32-ZICFISS-NEXT:.cfi_def_cfa_offset 16
+; RV32-ZICFISS-NEXT:sw ra, 12(sp) # 4-byte Folded Spill
+; RV32-ZICFISS-NEXT:.cfi_offset ra, -4
+; RV32-ZICFISS-NEXT:call bar
+; RV32-ZICFISS-NEXT:lw ra, 12(sp) # 4-byte Folded Reload
+; RV32-ZICFISS-NEXT:addi sp, sp, 16
+; RV32-ZICFISS-NEXT:sspopchk ra
+; RV32-ZICFISS-NEXT:ret
+;
+; RV64-ZICFISS-LABEL: f3:
+; RV64-ZICFISS:   # %bb.0:
+; RV64-ZICFISS-NEXT:sspush ra
+; RV64-ZICFISS-NEXT:addi sp, sp, -16
+; RV64-ZICFISS-NEXT:.cfi_def_cfa_offset 16
+; RV64-ZICFISS-NEXT:sd ra, 8(sp) # 8-byte Folded Spill
+; RV64-ZICFISS-NEXT:.cfi_offset ra, -8
+; RV64-ZICFISS-NEXT:call bar
+; RV64-ZICFISS-NEXT:ld ra, 8(sp) # 8-byte Folded Reload
+; RV64-ZICFISS-NEXT:addi sp, sp, 16
+; RV64-ZICFISS-NEXT:sspopchk ra
+; RV64-ZICFISS-NEXT:ret
   %res = call i32 @bar()
   %res1 = add i32 %res, 1
   ret i32 %res
@@ -140,6 

[clang] [llvm] [RISCV] Add Zicfiss support to the shadow call stack implementation. (PR #68075)

2024-01-07 Thread Yeting Kuo via cfe-commits

https://github.com/yetingk updated 
https://github.com/llvm/llvm-project/pull/68075

>From be70878169742f7e9cbb276a05254019c586897b Mon Sep 17 00:00:00 2001
From: Yeting Kuo 
Date: Tue, 3 Oct 2023 16:08:06 +0800
Subject: [PATCH 1/6] [RISCV] Implement shadow stack on shadow stack mode with
 Zicfiss.

There are two shadow stack implements with Zicfiss in [spec] now.
In Shadow stack mode, programs still store the return address to regular 
address.
In Control stack mode, programs only store the return address to shadow stack.
This patch only supports the shadow stack mode.

[spec]: 
https://github.com/riscv/riscv-cfi/blob/main/cfi_backward.adoc#push-to-and-pop-from-the-shadow-stack
---
 llvm/lib/Target/RISCV/RISCVFrameLowering.cpp |  14 +-
 llvm/test/CodeGen/RISCV/shadowcallstack.ll   | 130 +++
 2 files changed, 142 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp 
b/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
index 8dfea6d3862057..6f043ade98f409 100644
--- a/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
+++ b/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
@@ -51,9 +51,14 @@ static void emitSCSPrologue(MachineFunction &MF, 
MachineBasicBlock &MBB,
   CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
 return;
 
+  const RISCVInstrInfo *TII = STI.getInstrInfo();
+  if (STI.hasFeature(RISCV::FeatureStdExtZicfiss)) {
+BuildMI(MBB, MI, DL, TII->get(RISCV::SSPUSH)).addReg(RAReg);
+return;
+  }
+
   Register SCSPReg = RISCVABI::getSCSPReg();
 
-  const RISCVInstrInfo *TII = STI.getInstrInfo();
   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
   int64_t SlotSize = STI.getXLen() / 8;
   // Store return address to shadow call stack
@@ -106,9 +111,14 @@ static void emitSCSEpilogue(MachineFunction &MF, 
MachineBasicBlock &MBB,
   CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
 return;
 
+  const RISCVInstrInfo *TII = STI.getInstrInfo();
+  if (STI.hasFeature(RISCV::FeatureStdExtZicfiss)) {
+BuildMI(MBB, MI, DL, TII->get(RISCV::SSPOPCHK)).addReg(RAReg);
+return;
+  }
+
   Register SCSPReg = RISCVABI::getSCSPReg();
 
-  const RISCVInstrInfo *TII = STI.getInstrInfo();
   bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
   int64_t SlotSize = STI.getXLen() / 8;
   // Load return address from shadow call stack
diff --git a/llvm/test/CodeGen/RISCV/shadowcallstack.ll 
b/llvm/test/CodeGen/RISCV/shadowcallstack.ll
index fee067ee3ad141..8fbe7ed9ca0766 100644
--- a/llvm/test/CodeGen/RISCV/shadowcallstack.ll
+++ b/llvm/test/CodeGen/RISCV/shadowcallstack.ll
@@ -3,6 +3,10 @@
 ; RUN:   | FileCheck %s --check-prefix=RV32
 ; RUN: llc -mtriple=riscv64 -verify-machineinstrs < %s \
 ; RUN:   | FileCheck %s --check-prefix=RV64
+; RUN: llc -mtriple=riscv32 -mattr=+experimental-zicfiss -verify-machineinstrs 
< %s \
+; RUN:   | FileCheck %s --check-prefix=RV32-ZICFISS
+; RUN: llc -mtriple=riscv64 -mattr=+experimental-zicfiss -verify-machineinstrs 
< %s \
+; RUN:   | FileCheck %s --check-prefix=RV64-ZICFISS
 
 define void @f1() shadowcallstack {
 ; RV32-LABEL: f1:
@@ -12,6 +16,14 @@ define void @f1() shadowcallstack {
 ; RV64-LABEL: f1:
 ; RV64:   # %bb.0:
 ; RV64-NEXT:ret
+;
+; RV32-ZICFISS-LABEL: f1:
+; RV32-ZICFISS:   # %bb.0:
+; RV32-ZICFISS-NEXT:ret
+;
+; RV64-ZICFISS-LABEL: f1:
+; RV64-ZICFISS:   # %bb.0:
+; RV64-ZICFISS-NEXT:ret
   ret void
 }
 
@@ -25,6 +37,14 @@ define void @f2() shadowcallstack {
 ; RV64-LABEL: f2:
 ; RV64:   # %bb.0:
 ; RV64-NEXT:tail foo@plt
+;
+; RV32-ZICFISS-LABEL: f2:
+; RV32-ZICFISS:   # %bb.0:
+; RV32-ZICFISS-NEXT:tail foo@plt
+;
+; RV64-ZICFISS-LABEL: f2:
+; RV64-ZICFISS:   # %bb.0:
+; RV64-ZICFISS-NEXT:tail foo@plt
   tail call void @foo()
   ret void
 }
@@ -65,6 +85,32 @@ define i32 @f3() shadowcallstack {
 ; RV64-NEXT:addi gp, gp, -8
 ; RV64-NEXT:.cfi_restore gp
 ; RV64-NEXT:ret
+;
+; RV32-ZICFISS-LABEL: f3:
+; RV32-ZICFISS:   # %bb.0:
+; RV32-ZICFISS-NEXT:sspush ra
+; RV32-ZICFISS-NEXT:addi sp, sp, -16
+; RV32-ZICFISS-NEXT:.cfi_def_cfa_offset 16
+; RV32-ZICFISS-NEXT:sw ra, 12(sp) # 4-byte Folded Spill
+; RV32-ZICFISS-NEXT:.cfi_offset ra, -4
+; RV32-ZICFISS-NEXT:call bar@plt
+; RV32-ZICFISS-NEXT:lw ra, 12(sp) # 4-byte Folded Reload
+; RV32-ZICFISS-NEXT:addi sp, sp, 16
+; RV32-ZICFISS-NEXT:sspopchk ra
+; RV32-ZICFISS-NEXT:ret
+;
+; RV64-ZICFISS-LABEL: f3:
+; RV64-ZICFISS:   # %bb.0:
+; RV64-ZICFISS-NEXT:sspush ra
+; RV64-ZICFISS-NEXT:addi sp, sp, -16
+; RV64-ZICFISS-NEXT:.cfi_def_cfa_offset 16
+; RV64-ZICFISS-NEXT:sd ra, 8(sp) # 8-byte Folded Spill
+; RV64-ZICFISS-NEXT:.cfi_offset ra, -8
+; RV64-ZICFISS-NEXT:call bar@plt
+; RV64-ZICFISS-NEXT:ld ra, 8(sp) # 8-byte Folded Reload
+; RV64-ZICFISS-NEXT:addi sp, sp, 16
+; RV64-ZICFISS-NEXT:sspopchk ra
+; RV64-ZICFISS-NEXT:ret
   %res = call i32 @bar()
   %res1 = add i32 %res, 1
   ret

[clang] [llvm] [RISCV] Add Zicfiss support to the shadow call stack implementation. (PR #68075)

2024-01-07 Thread Yeting Kuo via cfe-commits

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


[clang] [libclang/python] Expose Rewriter to the python binding (PR #77269)

2024-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Jimmy Z (jimmy-zx)


Changes

Exposes `CXRewriter` API to the python binding as in 
https://github.com/llvm/llvm-project/commit/69e5abb57b70570cf04671a93246e5e624023650.

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


2 Files Affected:

- (modified) clang/bindings/python/clang/cindex.py (+62) 
- (added) clang/bindings/python/tests/cindex/test_rewrite.py (+75) 


``diff
diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index d780ee353a133c..ced449180d98fc 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -3531,6 +3531,61 @@ def cursor(self):
 return cursor
 
 
+class Rewriter(ClangObject):
+"""
+The Rewriter is a wrapper class around clang::Rewriter
+
+It enables rewriting buffers.
+"""
+
+@staticmethod
+def create(tu):
+"""
+Creates a new Rewriter
+Parameters:
+tu -- The translation unit for the target AST.
+"""
+return Rewriter(conf.lib.clang_CXRewriter_create(tu))
+
+def __init__(self, ptr):
+ClangObject.__init__(self, ptr)
+
+def __del__(self):
+conf.lib.clang_CXRewriter_dispose(self)
+
+def insertTextBefore(self, loc, insert):
+"""
+Insert the specified string at the specified location in the original 
buffer.
+"""
+conf.lib.clang_CXRewriter_insertTextBefore(self, loc, insert)
+
+def replaceText(self, toBeReplaced, replacement):
+"""
+This method replaces a range of characters in the input buffer with a 
new string.
+"""
+conf.lib.clang_CXRewriter_replaceText(self, toBeReplaced, replacement)
+
+def removeText(self, toBeRemoved):
+"""
+Remove the specified text region.
+"""
+conf.lib.clang_CXRewriter_removeText(self, toBeRemoved)
+
+def overwriteChangedFiles(self):
+"""
+Save all changed files to disk.
+
+Returns 1 if any files were not saved successfully, returns 0 
otherwise.
+"""
+return conf.lib.clang_CXRewriter_overwriteChangedFiles(self)
+
+def writeMainFileToStdOut(self):
+"""
+Writes the main file to stdout.
+"""
+conf.lib.clang_CXRewriter_writeMainFileToStdOut(self)
+
+
 # Now comes the plumbing to hook up the C library.
 
 # Register callback types in common container.
@@ -3596,6 +3651,13 @@ def cursor(self):
 ("clang_codeCompleteGetNumDiagnostics", [CodeCompletionResults], c_int),
 ("clang_createIndex", [c_int, c_int], c_object_p),
 ("clang_createTranslationUnit", [Index, c_interop_string], c_object_p),
+("clang_CXRewriter_create", [TranslationUnit], c_object_p),
+("clang_CXRewriter_dispose", [Rewriter]),
+("clang_CXRewriter_insertTextBefore", [Rewriter, SourceLocation, 
c_interop_string]),
+("clang_CXRewriter_overwriteChangedFiles", [Rewriter], c_int),
+("clang_CXRewriter_removeText", [Rewriter, SourceRange]),
+("clang_CXRewriter_replaceText", [Rewriter, SourceRange, 
c_interop_string]),
+("clang_CXRewriter_writeMainFileToStdOut", [Rewriter]),
 ("clang_CXXConstructor_isConvertingConstructor", [Cursor], bool),
 ("clang_CXXConstructor_isCopyConstructor", [Cursor], bool),
 ("clang_CXXConstructor_isDefaultConstructor", [Cursor], bool),
diff --git a/clang/bindings/python/tests/cindex/test_rewrite.py 
b/clang/bindings/python/tests/cindex/test_rewrite.py
new file mode 100644
index 00..2c5f904ce50bdc
--- /dev/null
+++ b/clang/bindings/python/tests/cindex/test_rewrite.py
@@ -0,0 +1,75 @@
+import sys
+import io
+import unittest
+import tempfile
+
+from clang.cindex import (
+Rewriter,
+TranslationUnit,
+Config,
+File,
+SourceLocation,
+SourceRange,
+)
+
+
+class TestRewrite(unittest.TestCase):
+code = """
+int test1;
+
+void test2(void);
+
+int f(int c) {
+return c;
+}
+"""
+
+def setUp(self):
+self.tmp = tempfile.NamedTemporaryFile(suffix=".cpp", buffering=0)
+self.tmp.write(TestRewrite.code.encode("utf-8"))
+self.tmp.flush()
+self.tu = TranslationUnit.from_source(self.tmp.name)
+self.rew = Rewriter.create(self.tu)
+self.file = File.from_name(self.tu, self.tmp.name)
+
+def tearDown(self):
+self.tmp.close()
+
+def test_insert(self):
+snip = "#include \n"
+
+beginning = SourceLocation.from_offset(self.tu, self.file, 0)
+self.rew.insertTextBefore(beginning, snip)
+self.rew.overwriteChangedFiles()
+
+with open(self.tmp.name, "r", encoding="utf-8") as f:
+self.assertEqual(f.read(), snip + TestRewrite.code)
+
+def test_replace(self):
+pattern = "test2"
+replacement = "func"
+
+offset = TestRewrite.code.find(pattern)
+pattern_range = SourceRange.from_locations(
+SourceLocation.from_offset

[clang] [libclang/python] Expose Rewriter to the python binding (PR #77269)

2024-01-07 Thread via cfe-commits

github-actions[bot] wrote:

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] [libclang/python] Expose Rewriter to the python binding (PR #77269)

2024-01-07 Thread Jimmy Z via cfe-commits

https://github.com/jimmy-zx created 
https://github.com/llvm/llvm-project/pull/77269

Exposes `CXRewriter` API to the python binding as in 
https://github.com/llvm/llvm-project/commit/69e5abb57b70570cf04671a93246e5e624023650.

>From a5379ca876d9531d48b37b9ad9c864db98c7dcd6 Mon Sep 17 00:00:00 2001
From: Jimmy Z <51149050+jimmy...@users.noreply.github.com>
Date: Mon, 8 Jan 2024 04:36:27 +
Subject: [PATCH] [libclang/python] Expose Rewriter to the python binding

---
 clang/bindings/python/clang/cindex.py | 62 +++
 .../python/tests/cindex/test_rewrite.py   | 75 +++
 2 files changed, 137 insertions(+)
 create mode 100644 clang/bindings/python/tests/cindex/test_rewrite.py

diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index d780ee353a133c..ced449180d98fc 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -3531,6 +3531,61 @@ def cursor(self):
 return cursor
 
 
+class Rewriter(ClangObject):
+"""
+The Rewriter is a wrapper class around clang::Rewriter
+
+It enables rewriting buffers.
+"""
+
+@staticmethod
+def create(tu):
+"""
+Creates a new Rewriter
+Parameters:
+tu -- The translation unit for the target AST.
+"""
+return Rewriter(conf.lib.clang_CXRewriter_create(tu))
+
+def __init__(self, ptr):
+ClangObject.__init__(self, ptr)
+
+def __del__(self):
+conf.lib.clang_CXRewriter_dispose(self)
+
+def insertTextBefore(self, loc, insert):
+"""
+Insert the specified string at the specified location in the original 
buffer.
+"""
+conf.lib.clang_CXRewriter_insertTextBefore(self, loc, insert)
+
+def replaceText(self, toBeReplaced, replacement):
+"""
+This method replaces a range of characters in the input buffer with a 
new string.
+"""
+conf.lib.clang_CXRewriter_replaceText(self, toBeReplaced, replacement)
+
+def removeText(self, toBeRemoved):
+"""
+Remove the specified text region.
+"""
+conf.lib.clang_CXRewriter_removeText(self, toBeRemoved)
+
+def overwriteChangedFiles(self):
+"""
+Save all changed files to disk.
+
+Returns 1 if any files were not saved successfully, returns 0 
otherwise.
+"""
+return conf.lib.clang_CXRewriter_overwriteChangedFiles(self)
+
+def writeMainFileToStdOut(self):
+"""
+Writes the main file to stdout.
+"""
+conf.lib.clang_CXRewriter_writeMainFileToStdOut(self)
+
+
 # Now comes the plumbing to hook up the C library.
 
 # Register callback types in common container.
@@ -3596,6 +3651,13 @@ def cursor(self):
 ("clang_codeCompleteGetNumDiagnostics", [CodeCompletionResults], c_int),
 ("clang_createIndex", [c_int, c_int], c_object_p),
 ("clang_createTranslationUnit", [Index, c_interop_string], c_object_p),
+("clang_CXRewriter_create", [TranslationUnit], c_object_p),
+("clang_CXRewriter_dispose", [Rewriter]),
+("clang_CXRewriter_insertTextBefore", [Rewriter, SourceLocation, 
c_interop_string]),
+("clang_CXRewriter_overwriteChangedFiles", [Rewriter], c_int),
+("clang_CXRewriter_removeText", [Rewriter, SourceRange]),
+("clang_CXRewriter_replaceText", [Rewriter, SourceRange, 
c_interop_string]),
+("clang_CXRewriter_writeMainFileToStdOut", [Rewriter]),
 ("clang_CXXConstructor_isConvertingConstructor", [Cursor], bool),
 ("clang_CXXConstructor_isCopyConstructor", [Cursor], bool),
 ("clang_CXXConstructor_isDefaultConstructor", [Cursor], bool),
diff --git a/clang/bindings/python/tests/cindex/test_rewrite.py 
b/clang/bindings/python/tests/cindex/test_rewrite.py
new file mode 100644
index 00..2c5f904ce50bdc
--- /dev/null
+++ b/clang/bindings/python/tests/cindex/test_rewrite.py
@@ -0,0 +1,75 @@
+import sys
+import io
+import unittest
+import tempfile
+
+from clang.cindex import (
+Rewriter,
+TranslationUnit,
+Config,
+File,
+SourceLocation,
+SourceRange,
+)
+
+
+class TestRewrite(unittest.TestCase):
+code = """
+int test1;
+
+void test2(void);
+
+int f(int c) {
+return c;
+}
+"""
+
+def setUp(self):
+self.tmp = tempfile.NamedTemporaryFile(suffix=".cpp", buffering=0)
+self.tmp.write(TestRewrite.code.encode("utf-8"))
+self.tmp.flush()
+self.tu = TranslationUnit.from_source(self.tmp.name)
+self.rew = Rewriter.create(self.tu)
+self.file = File.from_name(self.tu, self.tmp.name)
+
+def tearDown(self):
+self.tmp.close()
+
+def test_insert(self):
+snip = "#include \n"
+
+beginning = SourceLocation.from_offset(self.tu, self.file, 0)
+self.rew.insertTextBefore(beginning, snip)
+self.rew.overwriteChangedFiles()
+
+with open(self.tmp.name, "r", encoding="utf-8") as f:
+self.assertEqual(f.r

[clang] [libclang/python] Add cursorkinds 272-306 to the python binding (PR #77268)

2024-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Jimmy Z (jimmy-zx)


Changes

Added cursorkinds 272-306 to the python binding as in `index.h`.

Note: seems like `CursorKind.OMP_SCOPE_DIRECTIVE` is not in any of the group. I 
have changed the test cases to reflect that but I am not sure if this is a bug 
or intended behavior.

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


2 Files Affected:

- (modified) clang/bindings/python/clang/cindex.py (+105) 
- (modified) clang/bindings/python/tests/cindex/test_cursor_kind.py (+1) 


``diff
diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index d780ee353a133c..663373baec7856 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -1343,6 +1343,111 @@ def __repr__(self):
 # OpenMP teams distribute directive.
 CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(271)
 
+# OpenMP teams distribute simd directive.
+CursorKind.OMP_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(272)
+
+# OpenMP teams distribute parallel for simd directive.
+CursorKind.OMP_TEAMS_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(273)
+
+# OpenMP teams distribute parallel for directive.
+CursorKind.OMP_TEAMS_DISTRIBUTE_PARALLEL_FOR_DIRECTIVE = CursorKind(274)
+
+# OpenMP target teams directive.
+CursorKind.OMP_TARGET_TEAMS_DIRECTIVE = CursorKind(275)
+
+# OpenMP target teams distribute directive.
+CursorKind.OMP_TARGET_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(276)
+
+# OpenMP target teams distribute parallel for directive.
+CursorKind.OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_FOR_DIRECTIVE = CursorKind(277)
+
+# OpenMP target teams distribute parallel for simd directive.
+CursorKind.OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = 
CursorKind(278)
+
+# OpenMP target teams distribute simd directive.
+CursorKind.OMP_TARGET_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(279)
+
+# C++2a std::bit_cast expression.
+CursorKind.BUILTIN_BIT_CAST_EXPR = CursorKind(280)
+
+# OpenMP master taskloop directive.
+CursorKind.OMP_MASTER_TASK_LOOP_DIRECTIVE = CursorKind(281)
+
+# OpenMP parallel master taskloop directive.
+CursorKind.OMP_PARALLEL_MASTER_TASK_LOOP_DIRECTIVE = CursorKind(282)
+
+# OpenMP master taskloop simd directive.
+CursorKind.OMP_MASTER_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(283)
+
+# OpenMP parallel master taskloop simd directive.
+CursorKind.OMP_PARALLEL_MASTER_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(284)
+
+# OpenMP parallel master directive.
+CursorKind.OMP_PARALLEL_MASTER_DIRECTIVE = CursorKind(285)
+
+# OpenMP depobj directive.
+CursorKind.OMP_DEPOBJ_DIRECTIVE = CursorKind(286)
+
+# OpenMP scan directive.
+CursorKind.OMP_SCAN_DIRECTIVE = CursorKind(287)
+
+# OpenMP tile directive.
+CursorKind.OMP_TILE_DIRECTIVE = CursorKind(288)
+
+# OpenMP canonical loop.
+CursorKind.OMP_CANONICAL_LOOP = CursorKind(289)
+
+# OpenMP interop directive.
+CursorKind.OMP_INTEROP_DIRECTIVE = CursorKind(290)
+
+# OpenMP dispatch directive.
+CursorKind.OMP_DISPATCH_DIRECTIVE = CursorKind(291)
+
+# OpenMP masked directive.
+CursorKind.OMP_MASKED_DIRECTIVE = CursorKind(292)
+
+# OpenMP unroll directive.
+CursorKind.OMP_UNROLL_DIRECTIVE = CursorKind(293)
+
+# OpenMP metadirective directive.
+CursorKind.OMP_META_DIRECTIVE = CursorKind(294)
+
+# OpenMP loop directive.
+CursorKind.OMP_GENERIC_LOOP_DIRECTIVE = CursorKind(295)
+
+# OpenMP teams loop directive.
+CursorKind.OMP_TEAMS_GENERIC_LOOP_DIRECTIVE = CursorKind(296)
+
+# OpenMP target teams loop directive.
+CursorKind.OMP_TARGET_TEAMS_GENERIC_LOOP_DIRECTIVE = CursorKind(297)
+
+# OpenMP parallel loop directive.
+CursorKind.OMP_PARALLEL_GENERIC_LOOP_DIRECTIVE = CursorKind(298)
+
+# OpenMP target parallel loop directive.
+CursorKind.OMP_TARGET_PARALLEL_GENERIC_LOOP_DIRECTIVE = CursorKind(299)
+
+# OpenMP parallel masked directive.
+CursorKind.OMP_PARALLEL_MASKED_DIRECTIVE = CursorKind(300)
+
+# OpenMP masked taskloop directive.
+CursorKind.OMP_MASKED_TASK_LOOP_DIRECTIVE = CursorKind(301)
+
+# OpenMP masked taskloop simd directive.
+CursorKind.OMP_MASKED_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(302)
+
+# OpenMP parallel masked taskloop directive.
+CursorKind.OMP_PARALLEL_MASKED_TASK_LOOP_DIRECTIVE = CursorKind(303)
+
+# OpenMP parallel masked taskloop simd directive.
+CursorKind.OMP_PARALLEL_MASKED_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(304)
+
+# OpenMP error directive.
+CursorKind.OMP_ERROR_DIRECTIVE = CursorKind(305)
+
+# OpenMP scope directive.
+CursorKind.OMP_SCOPE_DIRECTIVE = CursorKind(306)
+
 ###
 # Other Kinds
 
diff --git a/clang/bindings/python/tests/cindex/test_cursor_kind.py 
b/clang/bindings/python/tests/cindex/test_cursor_kind.py
index 87199dba06ed25..d21e362fa73aed 100644
--- a/clang/bindings/python/tests/cindex/test_cursor_kind.py
+++ b/clang/bindings/python/tests/cindex/test_cursor_kind.py
@@ -64,6 +64,7 @@ def test_kind_groups(self):
 CursorKind.INCLUSION_DIRECTIVE,
 CursorKind.PREPROCESSING_DIREC

[clang] [libclang/python] Add cursorkinds 272-306 to the python binding (PR #77268)

2024-01-07 Thread via cfe-commits

github-actions[bot] wrote:

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] [libclang/python] Add cursorkinds 272-306 to the python binding (PR #77268)

2024-01-07 Thread Jimmy Z via cfe-commits

https://github.com/jimmy-zx created 
https://github.com/llvm/llvm-project/pull/77268

Added cursorkinds 272-306 to the python binding as in `index.h`.

Note: seems like `CursorKind.OMP_SCOPE_DIRECTIVE` is not in any of the group. I 
have changed the test cases to reflect that but I am not sure if this is a bug 
or intended behavior.

>From 32b62205d18bf96651db4f695075891b493e6b7e Mon Sep 17 00:00:00 2001
From: Jimmy Z <51149050+jimmy...@users.noreply.github.com>
Date: Mon, 8 Jan 2024 04:11:47 +
Subject: [PATCH] [libclang] Add cursorkinds 272-306

---
 clang/bindings/python/clang/cindex.py | 105 ++
 .../python/tests/cindex/test_cursor_kind.py   |   1 +
 2 files changed, 106 insertions(+)

diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index d780ee353a133c..663373baec7856 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -1343,6 +1343,111 @@ def __repr__(self):
 # OpenMP teams distribute directive.
 CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(271)
 
+# OpenMP teams distribute simd directive.
+CursorKind.OMP_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(272)
+
+# OpenMP teams distribute parallel for simd directive.
+CursorKind.OMP_TEAMS_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(273)
+
+# OpenMP teams distribute parallel for directive.
+CursorKind.OMP_TEAMS_DISTRIBUTE_PARALLEL_FOR_DIRECTIVE = CursorKind(274)
+
+# OpenMP target teams directive.
+CursorKind.OMP_TARGET_TEAMS_DIRECTIVE = CursorKind(275)
+
+# OpenMP target teams distribute directive.
+CursorKind.OMP_TARGET_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(276)
+
+# OpenMP target teams distribute parallel for directive.
+CursorKind.OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_FOR_DIRECTIVE = CursorKind(277)
+
+# OpenMP target teams distribute parallel for simd directive.
+CursorKind.OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = 
CursorKind(278)
+
+# OpenMP target teams distribute simd directive.
+CursorKind.OMP_TARGET_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(279)
+
+# C++2a std::bit_cast expression.
+CursorKind.BUILTIN_BIT_CAST_EXPR = CursorKind(280)
+
+# OpenMP master taskloop directive.
+CursorKind.OMP_MASTER_TASK_LOOP_DIRECTIVE = CursorKind(281)
+
+# OpenMP parallel master taskloop directive.
+CursorKind.OMP_PARALLEL_MASTER_TASK_LOOP_DIRECTIVE = CursorKind(282)
+
+# OpenMP master taskloop simd directive.
+CursorKind.OMP_MASTER_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(283)
+
+# OpenMP parallel master taskloop simd directive.
+CursorKind.OMP_PARALLEL_MASTER_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(284)
+
+# OpenMP parallel master directive.
+CursorKind.OMP_PARALLEL_MASTER_DIRECTIVE = CursorKind(285)
+
+# OpenMP depobj directive.
+CursorKind.OMP_DEPOBJ_DIRECTIVE = CursorKind(286)
+
+# OpenMP scan directive.
+CursorKind.OMP_SCAN_DIRECTIVE = CursorKind(287)
+
+# OpenMP tile directive.
+CursorKind.OMP_TILE_DIRECTIVE = CursorKind(288)
+
+# OpenMP canonical loop.
+CursorKind.OMP_CANONICAL_LOOP = CursorKind(289)
+
+# OpenMP interop directive.
+CursorKind.OMP_INTEROP_DIRECTIVE = CursorKind(290)
+
+# OpenMP dispatch directive.
+CursorKind.OMP_DISPATCH_DIRECTIVE = CursorKind(291)
+
+# OpenMP masked directive.
+CursorKind.OMP_MASKED_DIRECTIVE = CursorKind(292)
+
+# OpenMP unroll directive.
+CursorKind.OMP_UNROLL_DIRECTIVE = CursorKind(293)
+
+# OpenMP metadirective directive.
+CursorKind.OMP_META_DIRECTIVE = CursorKind(294)
+
+# OpenMP loop directive.
+CursorKind.OMP_GENERIC_LOOP_DIRECTIVE = CursorKind(295)
+
+# OpenMP teams loop directive.
+CursorKind.OMP_TEAMS_GENERIC_LOOP_DIRECTIVE = CursorKind(296)
+
+# OpenMP target teams loop directive.
+CursorKind.OMP_TARGET_TEAMS_GENERIC_LOOP_DIRECTIVE = CursorKind(297)
+
+# OpenMP parallel loop directive.
+CursorKind.OMP_PARALLEL_GENERIC_LOOP_DIRECTIVE = CursorKind(298)
+
+# OpenMP target parallel loop directive.
+CursorKind.OMP_TARGET_PARALLEL_GENERIC_LOOP_DIRECTIVE = CursorKind(299)
+
+# OpenMP parallel masked directive.
+CursorKind.OMP_PARALLEL_MASKED_DIRECTIVE = CursorKind(300)
+
+# OpenMP masked taskloop directive.
+CursorKind.OMP_MASKED_TASK_LOOP_DIRECTIVE = CursorKind(301)
+
+# OpenMP masked taskloop simd directive.
+CursorKind.OMP_MASKED_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(302)
+
+# OpenMP parallel masked taskloop directive.
+CursorKind.OMP_PARALLEL_MASKED_TASK_LOOP_DIRECTIVE = CursorKind(303)
+
+# OpenMP parallel masked taskloop simd directive.
+CursorKind.OMP_PARALLEL_MASKED_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(304)
+
+# OpenMP error directive.
+CursorKind.OMP_ERROR_DIRECTIVE = CursorKind(305)
+
+# OpenMP scope directive.
+CursorKind.OMP_SCOPE_DIRECTIVE = CursorKind(306)
+
 ###
 # Other Kinds
 
diff --git a/clang/bindings/python/tests/cindex/test_cursor_kind.py 
b/clang/bindings/python/tests/cindex/test_cursor_kind.py
index 87199dba06ed25..d21e362fa73aed 100644
--- a/clang/bindings/python/tests/cindex/test_cursor_kind.py
+++ b/clang/bindings/python/tests/cindex/test_cursor

[clang-tools-extra] [clangd] Fix is spelled in source bug (PR #76668)

2024-01-07 Thread Nathan Ridge via cfe-commits


@@ -813,6 +813,18 @@ TEST(SourceCodeTests, isKeywords) {
   EXPECT_FALSE(isKeyword("override", LangOpts));
 }
 
+TEST(SourceCodeTests, isSpelledInSource) {
+  Annotations Test("");
+  ParsedAST AST = TestTU::withCode(Test.code()).build();
+  const SourceManager &SM = AST.getSourceManager();
+
+  EXPECT_TRUE(
+  isSpelledInSource(SM.getLocForStartOfFile(SM.getMainFileID()), SM));
+  EXPECT_TRUE(isSpelledInSource(SourceLocation(), SM));

HighCommander4 wrote:

I think it's worth adding a couple of comments here.

First:

```c++
// Check that isSpelledInSource() handles various invalid source locations 
gracefully.
```

But also, a slightly more subtle point:

```c++
// Returning true for SourceLocation() is a behavior that falls out of the 
current
// implementation, which has an early exit for isFileID().
// FIXME: Should it return false on SourceLocation()? Does it matter?
```

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


[clang-tools-extra] [clangd] Fix is spelled in source bug (PR #76668)

2024-01-07 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Fix is spelled in source bug (PR #76668)

2024-01-07 Thread Nathan Ridge via cfe-commits

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

Thanks, looks good with the added comments.

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


[clang-tools-extra] [clangd] Fix sysroot flag handling in CommandMangler to prevent duplicates (PR #75694)

2024-01-07 Thread Nathan Ridge via cfe-commits

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

Thanks, LGTM!

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


[clang] [libclang/python] Expose Rewriter to the libclang python binding. (PR #71341)

2024-01-07 Thread Jimmy Z via cfe-commits

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


[clang] [llvm] [PGO]Add `-fdiagnostics-show-profile-count` option to show real loop count from instr-profile (PR #75021)

2024-01-07 Thread Elvis Wang via cfe-commits


@@ -2091,6 +2091,12 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions 
&Opts, ArgList &Args,
   bool UsingProfile =
   UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
 
+  if (Args.hasArg(options::OPT_fdiagnostics_show_profile_count) &&

ElvisWang123 wrote:

Thanks for your comment! Remove `-cc1` option and migrate warning  generation 
to driver.

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


[clang] [C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of dynamic classes (PR #75912)

2024-01-07 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,50 @@
+// REQUIRES: !system-windows
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t
+//
+// RUN: %clang_cc1 -std=c++20 %t/layer1.cppm -triple %itanium_abi_triple \
+// RUN: -emit-module-interface -o %t/foo-layer1.pcm
+// RUN: %clang_cc1 -std=c++20 %t/layer2.cppm -triple %itanium_abi_triple  \
+// RUN: -emit-module-interface -fmodule-file=foo:layer1=%t/foo-layer1.pcm \
+// RUN: -o %t/foo-layer2.pcm
+// RUN: %clang_cc1 -std=c++20 %t/foo-layer1.pcm -S -emit-llvm -o - | FileCheck 
%t/layer1.cppm
+// RUN: %clang_cc1 -std=c++20 %t/foo-layer2.pcm -S -emit-llvm -o - \
+// RUN: -fmodule-file=foo:layer1=%t/foo-layer1.pcm | FileCheck 
%t/layer2.cppm
+
+//--- layer1.cppm
+export module foo:layer1;
+struct Fruit {
+virtual ~Fruit() = default;
+virtual void eval() = 0;
+};
+struct Banana : public Fruit {
+Banana() {}
+void eval() override;
+};
+

ChuanqiXu9 wrote:

Great suggestion. I caught another bug after I removed `Banana`: previously we 
would only generate vtable if it is used. And my draft to fix that is 
https://github.com/ChuanqiXu9/llvm-project/commit/f6a22849bb410532c60dca4453fd2b0b71da3994.
 It touches Sema and Serializer. So I feel it is a little bit complex even if 
it is small. Personally, I prefer to separate that into 2 patches later instead 
of combining everything in the current single patch. How do you feel about the 
direction? @dwblaikie @rjmccall 

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


[clang] [llvm] [PGO]Add `-fdiagnostics-show-profile-count` option to show real loop count from instr-profile (PR #75021)

2024-01-07 Thread Elvis Wang via cfe-commits

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


[clang-tools-extra] [clangd] Handle lambda scopes inside Node::getDeclContext() (PR #76329)

2024-01-07 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> Happy New Year 2024!

You too!

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


[clang-tools-extra] [clangd] Handle lambda scopes inside Node::getDeclContext() (PR #76329)

2024-01-07 Thread Nathan Ridge via cfe-commits

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

Thanks, the change looks good to me!

I went through the existing callers of `Node::getDeclContext()`, and I was able 
to construct a test case where the patch actually changes behaviour (in a good 
way):

```c++
namespace NS {
void unrelated();
void foo();
}

auto L = [] {
  using NS::unrelated;
  NS::foo();
};
```

Here, if the "add using-declaration" code action is invoked on `NS::foo`, 
before this patch the result is:

```c++
namespace NS {
void unrelated();
void foo();
}

using NS::foo;

auto L = [] {
  using NS::unrelated;
  foo();
};
```

but after this patch the result is:

```c++
namespace NS {
void unrelated();
void foo();
}

auto L = [] {
  using NS::foo;
  using NS::unrelated;
  foo();
};
```

Let's add this test case to `AddUsingTests` while we're at it.

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


[clang] a90ed3e - Revert "[CMake] Include riscv32-unknown-elf runtimes in Fuchsia toolchain (#76849)"

2024-01-07 Thread Petr Hosek via cfe-commits

Author: Petr Hosek
Date: 2024-01-08T03:29:30Z
New Revision: a90ed3e8a4ea8c5238fd660bbac0371366afe3b5

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

LOG: Revert "[CMake] Include riscv32-unknown-elf runtimes in Fuchsia toolchain 
(#76849)"

This reverts commit 78550bef98347bccbf0e8e5fb66dc59718fc35ec since
it broke the two stage build.

Added: 


Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index eee37c5e7901fa..c4673c8a54c5ef 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -6,7 +6,7 @@ set(LLVM_TARGETS_TO_BUILD X86;ARM;AArch64;RISCV CACHE STRING "")
 
 set(PACKAGE_VENDOR Fuchsia CACHE STRING "")
 
-set(_FUCHSIA_ENABLE_PROJECTS 
"bolt;clang;clang-tools-extra;libc;lld;llvm;polly")
+set(_FUCHSIA_ENABLE_PROJECTS "bolt;clang;clang-tools-extra;lld;llvm;polly")
 set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING 
"")
 
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
@@ -22,11 +22,8 @@ set(LLVM_ENABLE_TERMINFO OFF CACHE BOOL "")
 set(LLVM_ENABLE_UNWIND_TABLES OFF CACHE BOOL "")
 set(LLVM_ENABLE_Z3_SOLVER OFF CACHE BOOL "")
 set(LLVM_ENABLE_ZLIB ON CACHE BOOL "")
-set(LLVM_FORCE_BUILD_RUNTIME ON CACHE BOOL "")
 set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "")
 set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
-set(LLVM_LIBC_FULL_BUILD ON CACHE BOOL "")
-set(LIBC_HDRGEN_ONLY ON CACHE BOOL "")
 set(LLVM_STATIC_LINK_CXX_STDLIB ON CACHE BOOL "")
 set(LLVM_USE_RELATIVE_PATHS_IN_FILES ON CACHE BOOL "")
 set(LLDB_ENABLE_CURSES OFF CACHE BOOL "")
@@ -300,39 +297,6 @@ if(FUCHSIA_SDK)
   set(LLVM_RUNTIME_MULTILIB_hwasan+noexcept_TARGETS 
"aarch64-unknown-fuchsia;riscv64-unknown-fuchsia" CACHE STRING "")
 endif()
 
-foreach(target riscv32-unknown-elf)
-  list(APPEND BUILTIN_TARGETS "${target}")
-  set(BUILTINS_${target}_CMAKE_SYSTEM_NAME Generic CACHE STRING "")
-  set(BUILTINS_${target}_CMAKE_SYSTEM_PROCESSOR RISCV CACHE STRING "")
-  set(BUILTINS_${target}_CMAKE_SYSROOT "" CACHE STRING "")
-  set(BUILTINS_${target}_CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "")
-  foreach(lang C;CXX;ASM)
-set(BUILTINS_${target}_CMAKE_${lang}_FLAGS "--target=${target} 
-march=rv32imafc -mabi=ilp32f" CACHE STRING "")
-  endforeach()
-  foreach(type SHARED;MODULE;EXE)
-set(BUILTINS_${target}_CMAKE_${type}_LINKER_FLAGS "-fuse-ld=lld" CACHE 
STRING "")
-  endforeach()
-  set(BUILTINS_${target}_COMPILER_RT_BAREMETAL_BUILD ON CACHE BOOL "")
-
-  list(APPEND RUNTIME_TARGETS "${target}")
-  set(RUNTIMES_${target}_CMAKE_SYSTEM_NAME Generic CACHE STRING "")
-  set(RUNTIMES_${target}_CMAKE_SYSTEM_PROCESSOR RISCV CACHE STRING "")
-  set(RUNTIMES_${target}_CMAKE_SYSROOT "" CACHE STRING "")
-  set(RUNTIMES_${target}_CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "")
-  set(RUNTIMES_${target}_CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY CACHE 
STRING "")
-  foreach(lang C;CXX;ASM)
-set(RUNTIMES_${target}_CMAKE_${lang}_FLAGS "--target=${target} 
-march=rv32imafc -mabi=ilp32f" CACHE STRING "")
-  endforeach()
-  foreach(type SHARED;MODULE;EXE)
-set(RUNTIMES_${target}_CMAKE_${type}_LINKER_FLAGS "-fuse-ld=lld" CACHE 
STRING "")
-  endforeach()
-  set(RUNTIMES_${target}_LLVM_LIBC_FULL_BUILD ON CACHE BOOL "")
-  set(RUNTIMES_${target}_LIBC_ENABLE_USE_BY_CLANG ON CACHE BOOL "")
-  set(RUNTIMES_${target}_LLVM_INCLUDE_TESTS OFF CACHE BOOL "")
-  set(RUNTIMES_${target}_LLVM_ENABLE_ASSERTIONS OFF CACHE BOOL "")
-  set(RUNTIMES_${target}_LLVM_ENABLE_RUNTIMES "libc" CACHE STRING "")
-endforeach()
-
 set(LLVM_BUILTIN_TARGETS "${BUILTIN_TARGETS}" CACHE STRING "")
 set(LLVM_RUNTIME_TARGETS "${RUNTIME_TARGETS}" CACHE STRING "")
 



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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-07 Thread Chuanqi Xu via cfe-commits

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-07 Thread Chuanqi Xu via cfe-commits

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-07 Thread Chuanqi Xu via cfe-commits


@@ -7575,15 +7577,27 @@ static void 
visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
 Path.pop_back();
   };
 
-  if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
-VisitLifetimeBoundArg(Callee, ObjectArg);
-
   bool CheckCoroCall = false;
   if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
 CheckCoroCall = RD->hasAttr() &&
 RD->hasAttr() &&
 !Callee->hasAttr();
   }
+
+  if (ObjectArg) {
+bool CheckCoroObjArg = CheckCoroCall;
+// Ignore `__promise.get_return_object()` as it is not lifetimebound.
+if (CheckCoroObjArg && Callee->getDeclName().isIdentifier() &&
+Callee->getName() == "get_return_object")
+  CheckCoroObjArg = false;
+// Coroutine lambda objects with empty capture list are not lifetimebound.
+if (auto *LE = dyn_cast(ObjectArg->IgnoreImplicit());
+LE && LE->captures().empty())
+  CheckCoroObjArg = false;

ChuanqiXu9 wrote:

I am a little bit surprised that we need to handle this specially. Is this an 
optimization? Or it is necessary and why?

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-07 Thread Chuanqi Xu via cfe-commits


@@ -7575,15 +7577,27 @@ static void 
visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
 Path.pop_back();
   };
 
-  if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
-VisitLifetimeBoundArg(Callee, ObjectArg);
-
   bool CheckCoroCall = false;
   if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
 CheckCoroCall = RD->hasAttr() &&
 RD->hasAttr() &&
 !Callee->hasAttr();
   }
+
+  if (ObjectArg) {
+bool CheckCoroObjArg = CheckCoroCall;
+// Ignore `__promise.get_return_object()` as it is not lifetimebound.
+if (CheckCoroObjArg && Callee->getDeclName().isIdentifier() &&
+Callee->getName() == "get_return_object")
+  CheckCoroObjArg = false;

ChuanqiXu9 wrote:

The hardcoded name are not good. What's wrong with it? And if necessary, we'd 
better to check it with the built `CoroutineBodyStmt::getReturnStmt` (and maybe 
`CoroutineBodyStmt::getReturnStmtOnAllocFailure`?) If that is not built this 
time, can we perform that in `Sema::CheckCompletedCoroutineBody`? Maybe that 
will require a little bit refactor work, but I guess it may be worthy.

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-07 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 commented:

Maybe it'll be better to say this is related to `[[coro_lifetimebound]]`. My 
instinct reaction to this is that "no, this is not strictly correct". But I 
feel good after I know it is an extension of `[[coro_lifetimebound]]` only.

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


[clang] [CMake] Include riscv32-unknown-elf runtimes in Fuchsia toolchain (PR #76849)

2024-01-07 Thread Petr Hosek via cfe-commits

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


[clang] 78550be - [CMake] Include riscv32-unknown-elf runtimes in Fuchsia toolchain (#76849)

2024-01-07 Thread via cfe-commits

Author: Petr Hosek
Date: 2024-01-07T18:13:39-08:00
New Revision: 78550bef98347bccbf0e8e5fb66dc59718fc35ec

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

LOG: [CMake] Include riscv32-unknown-elf runtimes in Fuchsia toolchain (#76849)

This contains compiler-rt builtins and llvm-libc for baremetal use.

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

Added: 


Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index c4673c8a54c5ef..eee37c5e7901fa 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -6,7 +6,7 @@ set(LLVM_TARGETS_TO_BUILD X86;ARM;AArch64;RISCV CACHE STRING "")
 
 set(PACKAGE_VENDOR Fuchsia CACHE STRING "")
 
-set(_FUCHSIA_ENABLE_PROJECTS "bolt;clang;clang-tools-extra;lld;llvm;polly")
+set(_FUCHSIA_ENABLE_PROJECTS 
"bolt;clang;clang-tools-extra;libc;lld;llvm;polly")
 set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING 
"")
 
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
@@ -22,8 +22,11 @@ set(LLVM_ENABLE_TERMINFO OFF CACHE BOOL "")
 set(LLVM_ENABLE_UNWIND_TABLES OFF CACHE BOOL "")
 set(LLVM_ENABLE_Z3_SOLVER OFF CACHE BOOL "")
 set(LLVM_ENABLE_ZLIB ON CACHE BOOL "")
+set(LLVM_FORCE_BUILD_RUNTIME ON CACHE BOOL "")
 set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "")
 set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
+set(LLVM_LIBC_FULL_BUILD ON CACHE BOOL "")
+set(LIBC_HDRGEN_ONLY ON CACHE BOOL "")
 set(LLVM_STATIC_LINK_CXX_STDLIB ON CACHE BOOL "")
 set(LLVM_USE_RELATIVE_PATHS_IN_FILES ON CACHE BOOL "")
 set(LLDB_ENABLE_CURSES OFF CACHE BOOL "")
@@ -297,6 +300,39 @@ if(FUCHSIA_SDK)
   set(LLVM_RUNTIME_MULTILIB_hwasan+noexcept_TARGETS 
"aarch64-unknown-fuchsia;riscv64-unknown-fuchsia" CACHE STRING "")
 endif()
 
+foreach(target riscv32-unknown-elf)
+  list(APPEND BUILTIN_TARGETS "${target}")
+  set(BUILTINS_${target}_CMAKE_SYSTEM_NAME Generic CACHE STRING "")
+  set(BUILTINS_${target}_CMAKE_SYSTEM_PROCESSOR RISCV CACHE STRING "")
+  set(BUILTINS_${target}_CMAKE_SYSROOT "" CACHE STRING "")
+  set(BUILTINS_${target}_CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "")
+  foreach(lang C;CXX;ASM)
+set(BUILTINS_${target}_CMAKE_${lang}_FLAGS "--target=${target} 
-march=rv32imafc -mabi=ilp32f" CACHE STRING "")
+  endforeach()
+  foreach(type SHARED;MODULE;EXE)
+set(BUILTINS_${target}_CMAKE_${type}_LINKER_FLAGS "-fuse-ld=lld" CACHE 
STRING "")
+  endforeach()
+  set(BUILTINS_${target}_COMPILER_RT_BAREMETAL_BUILD ON CACHE BOOL "")
+
+  list(APPEND RUNTIME_TARGETS "${target}")
+  set(RUNTIMES_${target}_CMAKE_SYSTEM_NAME Generic CACHE STRING "")
+  set(RUNTIMES_${target}_CMAKE_SYSTEM_PROCESSOR RISCV CACHE STRING "")
+  set(RUNTIMES_${target}_CMAKE_SYSROOT "" CACHE STRING "")
+  set(RUNTIMES_${target}_CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "")
+  set(RUNTIMES_${target}_CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY CACHE 
STRING "")
+  foreach(lang C;CXX;ASM)
+set(RUNTIMES_${target}_CMAKE_${lang}_FLAGS "--target=${target} 
-march=rv32imafc -mabi=ilp32f" CACHE STRING "")
+  endforeach()
+  foreach(type SHARED;MODULE;EXE)
+set(RUNTIMES_${target}_CMAKE_${type}_LINKER_FLAGS "-fuse-ld=lld" CACHE 
STRING "")
+  endforeach()
+  set(RUNTIMES_${target}_LLVM_LIBC_FULL_BUILD ON CACHE BOOL "")
+  set(RUNTIMES_${target}_LIBC_ENABLE_USE_BY_CLANG ON CACHE BOOL "")
+  set(RUNTIMES_${target}_LLVM_INCLUDE_TESTS OFF CACHE BOOL "")
+  set(RUNTIMES_${target}_LLVM_ENABLE_ASSERTIONS OFF CACHE BOOL "")
+  set(RUNTIMES_${target}_LLVM_ENABLE_RUNTIMES "libc" CACHE STRING "")
+endforeach()
+
 set(LLVM_BUILTIN_TARGETS "${BUILTIN_TARGETS}" CACHE STRING "")
 set(LLVM_RUNTIME_TARGETS "${RUNTIME_TARGETS}" CACHE STRING "")
 



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


[clang] [CMake] Include riscv32-unknown-elf runtimes in Fuchsia toolchain (PR #76849)

2024-01-07 Thread Petr Hosek via cfe-commits

https://github.com/petrhosek updated 
https://github.com/llvm/llvm-project/pull/76849

>From 0cb22bea1e724ca62306081da2ae97bbcc395a86 Mon Sep 17 00:00:00 2001
From: Petr Hosek 
Date: Fri, 9 Jun 2023 07:17:13 +
Subject: [PATCH] [CMake] Include riscv32-unknown-elf runtimes in Fuchsia
 toolchain

This contains compiler-rt builtins and llvm-libc for baremetal use.

Differential Revision: https://reviews.llvm.org/D155337
---
 clang/cmake/caches/Fuchsia-stage2.cmake | 38 -
 1 file changed, 37 insertions(+), 1 deletion(-)

diff --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index c4673c8a54c5ef..eee37c5e7901fa 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -6,7 +6,7 @@ set(LLVM_TARGETS_TO_BUILD X86;ARM;AArch64;RISCV CACHE STRING "")
 
 set(PACKAGE_VENDOR Fuchsia CACHE STRING "")
 
-set(_FUCHSIA_ENABLE_PROJECTS "bolt;clang;clang-tools-extra;lld;llvm;polly")
+set(_FUCHSIA_ENABLE_PROJECTS 
"bolt;clang;clang-tools-extra;libc;lld;llvm;polly")
 set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING 
"")
 
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
@@ -22,8 +22,11 @@ set(LLVM_ENABLE_TERMINFO OFF CACHE BOOL "")
 set(LLVM_ENABLE_UNWIND_TABLES OFF CACHE BOOL "")
 set(LLVM_ENABLE_Z3_SOLVER OFF CACHE BOOL "")
 set(LLVM_ENABLE_ZLIB ON CACHE BOOL "")
+set(LLVM_FORCE_BUILD_RUNTIME ON CACHE BOOL "")
 set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "")
 set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
+set(LLVM_LIBC_FULL_BUILD ON CACHE BOOL "")
+set(LIBC_HDRGEN_ONLY ON CACHE BOOL "")
 set(LLVM_STATIC_LINK_CXX_STDLIB ON CACHE BOOL "")
 set(LLVM_USE_RELATIVE_PATHS_IN_FILES ON CACHE BOOL "")
 set(LLDB_ENABLE_CURSES OFF CACHE BOOL "")
@@ -297,6 +300,39 @@ if(FUCHSIA_SDK)
   set(LLVM_RUNTIME_MULTILIB_hwasan+noexcept_TARGETS 
"aarch64-unknown-fuchsia;riscv64-unknown-fuchsia" CACHE STRING "")
 endif()
 
+foreach(target riscv32-unknown-elf)
+  list(APPEND BUILTIN_TARGETS "${target}")
+  set(BUILTINS_${target}_CMAKE_SYSTEM_NAME Generic CACHE STRING "")
+  set(BUILTINS_${target}_CMAKE_SYSTEM_PROCESSOR RISCV CACHE STRING "")
+  set(BUILTINS_${target}_CMAKE_SYSROOT "" CACHE STRING "")
+  set(BUILTINS_${target}_CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "")
+  foreach(lang C;CXX;ASM)
+set(BUILTINS_${target}_CMAKE_${lang}_FLAGS "--target=${target} 
-march=rv32imafc -mabi=ilp32f" CACHE STRING "")
+  endforeach()
+  foreach(type SHARED;MODULE;EXE)
+set(BUILTINS_${target}_CMAKE_${type}_LINKER_FLAGS "-fuse-ld=lld" CACHE 
STRING "")
+  endforeach()
+  set(BUILTINS_${target}_COMPILER_RT_BAREMETAL_BUILD ON CACHE BOOL "")
+
+  list(APPEND RUNTIME_TARGETS "${target}")
+  set(RUNTIMES_${target}_CMAKE_SYSTEM_NAME Generic CACHE STRING "")
+  set(RUNTIMES_${target}_CMAKE_SYSTEM_PROCESSOR RISCV CACHE STRING "")
+  set(RUNTIMES_${target}_CMAKE_SYSROOT "" CACHE STRING "")
+  set(RUNTIMES_${target}_CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "")
+  set(RUNTIMES_${target}_CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY CACHE 
STRING "")
+  foreach(lang C;CXX;ASM)
+set(RUNTIMES_${target}_CMAKE_${lang}_FLAGS "--target=${target} 
-march=rv32imafc -mabi=ilp32f" CACHE STRING "")
+  endforeach()
+  foreach(type SHARED;MODULE;EXE)
+set(RUNTIMES_${target}_CMAKE_${type}_LINKER_FLAGS "-fuse-ld=lld" CACHE 
STRING "")
+  endforeach()
+  set(RUNTIMES_${target}_LLVM_LIBC_FULL_BUILD ON CACHE BOOL "")
+  set(RUNTIMES_${target}_LIBC_ENABLE_USE_BY_CLANG ON CACHE BOOL "")
+  set(RUNTIMES_${target}_LLVM_INCLUDE_TESTS OFF CACHE BOOL "")
+  set(RUNTIMES_${target}_LLVM_ENABLE_ASSERTIONS OFF CACHE BOOL "")
+  set(RUNTIMES_${target}_LLVM_ENABLE_RUNTIMES "libc" CACHE STRING "")
+endforeach()
+
 set(LLVM_BUILTIN_TARGETS "${BUILTIN_TARGETS}" CACHE STRING "")
 set(LLVM_RUNTIME_TARGETS "${RUNTIME_TARGETS}" CACHE STRING "")
 

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


[llvm] [clang] [PGO]Add `-fdiagnostics-show-profile-count` option to show real loop count from instr-profile (PR #75021)

2024-01-07 Thread Elvis Wang via cfe-commits

https://github.com/ElvisWang123 updated 
https://github.com/llvm/llvm-project/pull/75021

>From 22ff830f3bd113eebd6b8369c61700879ae02b4a Mon Sep 17 00:00:00 2001
From: Elvis Wang 
Date: Sun, 10 Dec 2023 18:34:37 -0800
Subject: [PATCH 1/2] [PGO] Add `-fdiagnostics-show-profile-count` option to
 show real loop count from instr-profile

The original `-fdiagnostics-show-hotness` option show the relative
number of the loop count which is calculate by the
`function_entry_count` and `branch_frequency`. We want to know the real
loop iteration count in the remark which is collect in the instrument
profile, adding a new option to expose the new feature.

- Add a new metadata `MD_prof_count` which contains the runtime loop
iterations count. For example:
```
loop.header:
  ...
  br  i1  %0, label %true, label %false, !prof.count !0
...
!0 = !{!"profile_count", !i64 0}
```

- If option `-fdiagnostics-show-profile-count` is set we will append the
`MD_prof_count` metadata at the branch instruction at the header of
loops.
- Show the profile count like hotness with remark. For example:
```
  remark: the cost-model indicates that interleaving is not beneficial
  (ProfileCount: 20) [-Rpass-analysis=loop-vectorize]
  38 |   for(int i = 0;  i < argc % 20; i++){
 |   ^
```
---
 clang/docs/UsersManual.rst| 24 ++
 .../clang/Basic/DiagnosticDriverKinds.td  |  3 +
 clang/include/clang/Driver/Options.td |  3 +
 clang/lib/CodeGen/CGStmt.cpp  | 27 ++-
 clang/lib/CodeGen/CodeGenAction.cpp   |  4 +
 clang/lib/CodeGen/CodeGenFunction.h   |  1 +
 clang/lib/CodeGen/CodeGenPGO.cpp  | 12 +++
 clang/lib/Driver/ToolChains/Clang.cpp |  5 ++
 clang/lib/Frontend/CompilerInvocation.cpp |  6 ++
 ...ization-remark-with-profile-count.proftext |  9 +++
 ...ization-remark-with-profile-count-new-pm.c | 41 +++
 .../Inputs/c-profile-count-metadata.proftext  | 32 
 clang/test/Profile/c-profile-count-metadata.c | 73 +++
 llvm/docs/LangRef.rst | 22 ++
 .../llvm/Analysis/OptimizationRemarkEmitter.h |  7 ++
 llvm/include/llvm/IR/DiagnosticInfo.h |  6 ++
 llvm/include/llvm/IR/FixedMetadataKinds.def   |  1 +
 llvm/include/llvm/IR/MDBuilder.h  |  3 +
 llvm/include/llvm/Remarks/Remark.h|  4 +
 .../Analysis/OptimizationRemarkEmitter.cpp| 22 ++
 llvm/lib/IR/LLVMRemarkStreamer.cpp|  1 +
 llvm/lib/IR/MDBuilder.cpp | 10 +++
 llvm/lib/Remarks/Remark.cpp   |  2 +
 llvm/lib/Remarks/YAMLRemarkSerializer.cpp |  7 +-
 24 files changed, 319 insertions(+), 6 deletions(-)
 create mode 100644 
clang/test/Frontend/Inputs/optimization-remark-with-profile-count.proftext
 create mode 100644 
clang/test/Frontend/optimization-remark-with-profile-count-new-pm.c
 create mode 100644 clang/test/Profile/Inputs/c-profile-count-metadata.proftext
 create mode 100644 clang/test/Profile/c-profile-count-metadata.c

diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index f1b344ef5109b5..e3e4b585713df9 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -425,6 +425,30 @@ output format of the diagnostics that it generates.
If this option is not used, all the passes are included in the optimization
record.
 
+.. option:: -fdiagnostics-show-profile-count
+
+   Enable profile loop count information in diagnostic line.
+
+   This option controls whether Clang prints the profile loop count associated
+   with diagnostics in the presence of profile-guided optimization information.
+   This is currently supported with optimization remarks (see
+   :ref:`Options to Emit Optimization Reports `). The profile count 
information
+   allows users to focus on the hot optimization remarks that are likely to be
+   more relevant for run-time performance. The main difference between profile 
count
+   the hotness is the profile count is the real profile count from the runtime
+   profile and hotness is a relative number calculated by function entry count 
and
+   weight.
+
+   For example, in this output, the block containing the callsite of `foo` was
+   executed 3000 times according to the profile data:
+
+   ::
+
+s.c:38:3: remark: the cost-model indicates that interleaving is not 
beneficial (ProfileCount: 20) [-Rpass-analysis=loop-vectorize]
+  for(int i = 0;  i < 20; i++){
+  ^
+
+
 .. _opt_fdiagnostics-show-hotness:
 
 .. option:: -f[no-]diagnostics-show-hotness
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 676f1a62b49dd0..47ad1e058a1d82 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -420,6 +420,9 @@ def warn_drv_empty_joined_argument : Warning<
 def warn_drv_diagnostics_hotness_requires_pgo : Warning<
   "argument '%0' requires profi

[clang] [Sema] Warning for _Float16 passed to format specifier '%f' (PR #74439)

2024-01-07 Thread Haocong Lu via cfe-commits

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


[clang] 5034994 - [Sema] Warning for _Float16 passed to format specifier '%f' (#74439)

2024-01-07 Thread via cfe-commits

Author: Haocong Lu
Date: 2024-01-08T09:50:36+08:00
New Revision: 5034994134bbec92c1f1116c56008ac504f7d763

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

LOG: [Sema] Warning for _Float16 passed to format specifier '%f' (#74439)

According to https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2844.pdf,
default argument promotions for _FloatN types has been removed.

A warning is needed to notice user to promote _Float16 to double
explicitly, and then pass it to format specifier '%f', which is
consistent with GCC.

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

Added: 


Modified: 
clang/lib/AST/FormatString.cpp
clang/test/Sema/attr-format.c
clang/test/SemaCXX/attr-format.cpp
clang/test/SemaCXX/format-strings-scanf.cpp

Removed: 




diff  --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp
index e0c9e18cfe3a24..c5d14b4af7ff15 100644
--- a/clang/lib/AST/FormatString.cpp
+++ b/clang/lib/AST/FormatString.cpp
@@ -488,7 +488,6 @@ ArgType::matchesType(ASTContext &C, QualType argTy) const {
 return NoMatchPromotionTypeConfusion;
   break;
 case BuiltinType::Half:
-case BuiltinType::Float16:
 case BuiltinType::Float:
   if (T == C.DoubleTy)
 return MatchPromotion;

diff  --git a/clang/test/Sema/attr-format.c b/clang/test/Sema/attr-format.c
index 1f4c864d4f78bd..bdfd8425c4e9a5 100644
--- a/clang/test/Sema/attr-format.c
+++ b/clang/test/Sema/attr-format.c
@@ -16,6 +16,8 @@ typedef const char *xpto;
 void j(xpto c, va_list list) __attribute__((format(printf, 1, 0))); // no-error
 void k(xpto c) __attribute__((format(printf, 1, 0)));   // no-error
 
+void l(char *a, _Float16 b) __attribute__((format(printf, 1, 2))); // 
expected-warning {{GCC requires a function with the 'format' attribute to be 
variadic}}
+
 void y(char *str) __attribute__((format(strftime, 1, 0))); // 
no-error
 void z(char *str, int c, ...) __attribute__((format(strftime, 1, 2))); // 
expected-error {{strftime format attribute requires 3rd parameter to be 0}}
 
@@ -93,6 +95,11 @@ void call_nonvariadic(void) {
   d3("%s", 123); // expected-warning{{format specifies type 'char *' but the 
argument has type 'int'}}
 }
 
+void call_no_default_promotion(void) {
+  a("%f", (_Float16)1.0); // expected-warning{{format specifies type 'double' 
but the argument has type '_Float16'}}
+  l("%f", (_Float16)1.0); // expected-warning{{format specifies type 'double' 
but the argument has type '_Float16'}}
+}
+
 __attribute__((format(printf, 1, 2)))
 void forward_fixed(const char *fmt, _Bool b, char i, short j, int k, float l, 
double m) { // expected-warning{{GCC requires a function with the 'format' 
attribute to be variadic}}
   forward_fixed(fmt, b, i, j, k, l, m);

diff  --git a/clang/test/SemaCXX/attr-format.cpp 
b/clang/test/SemaCXX/attr-format.cpp
index adc05fc46776ca..4509c3a95e8efa 100644
--- a/clang/test/SemaCXX/attr-format.cpp
+++ b/clang/test/SemaCXX/attr-format.cpp
@@ -81,6 +81,7 @@ void do_format() {
 
   format("%c %c %hhd %hd %d\n", (char)'a', 'a', 'a', (short)123, (int)123);
   format("%f %f %f\n", (__fp16)123.f, 123.f, 123.);
+  format("%f", (_Float16)123.f);// expected-warning{{format specifies type 
'double' but the argument has type '_Float16'}}
   format("%Lf", (__fp16)123.f); // expected-warning{{format specifies type 
'long double' but the argument has type '__fp16'}}
   format("%Lf", 123.f); // expected-warning{{format specifies type 'long 
double' but the argument has type 'float'}}
   format("%hhi %hhu %hi %hu %i %u", b, b, b, b, b, b);

diff  --git a/clang/test/SemaCXX/format-strings-scanf.cpp 
b/clang/test/SemaCXX/format-strings-scanf.cpp
index 25fe5346791a0d..406c2069e28ca7 100644
--- a/clang/test/SemaCXX/format-strings-scanf.cpp
+++ b/clang/test/SemaCXX/format-strings-scanf.cpp
@@ -22,6 +22,7 @@ union bag {
 unsigned long long ull;
 signed long long sll;
 __fp16 f16;
+_Float16 Float16;
 float ff;
 double fd;
 long double fl;
@@ -51,18 +52,21 @@ void test(void) {
 // expected-warning@+1{{format specifies type 'int *' but the argument has 
type 'short *'}}
 scan("%hhi %i %li", &b.ss, &b.ss, &b.ss);
 
-// expected-warning@+3{{format specifies type 'float *' but the argument 
has type '__fp16 *'}}
+// expected-warning@+4{{format specifies type 'float *' but the argument 
has type '__fp16 *'}}
+// expected-warning@+3{{format specifies type 'float *' but the argument 
has type '_Float16 *'}}
 // expected-warning@+2{{format specifies type 'float *' but the argument 
has type 'double *'}}
 // expected-warning@+1{{format specifies type 'float *' but the argument 
has type 'long double *'}}
-scan("%

[llvm] [clang] [clang-tools-extra] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-07 Thread Freddy Ye via cfe-commits

https://github.com/FreddyLeaf updated 
https://github.com/llvm/llvm-project/pull/75580

>From e16afbdc9f0c04bad0e8f80f90c0eb26c13d3326 Mon Sep 17 00:00:00 2001
From: Freddy Ye 
Date: Fri, 15 Dec 2023 16:50:23 +0800
Subject: [PATCH 1/7] [X86] Emit Warnings for frontend options to enable
 knl/knm.

Since Knight Landing and Knight Mill microarchitectures are EOL, we
would like to remove its support in LLVM 19. In LLVM 18, we will first
emit a warning for the usage.
---
 clang/include/clang/Basic/DiagnosticCommonKinds.td |  2 ++
 clang/lib/Basic/Targets/X86.cpp|  3 +++
 clang/test/CodeGen/X86/avx512er-builtins.c |  2 +-
 clang/test/CodeGen/X86/avx512pf-builtins.c |  2 +-
 clang/test/Driver/cl-x86-flags.c   | 10 --
 clang/test/Frontend/x86-target-cpu.c   | 10 --
 clang/test/Misc/warning-flags.c|  3 ++-
 7 files changed, 25 insertions(+), 7 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td 
b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index 65a33f61a6948a..40841e9df547bc 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -349,6 +349,8 @@ def warn_invalid_feature_combination : Warning<
 def warn_target_unrecognized_env : Warning<
   "mismatch between architecture and environment in target triple '%0'; did 
you mean '%1'?">,
   InGroup;
+def warn_knl_knm_target_supports_remove : Warning<
+  "KNL/KNM's feature support will be removed in LLVM 19.">;
 
 // Source manager
 def err_cannot_open_file : Error<"cannot open file '%0': %1">, DefaultFatal;
diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index b97f88647fa49f..dc56524d378104 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -295,11 +295,13 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
   HasAVX512BF16 = true;
 } else if (Feature == "+avx512er") {
   HasAVX512ER = true;
+  Diags.Report(diag::warn_knl_knm_target_supports_remove);
 } else if (Feature == "+avx512fp16") {
   HasAVX512FP16 = true;
   HasLegalHalfType = true;
 } else if (Feature == "+avx512pf") {
   HasAVX512PF = true;
+  Diags.Report(diag::warn_knl_knm_target_supports_remove);
 } else if (Feature == "+avx512dq") {
   HasAVX512DQ = true;
 } else if (Feature == "+avx512bitalg") {
@@ -358,6 +360,7 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
   HasPREFETCHI = true;
 } else if (Feature == "+prefetchwt1") {
   HasPREFETCHWT1 = true;
+  Diags.Report(diag::warn_knl_knm_target_supports_remove);
 } else if (Feature == "+clzero") {
   HasCLZERO = true;
 } else if (Feature == "+cldemote") {
diff --git a/clang/test/CodeGen/X86/avx512er-builtins.c 
b/clang/test/CodeGen/X86/avx512er-builtins.c
index ee31236a3c01aa..11ec6aabec1e3f 100644
--- a/clang/test/CodeGen/X86/avx512er-builtins.c
+++ b/clang/test/CodeGen/X86/avx512er-builtins.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -flax-vector-conversions=none -ffreestanding %s 
-triple=x86_64-apple-darwin -target-feature +avx512f -target-feature +avx512er 
-emit-llvm -o - -Wall -Werror | FileCheck %s
+// RUN: %clang_cc1 -flax-vector-conversions=none -ffreestanding %s 
-triple=x86_64-apple-darwin -target-feature +avx512f -target-feature +avx512er 
-emit-llvm -o - -Wall | FileCheck %s
 
 
 #include 
diff --git a/clang/test/CodeGen/X86/avx512pf-builtins.c 
b/clang/test/CodeGen/X86/avx512pf-builtins.c
index 4ca70f5787968b..3a117ed6a9460e 100644
--- a/clang/test/CodeGen/X86/avx512pf-builtins.c
+++ b/clang/test/CodeGen/X86/avx512pf-builtins.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -flax-vector-conversions=none -ffreestanding %s 
-triple=x86_64-apple-darwin -target-feature +avx512pf -emit-llvm -o - -Wall 
-Werror | FileCheck %s
+// RUN: %clang_cc1 -flax-vector-conversions=none -ffreestanding %s 
-triple=x86_64-apple-darwin -target-feature +avx512pf -emit-llvm -o - -Wall | 
FileCheck %s
 
 
 #include 
diff --git a/clang/test/Driver/cl-x86-flags.c b/clang/test/Driver/cl-x86-flags.c
index 51b16f0ce35463..ae35a312fe8a4b 100644
--- a/clang/test/Driver/cl-x86-flags.c
+++ b/clang/test/Driver/cl-x86-flags.c
@@ -69,7 +69,10 @@
 // RUN: %clang_cl -m32 -arch:avx2 --target=i386-pc-windows -### -- 2>&1 %s | 
FileCheck -check-prefix=avx2 %s
 // avx2: invalid /arch: argument
 
-// RUN: %clang_cl -m32 -arch:AVX512F --target=i386-pc-windows /c /Fo%t.obj 
-Xclang -verify -DTEST_32_ARCH_AVX512F -- %s
+// RUN: %clang_cl -m32 -arch:AVX512F --target=i386-pc-windows /c /Fo%t.obj 
-Xclang -verify=KNL1 -DTEST_32_ARCH_AVX512F -- %s
+// KNL1-warning@*:* {{KNL/KNM's feature support will be removed in LLVM 19.}}
+// KNL1-warning@*:* {{KNL/KNM's feature support will be removed in LLVM 19.}}
+// KNL1-warning@*:* {{KNL/KNM's feature support will be removed in LLVM 19.}}
 #if defined(TEST_32_ARCH_AVX512F)
 #if _M_IX86_FP !=

[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits

https://github.com/qmfrederik updated 
https://github.com/llvm/llvm-project/pull/77255

>From d5dec27c1b0eb1999a86035ac458da377132ec7d Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Thu, 4 Jan 2024 11:10:05 -0800
Subject: [PATCH] Objective C: use C++ exceptions on MinGW+GNUstep

The GNUstep Objective C runtime (libobjc2) is adding support for
MinGW.  This runtime uses C++ exceptions in that configuration.
---
 clang/lib/CodeGen/CGException.cpp |  9 +++-
 clang/lib/CodeGen/CGObjCGNU.cpp   | 35 
 .../test/CodeGenObjC/exceptions-personality.m | 53 +++
 clang/test/CodeGenObjC/personality.m  |  5 +-
 clang/test/CodeGenObjCXX/personality.mm   |  5 +-
 5 files changed, 92 insertions(+), 15 deletions(-)
 create mode 100644 clang/test/CodeGenObjC/exceptions-personality.m

diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 0d507da5c1ba92..cadd6f6ad75daa 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -156,7 +156,9 @@ static const EHPersonality &getObjCPersonality(const 
TargetInfo &Target,
   case ObjCRuntime::WatchOS:
 return EHPersonality::NeXT_ObjC;
   case ObjCRuntime::GNUstep:
-if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
+if (T.isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
   return EHPersonality::GNUstep_ObjC;
 [[fallthrough]];
   case ObjCRuntime::GCC:
@@ -210,7 +212,10 @@ static const EHPersonality &getObjCXXPersonality(const 
TargetInfo &Target,
 return getObjCPersonality(Target, L);
 
   case ObjCRuntime::GNUstep:
-return EHPersonality::GNU_ObjCXX;
+if (Target.getTriple().isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else
+  return EHPersonality::GNU_ObjCXX;
 
   // The GCC runtime's personality function inherently doesn't support
   // mixed EH.  Use the ObjC personality just to avoid returning null.
diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index 4ca1a8cce64d89..2b3a5da87fb778 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -819,10 +819,19 @@ class CGObjCGNUstep : public CGObjCGNU {
   SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  PtrToObjCSuperTy, SelectorTy);
   // If we're in ObjC++ mode, then we want to make
-  if (usesSEHExceptions) {
-  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
-  // void objc_exception_rethrow(void)
-  ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
+  if (CGM.getTarget().getTriple().isOSCygMing() &&
+  isRuntime(ObjCRuntime::GNUstep, 2)) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void *__cxa_begin_catch(void *e)
+EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
+// void __cxa_end_catch(void)
+ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
+// void objc_exception_rethrow(void*)
+ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
+  } else if (usesSEHExceptions) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void objc_exception_rethrow(void)
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
   } else if (CGM.getLangOpts().CPlusPlus) {
 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
 // void *__cxa_begin_catch(void *e)
@@ -2210,7 +2219,12 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 
   // void objc_exception_throw(id);
   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
-  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  if ((CGM.getTarget().getTriple().isOSCygMing() &&
+   isRuntime(ObjCRuntime::GNUstep, 2))) {
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, IdTy);
+  } else {
+ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  }
   // int objc_sync_enter(id);
   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
   // int objc_sync_exit(id);
@@ -2387,7 +2401,9 @@ llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
   if (usesSEHExceptions)
 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
 
-  if (!CGM.getLangOpts().CPlusPlus)
+  if (!CGM.getLangOpts().CPlusPlus &&
+  !(CGM.getTarget().getTriple().isOSCygMing() &&
+isRuntime(ObjCRuntime::GNUstep, 2)))
 return CGObjCGNU::GetEHType(T);
 
   // For Objective-C++, we want to provide the ability to catch both C++ and
@@ -3993,7 +4009,9 @@ void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
 ExceptionAsObject = CGF.ObjCEHValueStack.back();
 isRethrow = true;
   }
-  if (isRethrow && usesSEHExceptions) {
+  if (isRethrow &&
+  (usesSEHExceptions || (CGM.getTarget().getTriple().isOSCygMing() &&
+

[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits

https://github.com/qmfrederik updated 
https://github.com/llvm/llvm-project/pull/77255

>From 4212c79b5bb9168ae741b05b2c3388aa23e38693 Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Thu, 4 Jan 2024 11:10:05 -0800
Subject: [PATCH] Objective C: use C++ exceptions on MinGW+GNUstep

The GNUstep Objective C runtime (libobjc2) is adding support for
MinGW.  This runtime uses C++ exceptions in that configuration.
---
 clang/lib/CodeGen/CGException.cpp |  9 +++-
 clang/lib/CodeGen/CGObjCGNU.cpp   | 35 
 .../test/CodeGenObjC/exceptions-personality.m | 53 +++
 clang/test/CodeGenObjC/personality.m  |  5 +-
 clang/test/CodeGenObjCXX/personality.mm   |  5 +-
 5 files changed, 92 insertions(+), 15 deletions(-)
 create mode 100644 clang/test/CodeGenObjC/exceptions-personality.m

diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 0d507da5c1ba92..cadd6f6ad75daa 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -156,7 +156,9 @@ static const EHPersonality &getObjCPersonality(const 
TargetInfo &Target,
   case ObjCRuntime::WatchOS:
 return EHPersonality::NeXT_ObjC;
   case ObjCRuntime::GNUstep:
-if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
+if (T.isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
   return EHPersonality::GNUstep_ObjC;
 [[fallthrough]];
   case ObjCRuntime::GCC:
@@ -210,7 +212,10 @@ static const EHPersonality &getObjCXXPersonality(const 
TargetInfo &Target,
 return getObjCPersonality(Target, L);
 
   case ObjCRuntime::GNUstep:
-return EHPersonality::GNU_ObjCXX;
+if (Target.getTriple().isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else
+  return EHPersonality::GNU_ObjCXX;
 
   // The GCC runtime's personality function inherently doesn't support
   // mixed EH.  Use the ObjC personality just to avoid returning null.
diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index 4ca1a8cce64d89..2b3a5da87fb778 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -819,10 +819,19 @@ class CGObjCGNUstep : public CGObjCGNU {
   SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  PtrToObjCSuperTy, SelectorTy);
   // If we're in ObjC++ mode, then we want to make
-  if (usesSEHExceptions) {
-  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
-  // void objc_exception_rethrow(void)
-  ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
+  if (CGM.getTarget().getTriple().isOSCygMing() &&
+  isRuntime(ObjCRuntime::GNUstep, 2)) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void *__cxa_begin_catch(void *e)
+EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
+// void __cxa_end_catch(void)
+ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
+// void objc_exception_rethrow(void*)
+ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
+  } else if (usesSEHExceptions) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void objc_exception_rethrow(void)
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
   } else if (CGM.getLangOpts().CPlusPlus) {
 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
 // void *__cxa_begin_catch(void *e)
@@ -2210,7 +2219,12 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 
   // void objc_exception_throw(id);
   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
-  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  if ((CGM.getTarget().getTriple().isOSCygMing() &&
+   isRuntime(ObjCRuntime::GNUstep, 2))) {
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, IdTy);
+  } else {
+ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  }
   // int objc_sync_enter(id);
   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
   // int objc_sync_exit(id);
@@ -2387,7 +2401,9 @@ llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
   if (usesSEHExceptions)
 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
 
-  if (!CGM.getLangOpts().CPlusPlus)
+  if (!CGM.getLangOpts().CPlusPlus &&
+  !(CGM.getTarget().getTriple().isOSCygMing() &&
+isRuntime(ObjCRuntime::GNUstep, 2)))
 return CGObjCGNU::GetEHType(T);
 
   // For Objective-C++, we want to provide the ability to catch both C++ and
@@ -3993,7 +4009,9 @@ void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
 ExceptionAsObject = CGF.ObjCEHValueStack.back();
 isRethrow = true;
   }
-  if (isRethrow && usesSEHExceptions) {
+  if (isRethrow &&
+  (usesSEHExceptions || (CGM.getTarget().getTriple().isOSCygMing() &&
+

[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits

https://github.com/qmfrederik updated 
https://github.com/llvm/llvm-project/pull/77255

>From d3e6d552b2502765eff8faccd20b7566a9362491 Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Thu, 4 Jan 2024 11:10:05 -0800
Subject: [PATCH] Objective C: use C++ exceptions on MinGW+GNUstep

The GNUstep Objective C runtime (libobjc2) is adding support for
MinGW.  This runtime uses C++ exceptions in that configuration.
---
 clang/lib/CodeGen/CGException.cpp |  9 +++-
 clang/lib/CodeGen/CGObjCGNU.cpp   | 35 
 .../test/CodeGenObjC/exceptions-personality.m | 53 +++
 3 files changed, 86 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/CodeGenObjC/exceptions-personality.m

diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 0d507da5c1ba92..cadd6f6ad75daa 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -156,7 +156,9 @@ static const EHPersonality &getObjCPersonality(const 
TargetInfo &Target,
   case ObjCRuntime::WatchOS:
 return EHPersonality::NeXT_ObjC;
   case ObjCRuntime::GNUstep:
-if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
+if (T.isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
   return EHPersonality::GNUstep_ObjC;
 [[fallthrough]];
   case ObjCRuntime::GCC:
@@ -210,7 +212,10 @@ static const EHPersonality &getObjCXXPersonality(const 
TargetInfo &Target,
 return getObjCPersonality(Target, L);
 
   case ObjCRuntime::GNUstep:
-return EHPersonality::GNU_ObjCXX;
+if (Target.getTriple().isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else
+  return EHPersonality::GNU_ObjCXX;
 
   // The GCC runtime's personality function inherently doesn't support
   // mixed EH.  Use the ObjC personality just to avoid returning null.
diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index 4ca1a8cce64d89..2b3a5da87fb778 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -819,10 +819,19 @@ class CGObjCGNUstep : public CGObjCGNU {
   SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  PtrToObjCSuperTy, SelectorTy);
   // If we're in ObjC++ mode, then we want to make
-  if (usesSEHExceptions) {
-  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
-  // void objc_exception_rethrow(void)
-  ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
+  if (CGM.getTarget().getTriple().isOSCygMing() &&
+  isRuntime(ObjCRuntime::GNUstep, 2)) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void *__cxa_begin_catch(void *e)
+EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
+// void __cxa_end_catch(void)
+ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
+// void objc_exception_rethrow(void*)
+ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
+  } else if (usesSEHExceptions) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void objc_exception_rethrow(void)
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
   } else if (CGM.getLangOpts().CPlusPlus) {
 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
 // void *__cxa_begin_catch(void *e)
@@ -2210,7 +2219,12 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 
   // void objc_exception_throw(id);
   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
-  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  if ((CGM.getTarget().getTriple().isOSCygMing() &&
+   isRuntime(ObjCRuntime::GNUstep, 2))) {
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, IdTy);
+  } else {
+ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  }
   // int objc_sync_enter(id);
   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
   // int objc_sync_exit(id);
@@ -2387,7 +2401,9 @@ llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
   if (usesSEHExceptions)
 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
 
-  if (!CGM.getLangOpts().CPlusPlus)
+  if (!CGM.getLangOpts().CPlusPlus &&
+  !(CGM.getTarget().getTriple().isOSCygMing() &&
+isRuntime(ObjCRuntime::GNUstep, 2)))
 return CGObjCGNU::GetEHType(T);
 
   // For Objective-C++, we want to provide the ability to catch both C++ and
@@ -3993,7 +4009,9 @@ void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
 ExceptionAsObject = CGF.ObjCEHValueStack.back();
 isRethrow = true;
   }
-  if (isRethrow && usesSEHExceptions) {
+  if (isRethrow &&
+  (usesSEHExceptions || (CGM.getTarget().getTriple().isOSCygMing() &&
+ isRuntime(ObjCRuntime::GNUstep, 2 {
 // For SEH, ExceptionAsObject may be undef, beca

[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits


@@ -156,7 +154,11 @@ static const EHPersonality &getObjCPersonality(const 
TargetInfo &Target,
   case ObjCRuntime::WatchOS:
 return EHPersonality::NeXT_ObjC;
   case ObjCRuntime::GNUstep:
-if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
+if (T.isOSCygMing())

qmfrederik wrote:

OK - this broke some tests, so I'll revert that.

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


[clang] [clang] [MinGW] Don't look for a GCC in path if the install base has a proper mingw sysroot (PR #76949)

2024-01-07 Thread Martin Storsjö via cfe-commits

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


[clang] 4ca1b5e - [clang] [MinGW] Don't look for a GCC in path if the install base has a proper mingw sysroot (#76949)

2024-01-07 Thread via cfe-commits

Author: Martin Storsjö
Date: 2024-01-07T23:24:06+02:00
New Revision: 4ca1b5e094280ef1af40412e3cfcb62dc3cf15bc

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

LOG: [clang] [MinGW] Don't look for a GCC in path if the install base has a 
proper mingw sysroot (#76949)

This fixes uses of the MSYS2 clang64 environment compilers, if another
set of GCC based compilers are available further back in PATH (which may
be explicitly added, or inherited unintentionally from other software
installed).

(The issue in the clang64 environment can be worked around somewhat by
installing *-gcc-compat packages which present aliases named
-gcc within the clang64 environment as well.)

This fixes https://github.com/msys2/MINGW-packages/issues/11495 and
https://github.com/msys2/MINGW-packages/issues/19279.

Added: 


Modified: 
clang/lib/Driver/ToolChains/MinGW.cpp
clang/test/Driver/mingw-sysroot.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/MinGW.cpp 
b/clang/lib/Driver/ToolChains/MinGW.cpp
index 65512f16357d04..18fc9d4b6807e3 100644
--- a/clang/lib/Driver/ToolChains/MinGW.cpp
+++ b/clang/lib/Driver/ToolChains/MinGW.cpp
@@ -471,12 +471,23 @@ findClangRelativeSysroot(const Driver &D, const 
llvm::Triple &LiteralTriple,
   return make_error_code(std::errc::no_such_file_or_directory);
 }
 
+static bool looksLikeMinGWSysroot(const std::string &Directory) {
+  StringRef Sep = llvm::sys::path::get_separator();
+  if (!llvm::sys::fs::exists(Directory + Sep + "include" + Sep + "_mingw.h"))
+return false;
+  if (!llvm::sys::fs::exists(Directory + Sep + "lib" + Sep + "libkernel32.a"))
+return false;
+  return true;
+}
+
 toolchains::MinGW::MinGW(const Driver &D, const llvm::Triple &Triple,
  const ArgList &Args)
 : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
   RocmInstallation(D, Triple, Args) {
   getProgramPaths().push_back(getDriver().getInstalledDir());
 
+  std::string InstallBase =
+  std::string(llvm::sys::path::parent_path(getDriver().getInstalledDir()));
   // The sequence for detecting a sysroot here should be kept in sync with
   // the testTriple function below.
   llvm::Triple LiteralTriple = getLiteralTriple(D, getTriple());
@@ -487,13 +498,17 @@ toolchains::MinGW::MinGW(const Driver &D, const 
llvm::Triple &Triple,
   else if (llvm::ErrorOr TargetSubdir = findClangRelativeSysroot(
getDriver(), LiteralTriple, getTriple(), SubdirName))
 Base = std::string(llvm::sys::path::parent_path(TargetSubdir.get()));
+  // If the install base of Clang seems to have mingw sysroot files directly
+  // in the toplevel include and lib directories, use this as base instead of
+  // looking for a triple prefixed GCC in the path.
+  else if (looksLikeMinGWSysroot(InstallBase))
+Base = InstallBase;
   else if (llvm::ErrorOr GPPName =
findGcc(LiteralTriple, getTriple()))
 Base = std::string(llvm::sys::path::parent_path(
 llvm::sys::path::parent_path(GPPName.get(;
   else
-Base = std::string(
-llvm::sys::path::parent_path(getDriver().getInstalledDir()));
+Base = InstallBase;
 
   Base += llvm::sys::path::get_separator();
   findGccLibDir(LiteralTriple);
@@ -778,9 +793,15 @@ static bool testTriple(const Driver &D, const llvm::Triple 
&Triple,
   if (D.SysRoot.size())
 return true;
   llvm::Triple LiteralTriple = getLiteralTriple(D, Triple);
+  std::string InstallBase =
+  std::string(llvm::sys::path::parent_path(D.getInstalledDir()));
   if (llvm::ErrorOr TargetSubdir =
   findClangRelativeSysroot(D, LiteralTriple, Triple, SubdirName))
 return true;
+  // If the install base itself looks like a mingw sysroot, we'll use that
+  // - don't use any potentially unrelated gcc to influence what triple to use.
+  if (looksLikeMinGWSysroot(InstallBase))
+return false;
   if (llvm::ErrorOr GPPName = findGcc(LiteralTriple, Triple))
 return true;
   // If we neither found a colocated sysroot or a matching gcc executable,

diff  --git a/clang/test/Driver/mingw-sysroot.cpp 
b/clang/test/Driver/mingw-sysroot.cpp
index 911dab4927073d..50152b2ca210d2 100644
--- a/clang/test/Driver/mingw-sysroot.cpp
+++ b/clang/test/Driver/mingw-sysroot.cpp
@@ -14,6 +14,12 @@
 // RUN: ln -s %S/Inputs/mingw_ubuntu_posix_tree/usr/x86_64-w64-mingw32 
%T/testroot-clang/x86_64-w64-mingw32
 // RUN: ln -s %S/Inputs/mingw_arch_tree/usr/i686-w64-mingw32 
%T/testroot-clang/i686-w64-mingw32
 
+// RUN: rm -rf %T/testroot-clang-native
+// RUN: mkdir -p %T/testroot-clang-native/bin
+// RUN: ln -s %clang %T/testroot-clang-native/bin/clang
+// RUN: mkdir -p %T/testroot-clang-native/include/_mingw.h
+// RUN: mkdir -p %T/testroot-clang-native/lib/libkernel32.a
+
 // RUN: rm -rf %T/testroot

[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits

qmfrederik wrote:

/cc @davidchisnall 

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


[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits

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


[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits

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


[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits


@@ -156,7 +154,11 @@ static const EHPersonality &getObjCPersonality(const 
TargetInfo &Target,
   case ObjCRuntime::WatchOS:
 return EHPersonality::NeXT_ObjC;
   case ObjCRuntime::GNUstep:
-if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
+if (T.isOSCygMing())

qmfrederik wrote:

I moved the check for `isWindowsMSVCEnvironment` inside the `GNUstep` case, as 
on Windows we'll be using `MSVC_CxxFrameHandler3` when compiling with GNUstep + 
msvc; `GNU_CPlusPlus_SEH` when compiling with GNUstep + mingw and 
`GNU_ObjC_SEH` when compiling iwth GCC + mingw.

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


[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits

https://github.com/qmfrederik updated 
https://github.com/llvm/llvm-project/pull/77255

>From d04a41177e9c39799b73168d397dd87fb948caa1 Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Thu, 4 Jan 2024 11:10:05 -0800
Subject: [PATCH] Objective C: use C++ exceptions on MinGW+GNUstep

The GNUstep Objective C runtime (libobjc2) is adding support for
MinGW.  This runtime uses C++ exceptions in that configuration.
---
 clang/lib/CodeGen/CGException.cpp | 18 ---
 clang/lib/CodeGen/CGObjCGNU.cpp   | 35 
 .../test/CodeGenObjC/exceptions-personality.m | 53 +++
 3 files changed, 90 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/CodeGenObjC/exceptions-personality.m

diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 0d507da5c1ba92..939f7962dcc635 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -145,8 +145,6 @@ static const EHPersonality &getCPersonality(const 
TargetInfo &Target,
 static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
const LangOptions &L) {
   const llvm::Triple &T = Target.getTriple();
-  if (T.isWindowsMSVCEnvironment())
-return EHPersonality::MSVC_CxxFrameHandler3;
 
   switch (L.ObjCRuntime.getKind()) {
   case ObjCRuntime::FragileMacOSX:
@@ -156,7 +154,11 @@ static const EHPersonality &getObjCPersonality(const 
TargetInfo &Target,
   case ObjCRuntime::WatchOS:
 return EHPersonality::NeXT_ObjC;
   case ObjCRuntime::GNUstep:
-if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
+if (T.isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else if (T.isWindowsMSVCEnvironment())
+  return EHPersonality::MSVC_CxxFrameHandler3;
+else if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
   return EHPersonality::GNUstep_ObjC;
 [[fallthrough]];
   case ObjCRuntime::GCC:
@@ -192,9 +194,6 @@ static const EHPersonality &getCXXPersonality(const 
TargetInfo &Target,
 /// and Objective-C exceptions are being caught.
 static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
  const LangOptions &L) {
-  if (Target.getTriple().isWindowsMSVCEnvironment())
-return EHPersonality::MSVC_CxxFrameHandler3;
-
   switch (L.ObjCRuntime.getKind()) {
   // In the fragile ABI, just use C++ exception handling and hope
   // they're not doing crazy exception mixing.
@@ -210,7 +209,12 @@ static const EHPersonality &getObjCXXPersonality(const 
TargetInfo &Target,
 return getObjCPersonality(Target, L);
 
   case ObjCRuntime::GNUstep:
-return EHPersonality::GNU_ObjCXX;
+if (Target.getTriple().isWindowsMSVCEnvironment())
+  return EHPersonality::MSVC_CxxFrameHandler3;
+else if (Target.getTriple().isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else
+  return EHPersonality::GNU_ObjCXX;
 
   // The GCC runtime's personality function inherently doesn't support
   // mixed EH.  Use the ObjC personality just to avoid returning null.
diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index 4ca1a8cce64d89..2b3a5da87fb778 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -819,10 +819,19 @@ class CGObjCGNUstep : public CGObjCGNU {
   SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  PtrToObjCSuperTy, SelectorTy);
   // If we're in ObjC++ mode, then we want to make
-  if (usesSEHExceptions) {
-  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
-  // void objc_exception_rethrow(void)
-  ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
+  if (CGM.getTarget().getTriple().isOSCygMing() &&
+  isRuntime(ObjCRuntime::GNUstep, 2)) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void *__cxa_begin_catch(void *e)
+EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
+// void __cxa_end_catch(void)
+ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
+// void objc_exception_rethrow(void*)
+ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
+  } else if (usesSEHExceptions) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void objc_exception_rethrow(void)
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
   } else if (CGM.getLangOpts().CPlusPlus) {
 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
 // void *__cxa_begin_catch(void *e)
@@ -2210,7 +2219,12 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 
   // void objc_exception_throw(id);
   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
-  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  if ((CGM.getTarget().getTriple().isOSCygM

[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits

https://github.com/qmfrederik updated 
https://github.com/llvm/llvm-project/pull/77255

>From 62d7da8476b786f7950ea6bb8d6ac223fc6d0468 Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Thu, 4 Jan 2024 11:10:05 -0800
Subject: [PATCH] Objective C: use C++ exceptions on MinGW+GNUstep

The GNUstep Objective C runtime (libobjc2) is adding support for
MinGW.  This runtime uses C++ exceptions in that configuration.
---
 clang/lib/CodeGen/CGException.cpp | 18 ---
 clang/lib/CodeGen/CGObjCGNU.cpp   | 34 
 .../test/CodeGenObjC/exceptions-personality.m | 53 +++
 3 files changed, 89 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/CodeGenObjC/exceptions-personality.m

diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 0d507da5c1ba92..939f7962dcc635 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -145,8 +145,6 @@ static const EHPersonality &getCPersonality(const 
TargetInfo &Target,
 static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
const LangOptions &L) {
   const llvm::Triple &T = Target.getTriple();
-  if (T.isWindowsMSVCEnvironment())
-return EHPersonality::MSVC_CxxFrameHandler3;
 
   switch (L.ObjCRuntime.getKind()) {
   case ObjCRuntime::FragileMacOSX:
@@ -156,7 +154,11 @@ static const EHPersonality &getObjCPersonality(const 
TargetInfo &Target,
   case ObjCRuntime::WatchOS:
 return EHPersonality::NeXT_ObjC;
   case ObjCRuntime::GNUstep:
-if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
+if (T.isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else if (T.isWindowsMSVCEnvironment())
+  return EHPersonality::MSVC_CxxFrameHandler3;
+else if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
   return EHPersonality::GNUstep_ObjC;
 [[fallthrough]];
   case ObjCRuntime::GCC:
@@ -192,9 +194,6 @@ static const EHPersonality &getCXXPersonality(const 
TargetInfo &Target,
 /// and Objective-C exceptions are being caught.
 static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
  const LangOptions &L) {
-  if (Target.getTriple().isWindowsMSVCEnvironment())
-return EHPersonality::MSVC_CxxFrameHandler3;
-
   switch (L.ObjCRuntime.getKind()) {
   // In the fragile ABI, just use C++ exception handling and hope
   // they're not doing crazy exception mixing.
@@ -210,7 +209,12 @@ static const EHPersonality &getObjCXXPersonality(const 
TargetInfo &Target,
 return getObjCPersonality(Target, L);
 
   case ObjCRuntime::GNUstep:
-return EHPersonality::GNU_ObjCXX;
+if (Target.getTriple().isWindowsMSVCEnvironment())
+  return EHPersonality::MSVC_CxxFrameHandler3;
+else if (Target.getTriple().isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else
+  return EHPersonality::GNU_ObjCXX;
 
   // The GCC runtime's personality function inherently doesn't support
   // mixed EH.  Use the ObjC personality just to avoid returning null.
diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index 4ca1a8cce64d89..3165fabf00a2e7 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -819,10 +819,19 @@ class CGObjCGNUstep : public CGObjCGNU {
   SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  PtrToObjCSuperTy, SelectorTy);
   // If we're in ObjC++ mode, then we want to make
-  if (usesSEHExceptions) {
-  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
-  // void objc_exception_rethrow(void)
-  ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
+  if (CGM.getTarget().getTriple().isOSCygMing() &&
+  isRuntime(ObjCRuntime::GNUstep, 2)) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void *__cxa_begin_catch(void *e)
+EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
+// void __cxa_end_catch(void)
+ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
+// void objc_exception_rethrow(void*)
+ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
+  } else if (usesSEHExceptions) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void objc_exception_rethrow(void)
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
   } else if (CGM.getLangOpts().CPlusPlus) {
 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
 // void *__cxa_begin_catch(void *e)
@@ -2210,7 +2219,11 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 
   // void objc_exception_throw(id);
   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
-  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  if ((CGM.getTarget().getTriple().isOSCygM

[clang] [llvm] [lld] [clang-tools-extra] [lldb] [mlir] [libc] [compiler-rt] [libcxx] Fix Multiple Build Errors on different platforms (PR #77216)

2024-01-07 Thread via cfe-commits

https://github.com/trcrsired updated 
https://github.com/llvm/llvm-project/pull/77216

>From a1156a564c798192cb7608e28ce9b9ed846a8b1c Mon Sep 17 00:00:00 2001
From: trcrsired 
Date: Sat, 6 Jan 2024 20:21:06 -0500
Subject: [PATCH 1/2] Fix Multiple Build Errors on different platforms

Particularly for canadian compilation
---
 .../pseudo/include/CMakeLists.txt |  12 +-
 clang/lib/Tooling/CMakeLists.txt  |  10 +-
 compiler-rt/lib/builtins/fp_compare_impl.inc  |   3 +
 lldb/source/Host/android/HostInfoAndroid.cpp  |   4 +
 lldb/source/Host/android/LibcGlue.cpp |   2 +
 llvm/include/llvm/TargetParser/Triple.h   | 287 +++---
 llvm/lib/Support/Unix/Unix.h  |  17 +-
 mlir/lib/ExecutionEngine/CRunnerUtils.cpp |   4 +-
 8 files changed, 147 insertions(+), 192 deletions(-)

diff --git a/clang-tools-extra/pseudo/include/CMakeLists.txt 
b/clang-tools-extra/pseudo/include/CMakeLists.txt
index 2334cfa12e3376..605f17dd4591a0 100644
--- a/clang-tools-extra/pseudo/include/CMakeLists.txt
+++ b/clang-tools-extra/pseudo/include/CMakeLists.txt
@@ -3,10 +3,18 @@ set(cxx_bnf ${CMAKE_CURRENT_SOURCE_DIR}/../lib/cxx/cxx.bnf)
 
 setup_host_tool(clang-pseudo-gen CLANG_PSEUDO_GEN pseudo_gen pseudo_gen_target)
 
+if(NOT DEFINED CLANG_PSEUDO_GEN)
+   if(DEFINED LLVM_NATIVE_TOOL_DIR AND NOT LLVM_NATIVE_TOOL_DIR STREQUAL "")
+  set(CLANG_PSEUDO_GEN "${LLVM_NATIVE_TOOL_DIR}/clang_pseudo_gen")
+   else()
+  set(CLANG_PSEUDO_GEN "${pseudo_gen}")
+   endif()
+endif()
+
 # Generate inc files.
 set(cxx_symbols_inc ${CMAKE_CURRENT_BINARY_DIR}/CXXSymbols.inc)
 add_custom_command(OUTPUT ${cxx_symbols_inc}
-   COMMAND "${pseudo_gen}"
+   COMMAND "${CLANG_PSEUDO_GEN}"
  --grammar ${cxx_bnf}
  --emit-symbol-list
  -o ${cxx_symbols_inc}
@@ -16,7 +24,7 @@ add_custom_command(OUTPUT ${cxx_symbols_inc}
 
 set(cxx_bnf_inc ${CMAKE_CURRENT_BINARY_DIR}/CXXBNF.inc)
 add_custom_command(OUTPUT ${cxx_bnf_inc}
-   COMMAND "${pseudo_gen}"
+   COMMAND "${CLANG_PSEUDO_GEN}"
  --grammar ${cxx_bnf}
  --emit-grammar-content
  -o ${cxx_bnf_inc}
diff --git a/clang/lib/Tooling/CMakeLists.txt b/clang/lib/Tooling/CMakeLists.txt
index aff39e4de13c0b..1510f5fb8a0810 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -53,6 +53,14 @@ else()
 list(APPEND implicitDirs -I ${implicitDir})
   endforeach()
 
+  if(NOT DEFINED CLANG_AST_DUMP)
+if(DEFINED LLVM_NATIVE_TOOL_DIR AND NOT LLVM_NATIVE_TOOL_DIR STREQUAL "")
+  set(CLANG_AST_DUMP ${LLVM_NATIVE_TOOL_DIR}/clang-ast-dump)
+else()
+  set(CLANG_AST_DUMP $)
+endif()
+  endif()
+
   include(GetClangResourceDir)
   get_clang_resource_dir(resource_dir PREFIX ${LLVM_BINARY_DIR})
   add_custom_command(
@@ -60,7 +68,7 @@ else()
   OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/ASTNodeAPI.json
   DEPENDS clang-ast-dump clang-resource-headers
   COMMAND
-  $
+  ${CLANG_AST_DUMP}
 # Skip this in debug mode because parsing AST.h is too slow
 --skip-processing=${skip_expensive_processing}
 -I ${resource_dir}/include
diff --git a/compiler-rt/lib/builtins/fp_compare_impl.inc 
b/compiler-rt/lib/builtins/fp_compare_impl.inc
index a9a4f6fbf5dfe4..b2ebd0737df033 100644
--- a/compiler-rt/lib/builtins/fp_compare_impl.inc
+++ b/compiler-rt/lib/builtins/fp_compare_impl.inc
@@ -18,6 +18,9 @@ typedef int CMP_RESULT;
 #elif __SIZEOF_POINTER__ == 8 && __SIZEOF_LONG__ == 4
 // LLP64 ABIs use long long instead of long.
 typedef long long CMP_RESULT;
+#elif defined(__wasm64__)
+// GCC uses int as CMP_RESULT
+typedef int CMP_RESULT;
 #elif __AVR__
 // AVR uses a single byte for the return value.
 typedef char CMP_RESULT;
diff --git a/lldb/source/Host/android/HostInfoAndroid.cpp 
b/lldb/source/Host/android/HostInfoAndroid.cpp
index 68440e016afe4b..5ba2f0e24a8d24 100644
--- a/lldb/source/Host/android/HostInfoAndroid.cpp
+++ b/lldb/source/Host/android/HostInfoAndroid.cpp
@@ -6,6 +6,8 @@
 //
 
//===--===//
 
+#ifdef __ANDROID__
+
 #include "lldb/Host/android/HostInfoAndroid.h"
 #include "lldb/Host/FileSystem.h"
 #include "lldb/Host/linux/HostInfoLinux.h"
@@ -92,3 +94,5 @@ bool HostInfoAndroid::ComputeTempFileBaseDirectory(FileSpec 
&file_spec) {
 
   return FileSystem::Instance().Exists(file_spec);
 }
+
+#endif
diff --git a/lldb/source/Host/android/LibcGlue.cpp 
b/lldb/source/Host/android/LibcGlue.cpp
index 877d735823feee..82b257719c2c8a 100644
--- a/lldb/source/Host/android/LibcGlue.cpp
+++ b/lldb/source/Host/android/LibcGlue.cpp
@@ -8,6 +8,7 @@
 
 // This files adds functions missing from libc on earlier versions of Android
 
+#ifdef __ANDROID__
 #include 
 
 #include 
@@ -26,3 +27,4 @@ time_t timegm(struct tm *t) { return (time_t)timegm64(t); }
 int posix_openpt(int flags) { return open("/dev/ptmx", flags); }
 
 #endif
+#endif
diff --git a/llvm/include/llvm/TargetParser/Triple.h 
b/llvm/include/llvm/TargetP

[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 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 6e1ecd100d7663a91135b1cf6c4a603681b7385b 
4cbc22e9b7c53547b97c666b24f191b25ae8866f -- clang/lib/CodeGen/CGException.cpp 
clang/lib/CodeGen/CGObjCGNU.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index 5ace469c92..2b3a5da87f 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -819,7 +819,8 @@ class CGObjCGNUstep : public CGObjCGNU {
   SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  PtrToObjCSuperTy, SelectorTy);
   // If we're in ObjC++ mode, then we want to make
-  if (CGM.getTarget().getTriple().isOSCygMing() && 
isRuntime(ObjCRuntime::GNUstep, 2)) {
+  if (CGM.getTarget().getTriple().isOSCygMing() &&
+  isRuntime(ObjCRuntime::GNUstep, 2)) {
 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
 // void *__cxa_begin_catch(void *e)
 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
@@ -828,9 +829,9 @@ class CGObjCGNUstep : public CGObjCGNU {
 // void objc_exception_rethrow(void*)
 ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
   } else if (usesSEHExceptions) {
-  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
-  // void objc_exception_rethrow(void)
-  ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void objc_exception_rethrow(void)
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
   } else if (CGM.getLangOpts().CPlusPlus) {
 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
 // void *__cxa_begin_catch(void *e)
@@ -2218,7 +2219,8 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 
   // void objc_exception_throw(id);
   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
-  if ((CGM.getTarget().getTriple().isOSCygMing() && 
isRuntime(ObjCRuntime::GNUstep, 2))) {
+  if ((CGM.getTarget().getTriple().isOSCygMing() &&
+   isRuntime(ObjCRuntime::GNUstep, 2))) {
 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, IdTy);
   } else {
 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
@@ -2399,7 +2401,9 @@ llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
   if (usesSEHExceptions)
 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
 
-  if (!CGM.getLangOpts().CPlusPlus && 
!(CGM.getTarget().getTriple().isOSCygMing() && isRuntime(ObjCRuntime::GNUstep, 
2)))
+  if (!CGM.getLangOpts().CPlusPlus &&
+  !(CGM.getTarget().getTriple().isOSCygMing() &&
+isRuntime(ObjCRuntime::GNUstep, 2)))
 return CGObjCGNU::GetEHType(T);
 
   // For Objective-C++, we want to provide the ability to catch both C++ and
@@ -4005,7 +4009,9 @@ void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
 ExceptionAsObject = CGF.ObjCEHValueStack.back();
 isRethrow = true;
   }
-  if (isRethrow && (usesSEHExceptions || 
(CGM.getTarget().getTriple().isOSCygMing() && isRuntime(ObjCRuntime::GNUstep, 
2 {
+  if (isRethrow &&
+  (usesSEHExceptions || (CGM.getTarget().getTriple().isOSCygMing() &&
+ isRuntime(ObjCRuntime::GNUstep, 2 {
 // For SEH, ExceptionAsObject may be undef, because the catch handler is
 // not passed it for catchalls and so it is not visible to the catch
 // funclet.  The real thrown object will still be live on the stack at this
@@ -4015,8 +4021,7 @@ void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
 // argument.
 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
 Throw->setDoesNotReturn();
-  }
-  else {
+  } else {
 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
 llvm::CallBase *Throw =
 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);

``




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


[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Frederik Carlier (qmfrederik)


Changes

The GNUstep Objective C runtime (libobjc2) is adding support for MinGW.  This 
runtime uses C++ exceptions in that configuration.

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


3 Files Affected:

- (modified) clang/lib/CodeGen/CGException.cpp (+11-7) 
- (modified) clang/lib/CodeGen/CGObjCGNU.cpp (+16-4) 
- (added) clang/test/CodeGenObjC/exceptions-personality.m (+53) 


``diff
diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 0d507da5c1ba92..939f7962dcc635 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -145,8 +145,6 @@ static const EHPersonality &getCPersonality(const 
TargetInfo &Target,
 static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
const LangOptions &L) {
   const llvm::Triple &T = Target.getTriple();
-  if (T.isWindowsMSVCEnvironment())
-return EHPersonality::MSVC_CxxFrameHandler3;
 
   switch (L.ObjCRuntime.getKind()) {
   case ObjCRuntime::FragileMacOSX:
@@ -156,7 +154,11 @@ static const EHPersonality &getObjCPersonality(const 
TargetInfo &Target,
   case ObjCRuntime::WatchOS:
 return EHPersonality::NeXT_ObjC;
   case ObjCRuntime::GNUstep:
-if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
+if (T.isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else if (T.isWindowsMSVCEnvironment())
+  return EHPersonality::MSVC_CxxFrameHandler3;
+else if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
   return EHPersonality::GNUstep_ObjC;
 [[fallthrough]];
   case ObjCRuntime::GCC:
@@ -192,9 +194,6 @@ static const EHPersonality &getCXXPersonality(const 
TargetInfo &Target,
 /// and Objective-C exceptions are being caught.
 static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
  const LangOptions &L) {
-  if (Target.getTriple().isWindowsMSVCEnvironment())
-return EHPersonality::MSVC_CxxFrameHandler3;
-
   switch (L.ObjCRuntime.getKind()) {
   // In the fragile ABI, just use C++ exception handling and hope
   // they're not doing crazy exception mixing.
@@ -210,7 +209,12 @@ static const EHPersonality &getObjCXXPersonality(const 
TargetInfo &Target,
 return getObjCPersonality(Target, L);
 
   case ObjCRuntime::GNUstep:
-return EHPersonality::GNU_ObjCXX;
+if (Target.getTriple().isWindowsMSVCEnvironment())
+  return EHPersonality::MSVC_CxxFrameHandler3;
+else if (Target.getTriple().isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else
+  return EHPersonality::GNU_ObjCXX;
 
   // The GCC runtime's personality function inherently doesn't support
   // mixed EH.  Use the ObjC personality just to avoid returning null.
diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index 4ca1a8cce64d89..5ace469c927045 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -819,7 +819,15 @@ class CGObjCGNUstep : public CGObjCGNU {
   SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  PtrToObjCSuperTy, SelectorTy);
   // If we're in ObjC++ mode, then we want to make
-  if (usesSEHExceptions) {
+  if (CGM.getTarget().getTriple().isOSCygMing() && 
isRuntime(ObjCRuntime::GNUstep, 2)) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void *__cxa_begin_catch(void *e)
+EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
+// void __cxa_end_catch(void)
+ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
+// void objc_exception_rethrow(void*)
+ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
+  } else if (usesSEHExceptions) {
   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
   // void objc_exception_rethrow(void)
   ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
@@ -2210,7 +2218,11 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 
   // void objc_exception_throw(id);
   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
-  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  if ((CGM.getTarget().getTriple().isOSCygMing() && 
isRuntime(ObjCRuntime::GNUstep, 2))) {
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, IdTy);
+  } else {
+ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  }
   // int objc_sync_enter(id);
   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
   // int objc_sync_exit(id);
@@ -2387,7 +2399,7 @@ llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
   if (usesSEHExceptions)
 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
 
-  if (!CGM.getLangOpts().CPlusPlus)
+  if (!CGM.getLangOpts().CPlusPlus && 
!(

[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread via cfe-commits

github-actions[bot] wrote:

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-07 Thread Frederik Carlier via cfe-commits

https://github.com/qmfrederik created 
https://github.com/llvm/llvm-project/pull/77255

The GNUstep Objective C runtime (libobjc2) is adding support for MinGW.  This 
runtime uses C++ exceptions in that configuration.

>From 4cbc22e9b7c53547b97c666b24f191b25ae8866f Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Thu, 4 Jan 2024 11:10:05 -0800
Subject: [PATCH] Objective C: use C++ exceptions on MinGW+GNUstep

The GNUstep Objective C runtime (libobjc2) is adding support for
MinGW.  This runtime uses C++ exceptions in that configuration.
---
 clang/lib/CodeGen/CGException.cpp | 18 ---
 clang/lib/CodeGen/CGObjCGNU.cpp   | 20 +--
 .../test/CodeGenObjC/exceptions-personality.m | 53 +++
 3 files changed, 80 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/CodeGenObjC/exceptions-personality.m

diff --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 0d507da5c1ba92..939f7962dcc635 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -145,8 +145,6 @@ static const EHPersonality &getCPersonality(const 
TargetInfo &Target,
 static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
const LangOptions &L) {
   const llvm::Triple &T = Target.getTriple();
-  if (T.isWindowsMSVCEnvironment())
-return EHPersonality::MSVC_CxxFrameHandler3;
 
   switch (L.ObjCRuntime.getKind()) {
   case ObjCRuntime::FragileMacOSX:
@@ -156,7 +154,11 @@ static const EHPersonality &getObjCPersonality(const 
TargetInfo &Target,
   case ObjCRuntime::WatchOS:
 return EHPersonality::NeXT_ObjC;
   case ObjCRuntime::GNUstep:
-if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
+if (T.isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else if (T.isWindowsMSVCEnvironment())
+  return EHPersonality::MSVC_CxxFrameHandler3;
+else if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
   return EHPersonality::GNUstep_ObjC;
 [[fallthrough]];
   case ObjCRuntime::GCC:
@@ -192,9 +194,6 @@ static const EHPersonality &getCXXPersonality(const 
TargetInfo &Target,
 /// and Objective-C exceptions are being caught.
 static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
  const LangOptions &L) {
-  if (Target.getTriple().isWindowsMSVCEnvironment())
-return EHPersonality::MSVC_CxxFrameHandler3;
-
   switch (L.ObjCRuntime.getKind()) {
   // In the fragile ABI, just use C++ exception handling and hope
   // they're not doing crazy exception mixing.
@@ -210,7 +209,12 @@ static const EHPersonality &getObjCXXPersonality(const 
TargetInfo &Target,
 return getObjCPersonality(Target, L);
 
   case ObjCRuntime::GNUstep:
-return EHPersonality::GNU_ObjCXX;
+if (Target.getTriple().isWindowsMSVCEnvironment())
+  return EHPersonality::MSVC_CxxFrameHandler3;
+else if (Target.getTriple().isOSCygMing())
+  return EHPersonality::GNU_CPlusPlus_SEH;
+else
+  return EHPersonality::GNU_ObjCXX;
 
   // The GCC runtime's personality function inherently doesn't support
   // mixed EH.  Use the ObjC personality just to avoid returning null.
diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index 4ca1a8cce64d89..5ace469c927045 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -819,7 +819,15 @@ class CGObjCGNUstep : public CGObjCGNU {
   SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  PtrToObjCSuperTy, SelectorTy);
   // If we're in ObjC++ mode, then we want to make
-  if (usesSEHExceptions) {
+  if (CGM.getTarget().getTriple().isOSCygMing() && 
isRuntime(ObjCRuntime::GNUstep, 2)) {
+llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
+// void *__cxa_begin_catch(void *e)
+EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
+// void __cxa_end_catch(void)
+ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
+// void objc_exception_rethrow(void*)
+ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
+  } else if (usesSEHExceptions) {
   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
   // void objc_exception_rethrow(void)
   ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
@@ -2210,7 +2218,11 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 
   // void objc_exception_throw(id);
   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
-  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  if ((CGM.getTarget().getTriple().isOSCygMing() && 
isRuntime(ObjCRuntime::GNUstep, 2))) {
+ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, IdTy);
+  } else {
+ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
+  }
   // int o

[llvm] [lld] [clang] [SHT_LLVM_BB_ADDR_MAP] Allow basic-block-sections and labels be used together by decoupling the handling of the two features. (PR #74128)

2024-01-07 Thread Micah Weston via cfe-commits


@@ -719,60 +730,83 @@ decodeBBAddrMapImpl(const ELFFile &EF,
   Feature = Data.getU8(Cur); // Feature byte
   if (!Cur)
 break;
-  auto FeatEnableOrErr = PGOAnalysisMap::Features::decode(Feature);
+  auto FeatEnableOrErr = BBAddrMap::Features::decode(Feature);
   if (!FeatEnableOrErr)
 return FeatEnableOrErr.takeError();
-  FeatEnable =
-  FeatEnableOrErr ? *FeatEnableOrErr : PGOAnalysisMap::Features{};
+  FeatEnable = FeatEnableOrErr ? *FeatEnableOrErr : BBAddrMap::Features{};

red1bluelost wrote:

(Nit) I think this can just always assume true given that we return on error in 
the line before. (woops, I think I wrote this wrong)

```suggestion
  FeatEnable = *FeatEnableOrErr;
```

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


[llvm] [clang] [lld] [SHT_LLVM_BB_ADDR_MAP] Allow basic-block-sections and labels be used together by decoupling the handling of the two features. (PR #74128)

2024-01-07 Thread Micah Weston via cfe-commits


@@ -0,0 +1,89 @@
+; COM: Emitting basic-block-address-map when machine function splitting is 
enabled.
+; RUN: llc < %s -mtriple=x86_64 -function-sections -split-machine-functions 
-basic-block-address-map | FileCheck %s --check-prefixes=CHECK,BASIC
+
+; COM: Emitting basic-block-address-map with PGO analysis with machine 
function splitting enabled.
+; RUN: llc < %s -mtriple=x86_64 -function-sections -split-machine-functions 
-basic-block-address-map -pgo-analysis-map=func-entry-count,bb-freq,br-prob | 
FileCheck %s --check-prefixes=CHECK,PGO
+
+define void @foo(i1 zeroext %0) nounwind !prof !14 {
+  br i1 %0, label %2, label %4, !prof !15
+
+2:; preds = %1
+  %3 = call i32 @bar()
+  br label %6
+
+4:; preds = %1
+  %5 = call i32 @baz()
+  br label %6
+
+6:; preds = %4, %2
+  %7 = tail call i32 @qux()
+  ret void
+}
+
+declare i32 @bar()
+declare i32 @baz()
+declare i32 @qux()
+
+!llvm.module.flags = !{!0}
+!0 = !{i32 1, !"ProfileSummary", !1}
+!1 = !{!2, !3, !4, !5, !6, !7, !8, !9}
+!2 = !{!"ProfileFormat", !"InstrProf"}
+!3 = !{!"TotalCount", i64 1}
+!4 = !{!"MaxCount", i64 10}
+!5 = !{!"MaxInternalCount", i64 1}
+!6 = !{!"MaxFunctionCount", i64 1000}
+!7 = !{!"NumCounts", i64 3}
+!8 = !{!"NumFunctions", i64 5}
+!9 = !{!"DetailedSummary", !10}
+!10 = !{!11, !12, !13}
+!11 = !{i32 1, i64 100, i32 1}
+!12 = !{i32 00, i64 100, i32 1}
+!13 = !{i32 99, i64 1, i32 2}
+!14 = !{!"function_entry_count", i64 7000}
+!15 = !{!"branch_weights", i32 7000, i32 0}
+
+; CHECK:  .section .text.hot.foo,"ax",@progbits
+; CHECK-LABEL:  foo:
+; CHECK-LABEL:  .Lfunc_begin0:
+; CHECK-LABEL:  .LBB_END0_0:
+; CHECK-LABEL:  .LBB0_1:
+; CHECK-LABEL:  .LBB_END0_1:
+; CHECK:  .section .text.split.foo,"ax",@progbits
+; CHECK-LABEL:  foo.cold:
+; CHECK-LABEL:  .LBB_END0_2:
+; CHECK-LABEL:  .Lfunc_end0:
+
+; CHECK:.section
.llvm_bb_addr_map,"o",@llvm_bb_addr_map,.text.hot.foo
+; CHECK-NEXT:   .byte   2   # version
+; BASIC-NEXT:   .byte   8   # feature
+; PGO-NEXT: .byte   15  # feature
+; CHECK-NEXT:   .byte   2   # number of basic block ranges
+; CHECK-NEXT:   .quad   .Lfunc_begin0   # base address
+; CHECK-NEXT:   .byte   2   # number of basic blocks
+; CHECK-NEXT:   .byte   0   # BB id
+; CHECK-NEXT:   .uleb128 .Lfunc_begin0-.Lfunc_begin0
+; CHECK-NEXT:   .uleb128 .LBB_END0_0-.Lfunc_begin0
+; CHECK-NEXT:   .byte   8
+; CHECK-NEXT:   .byte   1   # BB id
+; CHECK-NEXT:   .uleb128 .LBB0_1-.LBB_END0_0
+; CHECK-NEXT:   .uleb128 .LBB_END0_1-.LBB0_1
+; CHECK-NEXT:   .byte   3
+; CHECK-NEXT:   .quad   foo.cold# base address
+; CHECK-NEXT:   .byte   1   # number of basic blocks
+; CHECK-NEXT:   .byte   2   # BB id
+; CHECK-NEXT:   .uleb128 foo.cold-foo.cold
+; CHECK-NEXT:   .uleb128 .LBB_END0_2-foo.cold
+; CHECK-NEXT:   .byte   3
+
+;; PGO Analysis Map

red1bluelost wrote:

Thanks for including a test with PGO Analysis Map :)

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


[lld] [clang] [llvm] [SHT_LLVM_BB_ADDR_MAP] Allow basic-block-sections and labels be used together by decoupling the handling of the two features. (PR #74128)

2024-01-07 Thread Micah Weston via cfe-commits

https://github.com/red1bluelost commented:

Overall looks good to me so far, just two minor things and the merge conflict.

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


[lld] [clang] [llvm] [SHT_LLVM_BB_ADDR_MAP] Allow basic-block-sections and labels be used together by decoupling the handling of the two features. (PR #74128)

2024-01-07 Thread Micah Weston via cfe-commits

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


[llvm] [clang] [lld] [SHT_LLVM_BB_ADDR_MAP] Allow basic-block-sections and labels be used together by decoupling the handling of the two features. (PR #74128)

2024-01-07 Thread Micah Weston via cfe-commits


@@ -719,60 +730,83 @@ decodeBBAddrMapImpl(const ELFFile &EF,
   Feature = Data.getU8(Cur); // Feature byte
   if (!Cur)
 break;
-  auto FeatEnableOrErr = PGOAnalysisMap::Features::decode(Feature);
+  auto FeatEnableOrErr = BBAddrMap::Features::decode(Feature);
   if (!FeatEnableOrErr)
 return FeatEnableOrErr.takeError();
-  FeatEnable =
-  FeatEnableOrErr ? *FeatEnableOrErr : PGOAnalysisMap::Features{};
+  FeatEnable = FeatEnableOrErr ? *FeatEnableOrErr : BBAddrMap::Features{};
   if (Feature != 0 && Version < 2 && Cur)
 return createError(
 "version should be >= 2 for SHT_LLVM_BB_ADDR_MAP when "
 "PGO features are enabled: version = " +
 Twine(static_cast(Version)) +
 " feature = " + Twine(static_cast(Feature)));
 }
-uint64_t SectionOffset = Cur.tell();
-auto Address =
-static_cast::uintX_t>(Data.getAddress(Cur));
-if (!Cur)
-  return Cur.takeError();
-if (IsRelocatable) {
-  assert(Address == 0);
-  auto FOTIterator = FunctionOffsetTranslations.find(SectionOffset);
-  if (FOTIterator == FunctionOffsetTranslations.end()) {
-return createError("failed to get relocation data for offset: " +
-   Twine::utohexstr(SectionOffset) + " in section " +
-   describe(EF, Sec));
-  }
-  Address = FOTIterator->second;
-}
-uint32_t NumBlocks = readULEB128As(Data, Cur, ULEBSizeErr);
-
+uint32_t NumBlocksInBBRange = 0;
+uint32_t NumBBRanges = 1;
+typename ELFFile::uintX_t RangeBaseAddress = 0;
 std::vector BBEntries;
-uint32_t PrevBBEndOffset = 0;
-for (uint32_t BlockIndex = 0;
- !MetadataDecodeErr && !ULEBSizeErr && Cur && (BlockIndex < NumBlocks);
- ++BlockIndex) {
-  uint32_t ID = Version >= 2
-? readULEB128As(Data, Cur, ULEBSizeErr)
-: BlockIndex;
-  uint32_t Offset = readULEB128As(Data, Cur, ULEBSizeErr);
-  uint32_t Size = readULEB128As(Data, Cur, ULEBSizeErr);
-  uint32_t MD = readULEB128As(Data, Cur, ULEBSizeErr);
-  if (Version >= 1) {
-// Offset is calculated relative to the end of the previous BB.
-Offset += PrevBBEndOffset;
-PrevBBEndOffset = Offset + Size;
+if (FeatEnable.MultiBBRange) {
+  NumBBRanges = readULEB128As(Data, Cur, ULEBSizeErr);
+} else {
+  uint64_t RelocationOffsetInSection = Cur.tell();
+  RangeBaseAddress =
+  static_cast::uintX_t>(Data.getAddress(Cur));
+  if (!Cur)
+return Cur.takeError();
+  if (IsRelocatable) {
+Expected AddressOrErr =
+GetAddressForRelocation(RelocationOffsetInSection);
+if (!AddressOrErr)
+  return AddressOrErr.takeError();
+RangeBaseAddress = *AddressOrErr;
   }
-  Expected MetadataOrErr =
-  BBAddrMap::BBEntry::Metadata::decode(MD);
-  if (!MetadataOrErr) {
-MetadataDecodeErr = MetadataOrErr.takeError();
-break;
+  NumBlocksInBBRange = readULEB128As(Data, Cur, ULEBSizeErr);
+}
+std::vector BBRangeEntries;
+uint32_t TotalNumBlocks = 0;
+for (uint32_t BBRangeIndex = 0; BBRangeIndex < NumBBRanges;
+ ++BBRangeIndex) {
+  uint32_t PrevBBEndOffset = 0;
+  if (FeatEnable.MultiBBRange) {
+uint64_t RelocationOffsetInSection = Cur.tell();
+RangeBaseAddress =
+static_cast::uintX_t>(Data.getAddress(Cur));
+if (IsRelocatable) {
+  assert(RangeBaseAddress == 0);
+  Expected AddressOrErr =
+  GetAddressForRelocation(RelocationOffsetInSection);
+  if (!AddressOrErr)
+return AddressOrErr.takeError();
+  RangeBaseAddress = *AddressOrErr;
+}
+NumBlocksInBBRange = readULEB128As(Data, Cur, ULEBSizeErr);

red1bluelost wrote:

This seems nearly the same as at line 751. The differences seem to be this has 
an assert on the RangeBaseAddress and 751 short circuits on Cur. If it is 
possible, could it be moved into a lambda so that this and 751 can just call 
the lambda?

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


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-01-07 Thread Vlad Serebrennikov via cfe-commits


@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -fsyntax-only -Wextra -verify
+
+
+int t(int array[static 12]);
+int u(int i);
+const int v(int i); /* expected-warning {{'const' type qualifier on return 
type has no effec}} */
+int x(long);
+
+typedef int (f1)(long);
+typedef int (f2)(void*);
+typedef int (f3)();
+typedef void (f4)();
+typedef void (f5)(void);
+typedef int (f6)(long, int);
+typedef int (f7)(long,...);
+typedef int (f8)(int *);
+typedef int (f9)(const int);
+typedef int (f10)(int);
+
+f1 *a;
+f2 *b;
+f3 *c;
+f4 *d;
+f5 *e;
+f6 *f;
+f7 *g;
+f8 *h;
+f9 *i;
+f10 *j;
+
+void foo(void) {
+  a = (f1 *)x;
+  b = (f2 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f2 *' (aka 
'int (*)(void *)') converts to incompatible function type}} */
+  c = (f3 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f3 *' (aka 
'int (*)()') converts to incompatible function type}} */
+  d = (f4 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f4 *' (aka 
'void (*)()') converts to incompatible function type}} */
+  e = (f5 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f5 *' (aka 
'void (*)(void)') converts to incompatible function type}} */
+  f = (f6 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f6 *' (aka 
'int (*)(long, int)') converts to incompatible function type}} */
+  g = (f7 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f7 *' (aka 
'int (*)(long, ...)') converts to incompatible function type}} */
+  h = (f8 *)t;
+  i = (f9 *)u;
+  j = (f10 *)v; /* expected-warning {{cast from 'const int (*)(int)' to 'f10 
*' (aka 'int (*)(int)') converts to incompatible function type}} */

Endilll wrote:

I hope @AaronBallman can clarify.

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


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-01-07 Thread Vlad Serebrennikov via cfe-commits


@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -fsyntax-only -Wextra -verify

Endilll wrote:

Yes, more `RUN` lines with different `-std=` options, and potentially more 
`expected` directives tailored for particular language mode. We have an example 
of this in C++ defect report tests: 
https://github.com/llvm/llvm-project/blob/main/clang/test/CXX/drs/dr6xx.cpp

Note that I might be biased here, as someone who've spent a significant time 
with C++ defect report test suite.

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


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-01-07 Thread Abhin P Jose via cfe-commits


@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -fsyntax-only -Wextra -verify
+
+
+int t(int array[static 12]);
+int u(int i);
+const int v(int i); /* expected-warning {{'const' type qualifier on return 
type has no effec}} */
+int x(long);
+
+typedef int (f1)(long);
+typedef int (f2)(void*);
+typedef int (f3)();
+typedef void (f4)();
+typedef void (f5)(void);
+typedef int (f6)(long, int);
+typedef int (f7)(long,...);
+typedef int (f8)(int *);
+typedef int (f9)(const int);
+typedef int (f10)(int);
+
+f1 *a;
+f2 *b;
+f3 *c;
+f4 *d;
+f5 *e;
+f6 *f;
+f7 *g;
+f8 *h;
+f9 *i;
+f10 *j;
+
+void foo(void) {
+  a = (f1 *)x;
+  b = (f2 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f2 *' (aka 
'int (*)(void *)') converts to incompatible function type}} */
+  c = (f3 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f3 *' (aka 
'int (*)()') converts to incompatible function type}} */
+  d = (f4 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f4 *' (aka 
'void (*)()') converts to incompatible function type}} */
+  e = (f5 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f5 *' (aka 
'void (*)(void)') converts to incompatible function type}} */
+  f = (f6 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f6 *' (aka 
'int (*)(long, int)') converts to incompatible function type}} */
+  g = (f7 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f7 *' (aka 
'int (*)(long, ...)') converts to incompatible function type}} */
+  h = (f8 *)t;
+  i = (f9 *)u;
+  j = (f10 *)v; /* expected-warning {{cast from 'const int (*)(int)' to 'f10 
*' (aka 'int (*)(int)') converts to incompatible function type}} */

Abhinkop wrote:

Yeah, even I found this strange. Is there a place we can verify which is the 
correct behavior?

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


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-01-07 Thread Abhin P Jose via cfe-commits


@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -fsyntax-only -Wextra -verify

Abhinkop wrote:

add runs for -std=cNN for all remaining 5 of them? and also add extra test 
cases where conflicts arise?

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


[clang-tools-extra] [clang-tidy] Add support for lambdas in cppcoreguidelines-owning-memory (PR #77246)

2024-01-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Piotr Zegar (PiotrZSL)


Changes

Implement proper support for lambdas and sub-functions/classes.
Moved from https://reviews.llvm.org/D157285

Fixes: #59389

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


3 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp (+64-7) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+5-1) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/owning-memory.cpp 
(+95) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
index 9215b833573afd..89450149820f30 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
@@ -19,6 +19,18 @@ using namespace clang::ast_matchers::internal;
 
 namespace clang::tidy::cppcoreguidelines {
 
+namespace {
+AST_MATCHER_P(LambdaExpr, hasCallOperator,
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  return InnerMatcher.matches(*Node.getCallOperator(), Finder, Builder);
+}
+
+AST_MATCHER_P(LambdaExpr, hasLambdaBody, ast_matchers::internal::Matcher,
+  InnerMatcher) {
+  return InnerMatcher.matches(*Node.getBody(), Finder, Builder);
+}
+} // namespace
+
 void OwningMemoryCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "LegacyResourceProducers", LegacyResourceProducers);
   Options.store(Opts, "LegacyResourceConsumers", LegacyResourceConsumers);
@@ -55,6 +67,8 @@ void OwningMemoryCheck::registerMatchers(MatchFinder *Finder) 
{
 CreatesLegacyOwner, LegacyOwnerCast);
 
   const auto ConsideredOwner = eachOf(IsOwnerType, CreatesOwner);
+  const auto ScopeDeclaration = anyOf(translationUnitDecl(), namespaceDecl(),
+  recordDecl(), functionDecl());
 
   // Find delete expressions that delete non-owners.
   Finder->addMatcher(
@@ -147,10 +161,52 @@ void OwningMemoryCheck::registerMatchers(MatchFinder 
*Finder) {
   // Matching on functions, that return an owner/resource, but don't declare
   // their return type as owner.
   Finder->addMatcher(
-  functionDecl(hasDescendant(returnStmt(hasReturnValue(ConsideredOwner))
- .bind("bad_owner_return")),
-   unless(returns(qualType(hasDeclaration(OwnerDecl)
-  .bind("function_decl"),
+  functionDecl(
+  decl().bind("function_decl"),
+  hasBody(stmt(
+  stmt().bind("body"),
+  hasDescendant(
+  returnStmt(hasReturnValue(ConsideredOwner),
+ // Ignore sub-lambda expressions
+ hasAncestor(stmt(anyOf(equalsBoundNode("body"),
+lambdaExpr()))
+ .bind("scope")),
+ hasAncestor(stmt(equalsBoundNode("scope"),
+  equalsBoundNode("body"))),
+ // Ignore sub-functions
+ hasAncestor(functionDecl().bind("context")),
+ hasAncestor(functionDecl(
+ equalsBoundNode("context"),
+ equalsBoundNode("function_decl"
+  .bind("bad_owner_return",
+  returns(qualType(qualType().bind("result"),
+   unless(hasDeclaration(OwnerDecl),
+  this);
+
+  // Matching on lambdas, that return an owner/resource, but don't declare
+  // their return type as owner.
+  Finder->addMatcher(
+  lambdaExpr(
+  hasAncestor(decl(ScopeDeclaration).bind("scope-decl")),
+  hasLambdaBody(stmt(
+  stmt().bind("body"),
+  hasDescendant(
+  returnStmt(
+  hasReturnValue(ConsideredOwner),
+  // Ignore sub-lambdas
+  hasAncestor(
+  stmt(anyOf(equalsBoundNode("body"), lambdaExpr()))
+  .bind("scope")),
+  hasAncestor(stmt(equalsBoundNode("scope"),
+   equalsBoundNode("body"))),
+  // Ignore sub-functions
+  hasAncestor(decl(ScopeDeclaration).bind("context")),
+  hasAncestor(decl(equalsBoundNode("context"),
+   equalsBoundNode("scope-decl"
+  .bind("bad_owner_return",
+  hasCallOperator(returns(qualType(qualType().bind("result"),
+   
unless(hasDeclaration(OwnerDecl))
+  .bind("lambda"),
   this);
 
   // Match on classes that hav

[clang-tools-extra] [clang-tidy] Add support for lambdas in cppcoreguidelines-owning-memory (PR #77246)

2024-01-07 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL created 
https://github.com/llvm/llvm-project/pull/77246

Implement proper support for lambdas and sub-functions/classes.
Moved from https://reviews.llvm.org/D157285

Fixes: #59389

>From b2e230f90f97c0fb3385ab05d0217371b72b9a88 Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Sun, 7 Jan 2024 18:52:05 +
Subject: [PATCH] [clang-tidy] Add support for lambdas in
 cppcoreguidelines-owning-memory

Implement proper support for lambdas and sub-functions/classes.
Moved from https://reviews.llvm.org/D157285

Fixes: #59389
---
 .../cppcoreguidelines/OwningMemoryCheck.cpp   | 71 --
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 +-
 .../cppcoreguidelines/owning-memory.cpp   | 95 +++
 3 files changed, 164 insertions(+), 8 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
index 9215b833573afd..89450149820f30 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
@@ -19,6 +19,18 @@ using namespace clang::ast_matchers::internal;
 
 namespace clang::tidy::cppcoreguidelines {
 
+namespace {
+AST_MATCHER_P(LambdaExpr, hasCallOperator,
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  return InnerMatcher.matches(*Node.getCallOperator(), Finder, Builder);
+}
+
+AST_MATCHER_P(LambdaExpr, hasLambdaBody, ast_matchers::internal::Matcher,
+  InnerMatcher) {
+  return InnerMatcher.matches(*Node.getBody(), Finder, Builder);
+}
+} // namespace
+
 void OwningMemoryCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "LegacyResourceProducers", LegacyResourceProducers);
   Options.store(Opts, "LegacyResourceConsumers", LegacyResourceConsumers);
@@ -55,6 +67,8 @@ void OwningMemoryCheck::registerMatchers(MatchFinder *Finder) 
{
 CreatesLegacyOwner, LegacyOwnerCast);
 
   const auto ConsideredOwner = eachOf(IsOwnerType, CreatesOwner);
+  const auto ScopeDeclaration = anyOf(translationUnitDecl(), namespaceDecl(),
+  recordDecl(), functionDecl());
 
   // Find delete expressions that delete non-owners.
   Finder->addMatcher(
@@ -147,10 +161,52 @@ void OwningMemoryCheck::registerMatchers(MatchFinder 
*Finder) {
   // Matching on functions, that return an owner/resource, but don't declare
   // their return type as owner.
   Finder->addMatcher(
-  functionDecl(hasDescendant(returnStmt(hasReturnValue(ConsideredOwner))
- .bind("bad_owner_return")),
-   unless(returns(qualType(hasDeclaration(OwnerDecl)
-  .bind("function_decl"),
+  functionDecl(
+  decl().bind("function_decl"),
+  hasBody(stmt(
+  stmt().bind("body"),
+  hasDescendant(
+  returnStmt(hasReturnValue(ConsideredOwner),
+ // Ignore sub-lambda expressions
+ hasAncestor(stmt(anyOf(equalsBoundNode("body"),
+lambdaExpr()))
+ .bind("scope")),
+ hasAncestor(stmt(equalsBoundNode("scope"),
+  equalsBoundNode("body"))),
+ // Ignore sub-functions
+ hasAncestor(functionDecl().bind("context")),
+ hasAncestor(functionDecl(
+ equalsBoundNode("context"),
+ equalsBoundNode("function_decl"
+  .bind("bad_owner_return",
+  returns(qualType(qualType().bind("result"),
+   unless(hasDeclaration(OwnerDecl),
+  this);
+
+  // Matching on lambdas, that return an owner/resource, but don't declare
+  // their return type as owner.
+  Finder->addMatcher(
+  lambdaExpr(
+  hasAncestor(decl(ScopeDeclaration).bind("scope-decl")),
+  hasLambdaBody(stmt(
+  stmt().bind("body"),
+  hasDescendant(
+  returnStmt(
+  hasReturnValue(ConsideredOwner),
+  // Ignore sub-lambdas
+  hasAncestor(
+  stmt(anyOf(equalsBoundNode("body"), lambdaExpr()))
+  .bind("scope")),
+  hasAncestor(stmt(equalsBoundNode("scope"),
+   equalsBoundNode("body"))),
+  // Ignore sub-functions
+  hasAncestor(decl(ScopeDeclaration).bind("context")),
+  hasAncestor(decl(equalsBoundNode("context"),
+   equalsBoundNode("scope-decl"
+  .bind("bad_owner_return",
+   

[libunwind] [libunwind] Add length info for dynamic .eh_frame registration (PR #77185)

2024-01-07 Thread via cfe-commits

https://github.com/lhames requested changes to this pull request.

As @arichardson noted this would break the ABI.

The best solution is to fix the implementation of 
`__unw_add_dynamic_eh_frame_section` (and 
`__unw_remove_dynamic_eh_frame_section`) as described in 
https://github.com/llvm/llvm-project/issues/76957#issuecomment-1879977544.

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


[clang] [Driver] Add -fandroid-pad-segment/-fno-android-pad-segment (PR #77244)

2024-01-07 Thread Fangrui Song via cfe-commits

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

-fandroid-pad-segment is an Android-specific opt-in option that
links in crt_pad_segment.o.

crt_pad_segment.o contains a note section, which will be included in the
linker-created PT_NOTE segment. This PT_NOTE tell Bionic that: when
create a map for a PT_LOAD segment, extend the end to cover the gap so
that we will have fewer kernel 'struct vm_area_struct' objects when
page_size < MAXPAGESIZE.

See also https://sourceware.org/bugzilla/show_bug.cgi?id=31076


>From f4758993998e221cc41924d8ec9feb70f759937a Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Sun, 7 Jan 2024 09:47:53 -0800
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 clang/include/clang/Driver/Options.td |  5 +
 clang/lib/Driver/ToolChains/Gnu.cpp   |  5 +
 .../sysroot/usr/lib/crt_pad_segment.o |  0
 clang/test/Driver/linux-ld.c  | 19 ++-
 4 files changed, 28 insertions(+), 1 deletion(-)
 create mode 100644 
clang/test/Driver/Inputs/basic_android_tree/sysroot/usr/lib/crt_pad_segment.o

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 6aff37f1336871..6a5a7c58759e62 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6293,6 +6293,11 @@ def fno_sycl : Flag<["-"], "fno-sycl">,
   Visibility<[ClangOption, CLOption]>,
   Group, HelpText<"Disables SYCL kernels compilation for device">;
 
+// OS-specific options
+let Flags = [TargetSpecific] in {
+defm android_pad_segment : BooleanFFlag<"android-pad-segment">, Group;
+} // let Flags = [TargetSpecific]
+
 
//===--===//
 // FLangOption + NoXarchOption
 
//===--===//
diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index a610a94a39a2b4..dd0dd13883d83a 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -508,6 +508,11 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, 
const JobAction &JA,
 
 // Add crtfastmath.o if available and fast math is enabled.
 ToolChain.addFastMathRuntimeIfAvailable(Args, CmdArgs);
+
+if (isAndroid && Args.hasFlag(options::OPT_fandroid_pad_segment,
+  options::OPT_fno_android_pad_segment, false))
+  CmdArgs.push_back(
+  Args.MakeArgString(ToolChain.GetFilePath("crt_pad_segment.o")));
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u});
diff --git 
a/clang/test/Driver/Inputs/basic_android_tree/sysroot/usr/lib/crt_pad_segment.o 
b/clang/test/Driver/Inputs/basic_android_tree/sysroot/usr/lib/crt_pad_segment.o
new file mode 100644
index 00..e69de29bb2d1d6
diff --git a/clang/test/Driver/linux-ld.c b/clang/test/Driver/linux-ld.c
index 15643d6491ae52..49693b6a2d87e2 100644
--- a/clang/test/Driver/linux-ld.c
+++ b/clang/test/Driver/linux-ld.c
@@ -1338,7 +1338,24 @@
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD-LINK %s
 // CHECK-ANDROID-PTHREAD-LINK-NOT: argument unused during compilation: 
'-pthread'
-//
+
+/// Check -fandroid-pad-segment.
+// RUN: %clang -### %s --target=aarch64-linux-android -rtlib=platform 
--unwindlib=platform \
+// RUN:   --gcc-toolchain="" --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   -fandroid-pad-segment 2>&1 | FileCheck 
--check-prefix=CHECK-ANDROID-PAD-PHDR %s
+// CHECK-ANDROID-PAD-PHDR: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
+// CHECK-ANDROID-PAD-PHDR: "[[SYSROOT]]/usr/lib/crtbegin_dynamic.o" 
"[[SYSROOT]]/usr/lib/crt_pad_phdr.o"
+
+// RUN: %clang -### %s --target=aarch64-linux-android -rtlib=platform 
--unwindlib=platform \
+// RUN:   --gcc-toolchain="" --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   -fandroid-pad-segment -fno-android-pad-segment 2>&1 | FileCheck 
--check-prefix=CHECK-NO-ANDROID-PAD-PHDR %s
+// CHECK-NO-ANDROID-PAD-PHDR: "{{.*}}ld{{(.exe)?}}" 
"--sysroot=[[SYSROOT:[^"]+]]"
+// CHECK-NO-ANDROID-PAD-PHDR: "[[SYSROOT]]/usr/lib/crtbegin_dynamic.o"
+// CHECK-NO-ANDROID-PAD-PHDR-NOT: crt_pad_phdr.o"
+
+// RUN: not %clang -### %s --target=aarch64-linux -fandroid-pad-segment 2>&1 | 
FileCheck --check-prefix=ERR-ANDROID-PAD-EHDR %s
+// ERR-ANDROID-PAD-EHDR: error: unsupported option '-fandroid-pad-segment' for 
target 'aarch64-linux'
+
 // Check linker invocation on a Debian LoongArch sysroot.
 // RUN: %clang -### %s -no-pie 2>&1 \
 // RUN: --target=loongarch64-linux-gnu -rtlib=platform 
--unwindlib=platform \

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
htt

[clang] [llvm] [compiler-rt] [libcxx] [mlir] [asan] Enable StackSafetyAnalysis by default (PR #77210)

2024-01-07 Thread Fangrui Song via cfe-commits

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


[llvm] [compiler-rt] [libcxx] [clang] [mlir] [asan] Enable StackSafetyAnalysis by default (PR #77210)

2024-01-07 Thread Fangrui Song via cfe-commits

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

>From af33fcdf5a46c5bd34db89615a037e5eca421ef9 Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Fri, 5 Jan 2024 23:50:40 -0800
Subject: [PATCH] [asan] Enable StackSafetyAnalysis by default

StackSafetyAnalysis determines whether stack-allocated variables are
safe from memory access bugs and allows removing certain unneeded
instrumentations.
(hwasan enables StackSafetyAnalysis in https://reviews.llvm.org/D108381)

Test updates:

* asan-stack-safety.ll: test the -asan-use-stack-safety=1 default
* lifetime-uar-uas.ll: switch to an indexed store to prevent
  StackSafetyAnalysis from optimizing out instrumentation for %c
* alloca_vla_interact.cpp: add a load to prevent StackSafetyAnalysis
  from optimizing out `__asan_alloca_poison` for the VLA `array`
* scariness_score_test.cpp: add -asan-use-stack-safety=0 to make a load
  of a `__asan_poison_memory_region`-poisoned local variable fail as
  intended.
* other .ll tests: add -asan-use-stack-safety=0

Pull Request: https://github.com/llvm/llvm-project/pull/77210
---
 .../test/asan/TestCases/alloca_vla_interact.cpp |  2 ++
 .../test/asan/TestCases/scariness_score_test.cpp|  6 --
 .../Transforms/Instrumentation/AddressSanitizer.cpp |  2 +-
 .../AddressSanitizer/asan-stack-safety.ll   |  2 +-
 .../Instrumentation/AddressSanitizer/debug_info.ll  |  2 +-
 .../AddressSanitizer/lifetime-uar-uas.ll| 13 -
 .../Instrumentation/AddressSanitizer/lifetime.ll|  4 ++--
 .../AddressSanitizer/local_stack_base.ll|  2 +-
 .../AddressSanitizer/stack_dynamic_alloca.ll|  8 
 .../AddressSanitizer/stack_layout.ll|  4 ++--
 10 files changed, 26 insertions(+), 19 deletions(-)

diff --git a/compiler-rt/test/asan/TestCases/alloca_vla_interact.cpp 
b/compiler-rt/test/asan/TestCases/alloca_vla_interact.cpp
index 92b0afafc8db77..96ac4c7db291a0 100644
--- a/compiler-rt/test/asan/TestCases/alloca_vla_interact.cpp
+++ b/compiler-rt/test/asan/TestCases/alloca_vla_interact.cpp
@@ -33,6 +33,8 @@ __attribute__((noinline)) void foo(int len) {
 if (i) assert(!__asan_region_is_poisoned(bot, 96));
 // VLA is unpoisoned at the end of iteration.
 volatile char array[i];
+// Ensure that asan-use-stack-safety does not optimize out the poisoning.
+if (i) array[0] = 0;
 assert(!(reinterpret_cast(array) & 31L));
 // Alloca is unpoisoned at the end of iteration,
 // because dominated by VLA.
diff --git a/compiler-rt/test/asan/TestCases/scariness_score_test.cpp 
b/compiler-rt/test/asan/TestCases/scariness_score_test.cpp
index d73975feb6873b..9e55e33675fde3 100644
--- a/compiler-rt/test/asan/TestCases/scariness_score_test.cpp
+++ b/compiler-rt/test/asan/TestCases/scariness_score_test.cpp
@@ -1,7 +1,9 @@
 // Test how we produce the scariness score.
 
 // UAR Mode: runtime
-// RUN: %clangxx_asan -O0 %s -o %t
+// Case 26 loads a __asan_poison_memory_region-poisoned local variable, which 
is
+// only instrumented when StackSafetyAnalysis is disabled.
+// RUN: %clangxx_asan -O0 -mllvm -asan-use-stack-safety=0 %s -o %t
 // On OSX and Windows, alloc_dealloc_mismatch=1 isn't 100% reliable, so it's
 // off by default. It's safe for these tests, though, so we turn it on.
 // RUN: export 
%env_asan_opts=symbolize=0:detect_stack_use_after_return=1:handle_abort=1:print_scariness=1:alloc_dealloc_mismatch=1
@@ -36,7 +38,7 @@
 // RUN: not %run %t 27 2>&1 | FileCheck %s --check-prefix=CHECK27
 //
 // UAR Mode: always
-// RUN: %clangxx_asan -O0 %s -o %t -fsanitize-address-use-after-return=always
+// RUN: %clangxx_asan -O0 %s -o %t -fsanitize-address-use-after-return=always 
-mllvm -asan-use-stack-safety=0
 // On OSX and Windows, alloc_dealloc_mismatch=1 isn't 100% reliable, so it's
 // off by default. It's safe for these tests, though, so we turn it on.
 // RUN: export 
%env_asan_opts=symbolize=0:handle_abort=1:print_scariness=1:alloc_dealloc_mismatch=1
diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index e3deafa49bd91e..5e7e08eaa9978d 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -216,7 +216,7 @@ static cl::opt ClInstrumentWrites(
 cl::Hidden, cl::init(true));
 
 static cl::opt
-ClUseStackSafety("asan-use-stack-safety", cl::Hidden, cl::init(false),
+ClUseStackSafety("asan-use-stack-safety", cl::Hidden, cl::init(true),
  cl::Hidden, cl::desc("Use Stack Safety analysis results"),
  cl::Optional);
 
diff --git a/llvm/test/Instrumentation/AddressSanitizer/asan-stack-safety.ll 
b/llvm/test/Instrumentation/AddressSanitizer/asan-stack-safety.ll
index 02c58a1f492261..8210970aaaeb4b 100644
--- a/llvm/test/Instrumentation/AddressSanitizer/asan-stack-safety.ll
+++ b/llvm/test/Instrumentation/AddressSanitizer/asa

[libunwind] [libunwind] Add length info for dynamic .eh_frame registration (PR #77185)

2024-01-07 Thread Alexander Richardson via cfe-commits

https://github.com/arichardson commented:

While I think this is a reasonable change, I don't think we can change this 
function signature without breaking the ABI. So it probably needs to be a new 
function instead.

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


[compiler-rt] [libcxx] [llvm] [clang] [flang] [libc] [clang-tools-extra] [libc++] Implement LWG3940: std::expected::value() also needs E to be copy constructible (PR #71819)

2024-01-07 Thread Mark de Wever via cfe-commits

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


[libcxx] [flang] [clang-tools-extra] [compiler-rt] [llvm] [libc] [clang] [libc++] Implement LWG3940: std::expected::value() also needs E to be copy constructible (PR #71819)

2024-01-07 Thread Mark de Wever via cfe-commits

https://github.com/mordante commented:

> The CI finally passed now : )

Great. A few minor comment and then it LGTM. I'll leave the final approval to 
@huixie90 

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


[compiler-rt] [flang] [llvm] [libcxx] [clang-tools-extra] [libc] [clang] [libc++] Implement LWG3940: std::expected::value() also needs E to be copy constructible (PR #71819)

2024-01-07 Thread Mark de Wever via cfe-commits


@@ -1150,12 +1150,15 @@ class expected<_Tp, _Err> {
   }
 
   _LIBCPP_HIDE_FROM_ABI constexpr void value() const& {
+static_assert(is_copy_constructible_v<_Err>);
 if (!__has_val_) {
   std::__throw_bad_expected_access<_Err>(__union_.__unex_);
 }
   }
 
   _LIBCPP_HIDE_FROM_ABI constexpr void value() && {
+static_assert(is_copy_constructible_v<_Err> && 
is_move_constructible_v<_Err>,
+  "error_type has to be both copy constructible and move 
constructible");

mordante wrote:

Since we don't require a message in `static_assert` anymore and this message 
adds no extra information, let's remove it.

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


[flang] [llvm] [clang-tools-extra] [libc] [libcxx] [clang] [compiler-rt] [libc++] Implement LWG3940: std::expected::value() also needs E to be copy constructible (PR #71819)

2024-01-07 Thread Mark de Wever via cfe-commits


@@ -0,0 +1,51 @@
+//===--===//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+// UNSUPPORTED: no-rtti
+// UNSUPPORTED: no-exceptions
+
+// constexpr void value() const &;
+// Mandates: is_copy_constructible_v is true.
+
+// constexpr void value() &&;
+// Mandates: is_copy_constructible_v is true and is_move_constructible_v 
is true.
+
+#include 
+
+#include "MoveOnly.h"
+
+struct CopyOnly {
+  CopyOnly()= default;
+  CopyOnly(const CopyOnly&) = default;
+  CopyOnly(CopyOnly&&)  = delete;
+};
+
+void test() {
+  // MoveOnly type as error_type
+  std::expected e(std::unexpect, 5);
+
+  e.value(); // expected-note {{in instantiation of member function 
'std::expected::value' requested here}}
+  // expected-error@*:* {{static assertion failed due to requirement 
'is_copy_constructible_v'}}
+
+  std::move(e)
+  .value(); // expected-note {{in instantiation of member function 
'std::expected::value' requested here}}
+  // expected-error@*:* {{static assertion failed due to requirement 
'is_copy_constructible_v': error_type has to be both copy 
constructible and move constructible}}
+
+  // CopyOnly type as error_type
+  std::expected e2(std::unexpect);
+
+  e2.value();
+
+  std::move(e2)
+  .value(); // expected-note {{in instantiation of member function 
'std::expected::value' requested here}}
+  // expected-error@*:* {{static assertion failed due to requirement 
'is_move_constructible_v': error_type has to be both copy 
constructible and move constructible}}
+
+  // expected-error@*:* {{call to deleted constructor of 'MoveOnly'}}
+  // expected-error@*:* {{call to deleted constructor of 'CopyOnly'}}
+  // expected-error@*:* {{call to deleted constructor of 'CopyOnly'}}

mordante wrote:

Can you move these expected-error's to the places where they are generated. We 
need the `@*:*` since they are in the headers, but for maintainability it's 
good to have them where they are generated. 

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


[clang-tools-extra] [lldb] [clang] [libcxx] [compiler-rt] [llvm] [mlir] Fix Multiple Build Errors on different platforms (PR #77216)

2024-01-07 Thread via cfe-commits

https://github.com/trcrsired updated 
https://github.com/llvm/llvm-project/pull/77216

>From a1156a564c798192cb7608e28ce9b9ed846a8b1c Mon Sep 17 00:00:00 2001
From: trcrsired 
Date: Sat, 6 Jan 2024 20:21:06 -0500
Subject: [PATCH 1/2] Fix Multiple Build Errors on different platforms

Particularly for canadian compilation
---
 .../pseudo/include/CMakeLists.txt |  12 +-
 clang/lib/Tooling/CMakeLists.txt  |  10 +-
 compiler-rt/lib/builtins/fp_compare_impl.inc  |   3 +
 lldb/source/Host/android/HostInfoAndroid.cpp  |   4 +
 lldb/source/Host/android/LibcGlue.cpp |   2 +
 llvm/include/llvm/TargetParser/Triple.h   | 287 +++---
 llvm/lib/Support/Unix/Unix.h  |  17 +-
 mlir/lib/ExecutionEngine/CRunnerUtils.cpp |   4 +-
 8 files changed, 147 insertions(+), 192 deletions(-)

diff --git a/clang-tools-extra/pseudo/include/CMakeLists.txt 
b/clang-tools-extra/pseudo/include/CMakeLists.txt
index 2334cfa12e3376..605f17dd4591a0 100644
--- a/clang-tools-extra/pseudo/include/CMakeLists.txt
+++ b/clang-tools-extra/pseudo/include/CMakeLists.txt
@@ -3,10 +3,18 @@ set(cxx_bnf ${CMAKE_CURRENT_SOURCE_DIR}/../lib/cxx/cxx.bnf)
 
 setup_host_tool(clang-pseudo-gen CLANG_PSEUDO_GEN pseudo_gen pseudo_gen_target)
 
+if(NOT DEFINED CLANG_PSEUDO_GEN)
+   if(DEFINED LLVM_NATIVE_TOOL_DIR AND NOT LLVM_NATIVE_TOOL_DIR STREQUAL "")
+  set(CLANG_PSEUDO_GEN "${LLVM_NATIVE_TOOL_DIR}/clang_pseudo_gen")
+   else()
+  set(CLANG_PSEUDO_GEN "${pseudo_gen}")
+   endif()
+endif()
+
 # Generate inc files.
 set(cxx_symbols_inc ${CMAKE_CURRENT_BINARY_DIR}/CXXSymbols.inc)
 add_custom_command(OUTPUT ${cxx_symbols_inc}
-   COMMAND "${pseudo_gen}"
+   COMMAND "${CLANG_PSEUDO_GEN}"
  --grammar ${cxx_bnf}
  --emit-symbol-list
  -o ${cxx_symbols_inc}
@@ -16,7 +24,7 @@ add_custom_command(OUTPUT ${cxx_symbols_inc}
 
 set(cxx_bnf_inc ${CMAKE_CURRENT_BINARY_DIR}/CXXBNF.inc)
 add_custom_command(OUTPUT ${cxx_bnf_inc}
-   COMMAND "${pseudo_gen}"
+   COMMAND "${CLANG_PSEUDO_GEN}"
  --grammar ${cxx_bnf}
  --emit-grammar-content
  -o ${cxx_bnf_inc}
diff --git a/clang/lib/Tooling/CMakeLists.txt b/clang/lib/Tooling/CMakeLists.txt
index aff39e4de13c0b..1510f5fb8a0810 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -53,6 +53,14 @@ else()
 list(APPEND implicitDirs -I ${implicitDir})
   endforeach()
 
+  if(NOT DEFINED CLANG_AST_DUMP)
+if(DEFINED LLVM_NATIVE_TOOL_DIR AND NOT LLVM_NATIVE_TOOL_DIR STREQUAL "")
+  set(CLANG_AST_DUMP ${LLVM_NATIVE_TOOL_DIR}/clang-ast-dump)
+else()
+  set(CLANG_AST_DUMP $)
+endif()
+  endif()
+
   include(GetClangResourceDir)
   get_clang_resource_dir(resource_dir PREFIX ${LLVM_BINARY_DIR})
   add_custom_command(
@@ -60,7 +68,7 @@ else()
   OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/ASTNodeAPI.json
   DEPENDS clang-ast-dump clang-resource-headers
   COMMAND
-  $
+  ${CLANG_AST_DUMP}
 # Skip this in debug mode because parsing AST.h is too slow
 --skip-processing=${skip_expensive_processing}
 -I ${resource_dir}/include
diff --git a/compiler-rt/lib/builtins/fp_compare_impl.inc 
b/compiler-rt/lib/builtins/fp_compare_impl.inc
index a9a4f6fbf5dfe4..b2ebd0737df033 100644
--- a/compiler-rt/lib/builtins/fp_compare_impl.inc
+++ b/compiler-rt/lib/builtins/fp_compare_impl.inc
@@ -18,6 +18,9 @@ typedef int CMP_RESULT;
 #elif __SIZEOF_POINTER__ == 8 && __SIZEOF_LONG__ == 4
 // LLP64 ABIs use long long instead of long.
 typedef long long CMP_RESULT;
+#elif defined(__wasm64__)
+// GCC uses int as CMP_RESULT
+typedef int CMP_RESULT;
 #elif __AVR__
 // AVR uses a single byte for the return value.
 typedef char CMP_RESULT;
diff --git a/lldb/source/Host/android/HostInfoAndroid.cpp 
b/lldb/source/Host/android/HostInfoAndroid.cpp
index 68440e016afe4b..5ba2f0e24a8d24 100644
--- a/lldb/source/Host/android/HostInfoAndroid.cpp
+++ b/lldb/source/Host/android/HostInfoAndroid.cpp
@@ -6,6 +6,8 @@
 //
 
//===--===//
 
+#ifdef __ANDROID__
+
 #include "lldb/Host/android/HostInfoAndroid.h"
 #include "lldb/Host/FileSystem.h"
 #include "lldb/Host/linux/HostInfoLinux.h"
@@ -92,3 +94,5 @@ bool HostInfoAndroid::ComputeTempFileBaseDirectory(FileSpec 
&file_spec) {
 
   return FileSystem::Instance().Exists(file_spec);
 }
+
+#endif
diff --git a/lldb/source/Host/android/LibcGlue.cpp 
b/lldb/source/Host/android/LibcGlue.cpp
index 877d735823feee..82b257719c2c8a 100644
--- a/lldb/source/Host/android/LibcGlue.cpp
+++ b/lldb/source/Host/android/LibcGlue.cpp
@@ -8,6 +8,7 @@
 
 // This files adds functions missing from libc on earlier versions of Android
 
+#ifdef __ANDROID__
 #include 
 
 #include 
@@ -26,3 +27,4 @@ time_t timegm(struct tm *t) { return (time_t)timegm64(t); }
 int posix_openpt(int flags) { return open("/dev/ptmx", flags); }
 
 #endif
+#endif
diff --git a/llvm/include/llvm/TargetParser/Triple.h 
b/llvm/include/llvm/TargetP

[clang] [libcxx] [llvm] Reapply "[libc++][streams] P1759R6: Native handles and file streams" (PR #77190)

2024-01-07 Thread Hristo Hristov via cfe-commits

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


[clang] [libcxx] [llvm] Reapply "[libc++][streams] P1759R6: Native handles and file streams" (PR #77190)

2024-01-07 Thread Hristo Hristov via cfe-commits

Zingam wrote:

I'm relanding this and I'll keep eyes on it here: 
https://ci.chromium.org/ui/p/fuchsia/builders/toolchain.ci/clang-windows-x64

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


[lldb] [clang] [libcxx] [llvm] [clang-tools-extra] [compiler-rt] [mlir] Fix Multiple Build Errors on different platforms (PR #77216)

2024-01-07 Thread via cfe-commits

https://github.com/trcrsired updated 
https://github.com/llvm/llvm-project/pull/77216

>From a1156a564c798192cb7608e28ce9b9ed846a8b1c Mon Sep 17 00:00:00 2001
From: trcrsired 
Date: Sat, 6 Jan 2024 20:21:06 -0500
Subject: [PATCH 1/2] Fix Multiple Build Errors on different platforms

Particularly for canadian compilation
---
 .../pseudo/include/CMakeLists.txt |  12 +-
 clang/lib/Tooling/CMakeLists.txt  |  10 +-
 compiler-rt/lib/builtins/fp_compare_impl.inc  |   3 +
 lldb/source/Host/android/HostInfoAndroid.cpp  |   4 +
 lldb/source/Host/android/LibcGlue.cpp |   2 +
 llvm/include/llvm/TargetParser/Triple.h   | 287 +++---
 llvm/lib/Support/Unix/Unix.h  |  17 +-
 mlir/lib/ExecutionEngine/CRunnerUtils.cpp |   4 +-
 8 files changed, 147 insertions(+), 192 deletions(-)

diff --git a/clang-tools-extra/pseudo/include/CMakeLists.txt 
b/clang-tools-extra/pseudo/include/CMakeLists.txt
index 2334cfa12e3376..605f17dd4591a0 100644
--- a/clang-tools-extra/pseudo/include/CMakeLists.txt
+++ b/clang-tools-extra/pseudo/include/CMakeLists.txt
@@ -3,10 +3,18 @@ set(cxx_bnf ${CMAKE_CURRENT_SOURCE_DIR}/../lib/cxx/cxx.bnf)
 
 setup_host_tool(clang-pseudo-gen CLANG_PSEUDO_GEN pseudo_gen pseudo_gen_target)
 
+if(NOT DEFINED CLANG_PSEUDO_GEN)
+   if(DEFINED LLVM_NATIVE_TOOL_DIR AND NOT LLVM_NATIVE_TOOL_DIR STREQUAL "")
+  set(CLANG_PSEUDO_GEN "${LLVM_NATIVE_TOOL_DIR}/clang_pseudo_gen")
+   else()
+  set(CLANG_PSEUDO_GEN "${pseudo_gen}")
+   endif()
+endif()
+
 # Generate inc files.
 set(cxx_symbols_inc ${CMAKE_CURRENT_BINARY_DIR}/CXXSymbols.inc)
 add_custom_command(OUTPUT ${cxx_symbols_inc}
-   COMMAND "${pseudo_gen}"
+   COMMAND "${CLANG_PSEUDO_GEN}"
  --grammar ${cxx_bnf}
  --emit-symbol-list
  -o ${cxx_symbols_inc}
@@ -16,7 +24,7 @@ add_custom_command(OUTPUT ${cxx_symbols_inc}
 
 set(cxx_bnf_inc ${CMAKE_CURRENT_BINARY_DIR}/CXXBNF.inc)
 add_custom_command(OUTPUT ${cxx_bnf_inc}
-   COMMAND "${pseudo_gen}"
+   COMMAND "${CLANG_PSEUDO_GEN}"
  --grammar ${cxx_bnf}
  --emit-grammar-content
  -o ${cxx_bnf_inc}
diff --git a/clang/lib/Tooling/CMakeLists.txt b/clang/lib/Tooling/CMakeLists.txt
index aff39e4de13c0b..1510f5fb8a0810 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -53,6 +53,14 @@ else()
 list(APPEND implicitDirs -I ${implicitDir})
   endforeach()
 
+  if(NOT DEFINED CLANG_AST_DUMP)
+if(DEFINED LLVM_NATIVE_TOOL_DIR AND NOT LLVM_NATIVE_TOOL_DIR STREQUAL "")
+  set(CLANG_AST_DUMP ${LLVM_NATIVE_TOOL_DIR}/clang-ast-dump)
+else()
+  set(CLANG_AST_DUMP $)
+endif()
+  endif()
+
   include(GetClangResourceDir)
   get_clang_resource_dir(resource_dir PREFIX ${LLVM_BINARY_DIR})
   add_custom_command(
@@ -60,7 +68,7 @@ else()
   OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/ASTNodeAPI.json
   DEPENDS clang-ast-dump clang-resource-headers
   COMMAND
-  $
+  ${CLANG_AST_DUMP}
 # Skip this in debug mode because parsing AST.h is too slow
 --skip-processing=${skip_expensive_processing}
 -I ${resource_dir}/include
diff --git a/compiler-rt/lib/builtins/fp_compare_impl.inc 
b/compiler-rt/lib/builtins/fp_compare_impl.inc
index a9a4f6fbf5dfe4..b2ebd0737df033 100644
--- a/compiler-rt/lib/builtins/fp_compare_impl.inc
+++ b/compiler-rt/lib/builtins/fp_compare_impl.inc
@@ -18,6 +18,9 @@ typedef int CMP_RESULT;
 #elif __SIZEOF_POINTER__ == 8 && __SIZEOF_LONG__ == 4
 // LLP64 ABIs use long long instead of long.
 typedef long long CMP_RESULT;
+#elif defined(__wasm64__)
+// GCC uses int as CMP_RESULT
+typedef int CMP_RESULT;
 #elif __AVR__
 // AVR uses a single byte for the return value.
 typedef char CMP_RESULT;
diff --git a/lldb/source/Host/android/HostInfoAndroid.cpp 
b/lldb/source/Host/android/HostInfoAndroid.cpp
index 68440e016afe4b..5ba2f0e24a8d24 100644
--- a/lldb/source/Host/android/HostInfoAndroid.cpp
+++ b/lldb/source/Host/android/HostInfoAndroid.cpp
@@ -6,6 +6,8 @@
 //
 
//===--===//
 
+#ifdef __ANDROID__
+
 #include "lldb/Host/android/HostInfoAndroid.h"
 #include "lldb/Host/FileSystem.h"
 #include "lldb/Host/linux/HostInfoLinux.h"
@@ -92,3 +94,5 @@ bool HostInfoAndroid::ComputeTempFileBaseDirectory(FileSpec 
&file_spec) {
 
   return FileSystem::Instance().Exists(file_spec);
 }
+
+#endif
diff --git a/lldb/source/Host/android/LibcGlue.cpp 
b/lldb/source/Host/android/LibcGlue.cpp
index 877d735823feee..82b257719c2c8a 100644
--- a/lldb/source/Host/android/LibcGlue.cpp
+++ b/lldb/source/Host/android/LibcGlue.cpp
@@ -8,6 +8,7 @@
 
 // This files adds functions missing from libc on earlier versions of Android
 
+#ifdef __ANDROID__
 #include 
 
 #include 
@@ -26,3 +27,4 @@ time_t timegm(struct tm *t) { return (time_t)timegm64(t); }
 int posix_openpt(int flags) { return open("/dev/ptmx", flags); }
 
 #endif
+#endif
diff --git a/llvm/include/llvm/TargetParser/Triple.h 
b/llvm/include/llvm/TargetP

[clang] [flang] [Flang][Driver] Enable gpulibc/nogpulibc options for Flang, which allows linking of GPU LIBC for the fortran and OpenMP runtime (PR #77135)

2024-01-07 Thread Andrzej WarzyƄski via cfe-commits

banach-space wrote:

Thanks for the discussion!

> It defaults to on if it finds the `libc` wrapper headers in the `clang` 
> resource directory, 
> `lib/clang/18/include/llvm_libc_wrappers/llvm-libc-decls`. I'm assuming that 
> Fortran doesn't have this?

It shouldn't, which means that the semantics of `-gpulibc` will be a bit 
different in Flang, right? That's something that could be tested.

> I'm not familiar with how Fortran handles stuff here. It's tested in the 
> clang portion at least. The handling of this is in CommonArgs somewhere I 
> believe. If Fortran shares that it should be inherited, so it's at least 
> tested in the clang version so it might be fine.

Some bits in "CommonArgs" will be shared, but we do specialise for Flang in 
various places. Also, tests in Clang check the driver in the "Clang" mode - it 
would be good to verify this option in the "Flang" mode as well. There's 
[driver-help.f90](https://github.com/llvm/llvm-project/pull/77135/files#diff-4c4771b20e711ab7224825cfe3902f57465195797c39a29d8a59027360f6bf30),
 but it is not that helpful (it only makes sure that we don't pollute 
`flang-new -help` with options from Clang that are not supported).


> However, i am a little bit of a driver and build environment/system noob 

Not true, you've already landed a few patches :) 

> ill defer to everyone else's better judgement in this case!

Replicating the following would be sufficient: 
https://github.com/llvm/llvm-project/blob/main/clang/test/Driver/openmp-offload-gpu.c#L392.


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


[clang-tools-extra] [clangd] don't lower severity of clang-tidy modernize-* checks to remarks (PR #75706)

2024-01-07 Thread Marzo Sette Torres Junior via cfe-commits

marzojr wrote:

Coming from the issue I posted on `vscode-clangd`, I think it was a bad 
decision to make `modernize-*` checks basically disappear from the GUI. I feel 
less strongly with regards to `misc-unused-*` checks, but it is probably also 
true for those.

While trying to remove clutter is a good thing, I think this was done in the 
wrong way: there is no way to *opt into* the clutter if one wants to (which, 
one might argue, the user already *has* opted into when they enabled those 
checks in clang-tidy in the first place). As is, these warnings become nearly 
invisible, to the point of being useless -- if you *want* to address them, you 
either have to manually run clang-tidy from the command line, or go file by 
file scanning for strike-through text (which, in some cases, can be a single 
character wide), hovering over with the mouse to see if you want to fix it.

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


[clang] 8f76f18 - [OpenMP][Obvious] Fix test failing on BE architectures

2024-01-07 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2024-01-07T08:38:50-06:00
New Revision: 8f76f1816ea63b7cc28e150ba319ffbfe6351f9e

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

LOG: [OpenMP][Obvious] Fix test failing on BE architectures

Summary:
This accidentally included a byte past the magic, which was out of order
on big endian architectures.

Added: 


Modified: 
clang/test/Driver/linker-wrapper-image.c

Removed: 




diff  --git a/clang/test/Driver/linker-wrapper-image.c 
b/clang/test/Driver/linker-wrapper-image.c
index 40dde2e0291800..03caa1eb084e6e 100644
--- a/clang/test/Driver/linker-wrapper-image.c
+++ b/clang/test/Driver/linker-wrapper-image.c
@@ -19,7 +19,7 @@
 //  OPENMP-COFF: @__start_omp_offloading_entries = hidden constant [0 x 
%struct.__tgt_offload_entry] zeroinitializer, section 
"omp_offloading_entries$OA"
 // OPENMP-COFF-NEXT: @__stop_omp_offloading_entries = hidden constant [0 x 
%struct.__tgt_offload_entry] zeroinitializer, section 
"omp_offloading_entries$OZ"
 
-// OPENMP-NEXT: @.omp_offloading.device_image = internal unnamed_addr constant 
[[[SIZE:[0-9]+]] x i8] c"\10\FF\10\AD\01{{.*}}", section ".llvm.offloading", 
align 8
+//  OPENMP: @.omp_offloading.device_image = internal unnamed_addr constant 
[[[SIZE:[0-9]+]] x i8] c"\10\FF\10\AD{{.*}}", section ".llvm.offloading", align 
8
 // OPENMP-NEXT: @.omp_offloading.device_images = internal unnamed_addr 
constant [1 x %__tgt_device_image] [%__tgt_device_image { ptr getelementptr 
inbounds ([[[BEGIN:[0-9]+]] x i8], ptr @.omp_offloading.device_image, i64 1, 
i64 0), ptr getelementptr inbounds ([[[END:[0-9]+]] x i8], ptr 
@.omp_offloading.device_image, i64 1, i64 0), ptr 
@__start_omp_offloading_entries, ptr @__stop_omp_offloading_entries }]
 // OPENMP-NEXT: @.omp_offloading.descriptor = internal constant 
%__tgt_bin_desc { i32 1, ptr @.omp_offloading.device_images, ptr 
@__start_omp_offloading_entries, ptr @__stop_omp_offloading_entries }
 // OPENMP-NEXT: @llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] 
[{ i32, ptr, ptr } { i32 1, ptr @.omp_offloading.descriptor_reg, ptr null }]



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


  1   2   >