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

2024-01-08 Thread Rainer Orth via cfe-commits

rorth wrote:

This patch broke the [Solaris/sparcv9 
buildbot](https://lab.llvm.org/buildbot/#/builders/72/builds/1709): the 
new/changed tests `FAIL` with
```
  File 
/opt/llvm-buildbot/home/solaris11-sparcv9/clang-solaris11-sparcv9/llvm/clang/test/SemaCXX/format-strings-scanf.cpp
 Line 25: _Float16 is not supported on this target
1 error generated.
```

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] [Serialization] Load Specializations Lazily (1/2) (PR #76774)

2024-01-08 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:

It looks like the qualified related problems in ODRHash (at least some of them) 
are fixed in https://reviews.llvm.org/D156210

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-08 Thread Vassil Vassilev via cfe-commits

vgvassilev wrote:

> > This is a great way to start a new year ;)
> > The phab link is https://reviews.llvm.org/D41416.
> > In general I was wondering could we simplify the implementation by loading 
> > the specialization hash table upon module load. That should be relatively 
> > cheap as we will read 2 integers per specialization.
> > Perhaps we should put both patches together and that'd allow us to test 
> > them if they are on par with https://reviews.llvm.org/D41416 which we use 
> > downstream.
> > Thanks for working on this!
> 
> Hi Vassilev, for testing purpose I sent 
> https://github.com/ChuanqiXu9/llvm-project/tree/LoadSpecializationUpdatesLazily.
>  I didn't create stacked review since I feel a standalone branch may be 
> sufficient.
> 

@ChuanqiXu9, I'd prefer to review both patches at the same time. Otherwise we 
risk of missing some important details.

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-08 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> > > This is a great way to start a new year ;)
> > > The phab link is https://reviews.llvm.org/D41416.
> > > In general I was wondering could we simplify the implementation by 
> > > loading the specialization hash table upon module load. That should be 
> > > relatively cheap as we will read 2 integers per specialization.
> > > Perhaps we should put both patches together and that'd allow us to test 
> > > them if they are on par with https://reviews.llvm.org/D41416 which we use 
> > > downstream.
> > > Thanks for working on this!
> > 
> > 
> > Hi Vassilev, for testing purpose I sent 
> > https://github.com/ChuanqiXu9/llvm-project/tree/LoadSpecializationUpdatesLazily.
> >  I didn't create stacked review since I feel a standalone branch may be 
> > sufficient.
> 
> @ChuanqiXu9, I'd prefer to review both patches at the same time. Otherwise we 
> risk of missing some important details.

Got it. I can try to create a stacked review. But from I know about the status 
quo stacked review now, it will require us to lost the current contexnt...

And it will still be pretty valuable if you can test this with your internal 
workloads, then may be we can find something pretty important in the high level 
before going into the details. I've tested this in our local workloads, and it 
looks good and the performance improvements remains. But I know our uses about 
modules may be not so complex like yours.

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-08 Thread Vassil Vassilev 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); }

vgvassilev wrote:

I guess the comment we are discussing is here: 
https://reviews.llvm.org/D154324#4524368 by @zygoloid:

"
...

For [D41416](https://reviews.llvm.org/D41416), ODR hashing may not be the best 
mechanism to hash the template arguments, unfortunately. ODR hashing is (or 
perhaps, should be) about determining whether two things are spelled the same 
way and have the same meaning (as required by the C++ ODR), whereas I think 
what you're looking for is whether they have the same meaning regardless of 
spelling. Maybe we can get away with reusing ODR hashing anyway, on the basis 
that any canonical, non-dependent template argument should have the same 
(invented) spelling in every translation unit, but I'm not certain that's true 
in all cases. There may still be cases where the canonical type includes some 
aspect of "whatever we saw first", in which case the ODR hash can differ across 
translation units for non-dependent, canonical template arguments that are 
spelled differently but have the same meaning, though I can't think of one 
off-hand.
```

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-08 Thread Vassil Vassilev via cfe-commits

https://github.com/vgvassilev edited 
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-08 Thread Vassil Vassilev via cfe-commits

https://github.com/vgvassilev edited 
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] Objective C: use C++ exceptions on MinGW+GNUstep (PR #77255)

2024-01-08 Thread David Chisnall via cfe-commits


@@ -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 {

davidchisnall wrote:

It looks as if both branches of the if and else here do the same thing?

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-tools-extra] [clang-tidy] Improve performance of misc-const-correctness (PR #72705)

2024-01-08 Thread Congcong Cai via cfe-commits

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

LGTM

https://github.com/llvm/llvm-project/pull/72705
___
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-08 Thread David Chisnall via cfe-commits

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

>From 6195e6c57b5b461dda2bffec0e5497ceb659f82c 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-08 Thread David Chisnall via cfe-commits

davidchisnall wrote:

The failing format CI isn’t in this PR, rebasing to (hopefully) fix it

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] [Serialization] Load Specializations Lazily (1/2) (PR #76774)

2024-01-08 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:

Yeah, I just saw it. My concern for reinventing a new hash mechanism is how can 
we make sure it is correct. It may be not hard to invent a new hasher. But I am 
just worrying it may not be well tested. I prefer to make it step by step.

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


[llvm] [clang] [ASAN] For Asan instrumented global, emit two symbols, one with actual size and other with instrumented size. (PR #70166)

2024-01-08 Thread via cfe-commits

skc7 wrote:

> Will wait for a rebase on some changes requested in #68865, but it'd also be 
> really important to write tests for a couple more scenarios:
> 
> 1. Building with `-fsanitize=address -S -emit-llvm` results in GVs with 
> `sanitized_padded_global` (and results in GVs without 
> `sanitized_padded_global` if they have 
> `__attribute__((no_sanitize("address")))` for example). See 
> `clang/test/CodeGen/memtag-globals.cpp`.
> 2. Running [Fixing Rust build 
> #1](https://github.com/llvm/llvm-project/pull/1) through bitcode back/forth 
> to make sure you still have the same attributes sets (to ensure you got the 
> parser/writer logic correct). See `llvm/test/Bitcode/compatibility.ll` and 
> `llvm/test/Assembler/globalvariable-attributes.ll`.

Hi @hctim, #68865 has been updated as per suggestions. Please review.

https://github.com/llvm/llvm-project/pull/70166
___
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-08 Thread Vassil Vassilev via cfe-commits

vgvassilev wrote:

> > > > This is a great way to start a new year ;)
> > > > The phab link is https://reviews.llvm.org/D41416.
> > > > In general I was wondering could we simplify the implementation by 
> > > > loading the specialization hash table upon module load. That should be 
> > > > relatively cheap as we will read 2 integers per specialization.
> > > > Perhaps we should put both patches together and that'd allow us to test 
> > > > them if they are on par with https://reviews.llvm.org/D41416 which we 
> > > > use downstream.
> > > > Thanks for working on this!
> > > 
> > > 
> > > Hi Vassilev, for testing purpose I sent 
> > > https://github.com/ChuanqiXu9/llvm-project/tree/LoadSpecializationUpdatesLazily.
> > >  I didn't create stacked review since I feel a standalone branch may be 
> > > sufficient.
> > 
> > 
> > @ChuanqiXu9, I'd prefer to review both patches at the same time. Otherwise 
> > we risk of missing some important details.
> 
> Got it. I can try to create a stacked review. But from I know about the 
> status quo stacked review now, it will require us to lost the current 
> contexnt...
> 
> And it will still be pretty valuable if you can test this with your internal 
> workloads, then may be we can find something pretty important in the high 
> level before going into the details. I've tested this in our local workloads, 
> and it looks good and the performance improvements remains. But I know our 
> uses about modules may be not so complex like yours.

I would just push the second commit here. It should be good enough. 

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] Diagnose reads from non-const global variables (PR #71919)

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

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/71919

>From 720d87366993568f47470761e4a20b071cf8c369 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 9 Nov 2023 15:45:05 +0100
Subject: [PATCH] [clang][Interp] Diagnose reads from non-const global
 variables

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp |  2 +-
 clang/lib/AST/Interp/Interp.cpp  | 48 +++-
 clang/lib/AST/Interp/Interp.h| 14 +++
 clang/lib/AST/Interp/Opcodes.td  |  1 +
 clang/test/AST/Interp/arrays.cpp | 32 
 clang/test/AST/Interp/cxx23.cpp  | 22 ---
 clang/test/AST/Interp/literals.cpp   | 27 +++--
 7 files changed, 126 insertions(+), 20 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e6b3097a80d8f7..edbcf4005aedbf 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2330,7 +2330,7 @@ bool ByteCodeExprGen::visitDecl(const VarDecl 
*VD) {
 auto GlobalIndex = P.getGlobal(VD);
 assert(GlobalIndex); // visitVarDecl() didn't return false.
 if (VarT) {
-  if (!this->emitGetGlobal(*VarT, *GlobalIndex, VD))
+  if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
 return false;
 } else {
   if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 21ea2503b94bff..e3cc2ba4fb3dd6 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -53,6 +53,21 @@ static bool Jf(InterpState &S, CodePtr &PC, int32_t Offset) {
   return true;
 }
 
+static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC,
+ const ValueDecl *VD) {
+  if (!S.getLangOpts().CPlusPlus)
+return;
+
+  const SourceInfo &Loc = S.Current->getSource(OpPC);
+  S.FFDiag(Loc,
+   VD->getType()->isIntegralOrEnumerationType()
+   ? diag::note_constexpr_ltor_non_const_int
+   : diag::note_constexpr_ltor_non_constexpr,
+   1)
+  << VD;
+  S.Note(VD->getLocation(), diag::note_declared_at);
+}
+
 static bool CheckActive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
 AccessKinds AK) {
   if (Ptr.isActive())
@@ -159,9 +174,7 @@ bool CheckExtern(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr) {
 
   if (!S.checkingPotentialConstantExpression() && S.getLangOpts().CPlusPlus) {
 const auto *VD = Ptr.getDeclDesc()->asValueDecl();
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.FFDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
-S.Note(VD->getLocation(), diag::note_declared_at);
+diagnoseNonConstVariable(S, OpPC, VD);
   }
   return false;
 }
@@ -204,6 +217,24 @@ bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer 
&Ptr,
   return true;
 }
 
+bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc) {
+  assert(Desc);
+  if (const auto *D = Desc->asValueDecl()) {
+if (const auto *VD = dyn_cast(D);
+VD && VD->hasGlobalStorage() &&
+!(VD->isConstexpr() || VD->getType().isConstQualified())) {
+  diagnoseNonConstVariable(S, OpPC, VD);
+  return false;
+}
+  }
+
+  return true;
+}
+
+static bool CheckConstant(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  return CheckConstant(S, OpPC, Ptr.getDeclDesc());
+}
+
 bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
   return !Ptr.isZero() && !Ptr.isDummy();
 }
@@ -292,6 +323,9 @@ bool CheckInitialized(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
   if (!CheckLive(S, OpPC, Ptr, AK_Read))
 return false;
+  if (!CheckConstant(S, OpPC, Ptr))
+return false;
+
   if (!CheckDummy(S, OpPC, Ptr))
 return false;
   if (!CheckExtern(S, OpPC, Ptr))
@@ -593,13 +627,7 @@ bool CheckDeclRef(InterpState &S, CodePtr OpPC, const 
DeclRefExpr *DR) {
 }
   } else if (const auto *VD = dyn_cast(D)) {
 if (!VD->getType().isConstQualified()) {
-  S.FFDiag(E,
-   VD->getType()->isIntegralOrEnumerationType()
-   ? diag::note_constexpr_ltor_non_const_int
-   : diag::note_constexpr_ltor_non_constexpr,
-   1)
-  << VD;
-  S.Note(VD->getLocation(), diag::note_declared_at) << 
VD->getSourceRange();
+  diagnoseNonConstVariable(S, OpPC, VD);
   return false;
 }
 
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index c05dea0cc55d3c..dbbc4c09ce42a1 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -77,6 +77,9 @@ bool CheckSubobject(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 /// Checks if a pointer points to const storage.
 bool CheckConst(InterpState &S, CodePtr OpPC, const Pointer &Ptr);
 
+/// Checks if th

[clang] [clang] Bounds checking on unclosed parentheses, brackets or braces in Expanded Tokens (PR #69849)

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

HighCommander4 wrote:

I poked at this a bit more. A few more notes:

 * Since the test case currently in the patch does not trigger the crash 
(without the fix), and it was not obvious to me what sort of call to 
`spelledForExpanded()` to formulate to trigger the crash, I instead formulated 
a test case in `DumpASTTests.cpp` that calls `dumpAST()` on the 
`TranslationUnitDecl` of a file containing the code `int main() {`. This does 
trigger the crash.
 * The crash occurs when dumping the `FunctionDecl` node for `main`. When 
dumping a node, `dumpAST()` 
[calls](https://searchfox.org/llvm/rev/fd1c156e5d6584684ce58c0536dca96cedcc41f0/clang-tools-extra/clangd/DumpAST.cpp#93)
 `Tokens.spelledForExpanded(Tokens.expandedTokens(SR))` where `SR` is the 
node's source range.
 * For this `FunctionDecl` node, the end location of its source range points to 
a `tok::eof` token.
* This comes from the end location of the function's `CompoundStmt` body, 
which is what the parser assigns in 
[Parser::ParseCompoundStatementBody()](https://searchfox.org/llvm/rev/fd1c156e5d6584684ce58c0536dca96cedcc41f0/clang/lib/Parse/ParseStmt.cpp#1292)
 in this situation.
 * The range of expanded tokens returned by `Tok.expandedTokens(SR)` thus 
includes as its last element the `tok::eof` token.
 * The 
[comment](https://searchfox.org/llvm/rev/fd1c156e5d6584684ce58c0536dca96cedcc41f0/clang/include/clang/Tooling/Syntax/Tokens.h#162)
 above `TokenBuffer` says "the expanded token stream has a `tok::eof` token at 
the end, the spelled tokens never store a 'eof' token".

I haven't dug into the implementation of `spelledForExpanded()` yet, but from 
the above it's looking to me like `spelledForExpanded()` is not expecting an 
input expanded token range that includes the `eof` token, but we are passing it 
one (and such a token range can legitimately arise from the source range of the 
AST node in cases of invalid code like this).

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


[clang] [clang] Bounds checking on unclosed parentheses, brackets or braces in Expanded Tokens (PR #69849)

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

HighCommander4 wrote:

Anyways, in a case like this, this preferable behaviour would be for 
`spelledForExpanded()` to return the spelled tokens covering `int main() {` 
(not including the `eof` token but including everything else), **not** nullopt.

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


[clang] [clang][Interp] Support __real/__imag on primitives (PR #75485)

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

tbaederr wrote:

Ping

https://github.com/llvm/llvm-project/pull/75485
___
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-08 Thread Frederik Carlier via cfe-commits


@@ -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 {

qmfrederik wrote:

On MinGW + objc2, `objc_exception_rethrow` is called; on other targets, 
`objc_exception_throw` is used (**re**throw vs throw).  I find it odd we were 
using `objc_exception_throw` to *re*throw an exception but decided to change it 
for MinGW+objc2 only.

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] 2c213c4 - [Clang] Fix reference to sve in rvv driver test comment. NFC

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

Author: Luke Lau
Date: 2024-01-08T16:04:33+07:00
New Revision: 2c213c45046b78eac48809b013e7a80099607ebb

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

LOG: [Clang] Fix reference to sve in rvv driver test comment. NFC

Added: 


Modified: 
clang/test/Driver/riscv-rvv-vector-bits.c

Removed: 




diff  --git a/clang/test/Driver/riscv-rvv-vector-bits.c 
b/clang/test/Driver/riscv-rvv-vector-bits.c
index e92b66c972daf3..24af5f0c73c6ef 100644
--- a/clang/test/Driver/riscv-rvv-vector-bits.c
+++ b/clang/test/Driver/riscv-rvv-vector-bits.c
@@ -44,7 +44,7 @@
 
 // CHECK-BAD-VALUE-ERROR: error: unsupported argument '{{.*}}' to option 
'-mrvv-vector-bits='
 
-// Error if using attribute without -msve-vector-bits= or if using 
-msve-vector-bits=+ syntax
+// Error if using attribute without -mrvv-vector-bits= or if using 
-mrvv-vector-bits=+ syntax
 // 
-
 // RUN: not %clang -c %s -o /dev/null -target riscv64-linux-gnu \
 // RUN:  -march=rv64gc_zve64x 2>&1 | FileCheck 
--check-prefix=CHECK-NO-FLAG-ERROR %s



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


[clang] Improve modeling of 'getcwd' in the StdLibraryFunctionsChecker (PR #77040)

2024-01-08 Thread Balázs Kéri via cfe-commits


@@ -2519,12 +2519,17 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 addToFunctionSummaryMap(
 "getcwd", Signature(ArgTypes{CharPtrTy, SizeTy}, RetType{CharPtrTy}),
 Summary(NoEvalCall)
-.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+.Case({ArgumentCondition(1, WithinRange, Range(1, SizeMax)),
+   ReturnValueCondition(BO_EQ, ArgNo(0))},
   ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ArgumentCondition(1, WithinRange, SingleValue(0))},

balazske wrote:

```suggestion
.Case({ArgumentCondition(1, WithinRange, SingleValue(0)),
   IsNull(Ret)},
  ErrnoNEZeroIrrelevant,
  "Assuming that argument 'size' is 0")
```

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


[clang] Improve modeling of 'getcwd' in the StdLibraryFunctionsChecker (PR #77040)

2024-01-08 Thread Balázs Kéri via cfe-commits


@@ -2519,12 +2519,17 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 addToFunctionSummaryMap(
 "getcwd", Signature(ArgTypes{CharPtrTy, SizeTy}, RetType{CharPtrTy}),
 Summary(NoEvalCall)
-.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+.Case({ArgumentCondition(1, WithinRange, Range(1, SizeMax)),
+   ReturnValueCondition(BO_EQ, ArgNo(0))},
   ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ArgumentCondition(1, WithinRange, SingleValue(0))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)

balazske wrote:

```suggestion
.Case({ArgumentCondition(1, WithinRange, Range(1, SizeMax)), 
IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
```

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


[clang] [clang-format] Fix crash involving array designators and dangling comma (PR #77045)

2024-01-08 Thread Owen Pan via cfe-commits


@@ -1444,16 +1444,26 @@ WhitespaceManager::CellDescriptions 
WhitespaceManager::getCells(unsigned Start,
   } else if (C.Tok->is(tok::comma)) {
 if (!Cells.empty())
   Cells.back().EndIndex = i;
-if (C.Tok->getNextNonComment()->isNot(tok::r_brace)) // dangling comma
+
+if (const auto *Next = C.Tok->getNextNonComment();
+Next && Next->isNot(tok::r_brace)) { // Dangling comma.
   ++Cell;
+}
   }
 } else if (Depth == 1) {
   if (C.Tok == MatchingParen) {
 if (!Cells.empty())
   Cells.back().EndIndex = i;
 Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr});
-CellCounts.push_back(C.Tok->Previous->isNot(tok::comma) ? Cell + 1
-: Cell);
+CellCounts.push_back(
+C.Tok->Previous->isNot(tok::comma) &&
+// When dealing with C array designators. There is a
+// possibility of some nested array not having an `=`.
+// When this happens we make the cells non rectangular,
+// avoiding an access out of bound later on.
+MatchingParen->MatchingParen->Previous->isNot(tok::equal)

owenca wrote:

This seems a little hacky. We should probably investigate a bit more to find 
the root cause.

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


[clang] [clang][Interp] Fix diagnosing non-const variables pre-C++11 (PR #76718)

2024-01-08 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/76718

>From 64039561ffa3bad6e5a0c98c729478e59777e782 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 9 Nov 2023 15:45:05 +0100
Subject: [PATCH 1/2] [clang][Interp] Diagnose reads from non-const global
 variables

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp |  2 +-
 clang/lib/AST/Interp/Interp.cpp  | 47 +++-
 clang/lib/AST/Interp/Interp.h| 14 +++
 clang/lib/AST/Interp/Opcodes.td  |  1 +
 clang/test/AST/Interp/arrays.cpp | 32 
 clang/test/AST/Interp/cxx23.cpp  | 22 ---
 clang/test/AST/Interp/literals.cpp   | 27 --
 7 files changed, 125 insertions(+), 20 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e6b3097a80d8f7..edbcf4005aedbf 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2330,7 +2330,7 @@ bool ByteCodeExprGen::visitDecl(const VarDecl 
*VD) {
 auto GlobalIndex = P.getGlobal(VD);
 assert(GlobalIndex); // visitVarDecl() didn't return false.
 if (VarT) {
-  if (!this->emitGetGlobal(*VarT, *GlobalIndex, VD))
+  if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
 return false;
 } else {
   if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 21ea2503b94bff..6d4e45dceeacfa 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -53,6 +53,21 @@ static bool Jf(InterpState &S, CodePtr &PC, int32_t Offset) {
   return true;
 }
 
+static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC,
+ const ValueDecl *VD) {
+  if (!S.getLangOpts().CPlusPlus)
+return;
+
+  const SourceInfo &Loc = S.Current->getSource(OpPC);
+  S.FFDiag(Loc,
+   VD->getType()->isIntegralOrEnumerationType()
+   ? diag::note_constexpr_ltor_non_const_int
+   : diag::note_constexpr_ltor_non_constexpr,
+   1)
+  << VD;
+  S.Note(VD->getLocation(), diag::note_declared_at);
+}
+
 static bool CheckActive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
 AccessKinds AK) {
   if (Ptr.isActive())
@@ -159,9 +174,7 @@ bool CheckExtern(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr) {
 
   if (!S.checkingPotentialConstantExpression() && S.getLangOpts().CPlusPlus) {
 const auto *VD = Ptr.getDeclDesc()->asValueDecl();
-const SourceInfo &Loc = S.Current->getSource(OpPC);
-S.FFDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
-S.Note(VD->getLocation(), diag::note_declared_at);
+diagnoseNonConstVariable(S, OpPC, VD);
   }
   return false;
 }
@@ -204,6 +217,24 @@ bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer 
&Ptr,
   return true;
 }
 
+bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc) {
+  assert(Desc);
+  if (const auto *D = Desc->asValueDecl()) {
+if (const auto *VD = dyn_cast(D);
+VD && VD->hasGlobalStorage() &&
+!(VD->isConstexpr() || VD->getType().isConstQualified())) {
+  diagnoseNonConstVariable(S, OpPC, VD);
+  return false;
+}
+  }
+
+  return true;
+}
+
+static bool CheckConstant(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  return CheckConstant(S, OpPC, Ptr.getDeclDesc());
+}
+
 bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
   return !Ptr.isZero() && !Ptr.isDummy();
 }
@@ -292,6 +323,8 @@ bool CheckInitialized(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
   if (!CheckLive(S, OpPC, Ptr, AK_Read))
 return false;
+  if (!CheckConstant(S, OpPC, Ptr))
+return false;
   if (!CheckDummy(S, OpPC, Ptr))
 return false;
   if (!CheckExtern(S, OpPC, Ptr))
@@ -593,13 +626,7 @@ bool CheckDeclRef(InterpState &S, CodePtr OpPC, const 
DeclRefExpr *DR) {
 }
   } else if (const auto *VD = dyn_cast(D)) {
 if (!VD->getType().isConstQualified()) {
-  S.FFDiag(E,
-   VD->getType()->isIntegralOrEnumerationType()
-   ? diag::note_constexpr_ltor_non_const_int
-   : diag::note_constexpr_ltor_non_constexpr,
-   1)
-  << VD;
-  S.Note(VD->getLocation(), diag::note_declared_at) << 
VD->getSourceRange();
+  diagnoseNonConstVariable(S, OpPC, VD);
   return false;
 }
 
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index c05dea0cc55d3c..dbbc4c09ce42a1 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -77,6 +77,9 @@ bool CheckSubobject(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 /// Checks if a pointer points to const storage.
 bool CheckConst(InterpState &S, 

[clang] [clang][Interp] Add inline descriptor to global variables (PR #72892)

2024-01-08 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?B=C3=A4der?= ,
Timm =?utf-8?q?B=C3=A4der?= 
Message-ID:
In-Reply-To: 


tbaederr wrote:

Ping

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


[clang] Improve modeling of 'getcwd' in the StdLibraryFunctionsChecker (PR #77040)

2024-01-08 Thread Balázs Kéri via cfe-commits


@@ -75,13 +75,16 @@ void errno_mkdtemp(char *template) {
   }
 }
 
-void errno_getcwd(char *Buf, size_t sz) {
-  char *Path = getcwd(Buf, sz);
-  if (Path == NULL) {
-clang_analyzer_eval(errno != 0);  // expected-warning{{TRUE}}
-if (errno) {} // no warning
+void errno_getcwd_general(char *Buf, size_t Sz) {
+  char *Path = getcwd(Buf, Sz);
+  if (Sz == 0) {
+clang_analyzer_eval(errno != 0);  // expected-warning{{TRUE}}

balazske wrote:

clang_analyzer_eval(Path == NULL); // expected-warning{{TRUE}}

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


[clang] [clang-format] Break after string literals with trailing line breaks (PR #76795)

2024-01-08 Thread kadir çetinkaya via cfe-commits


@@ -5151,6 +5151,14 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
+  // FIXME: Breaking after newlines seems useful in general. Turn this into an
+  // option and recognize more cases like endl etc, and break independent of
+  // what comes after operator lessless.
+  if (Right.is(tok::lessless) && Right.Next &&
+  Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) &&
+  Left.TokenText.ends_with("\\n\"")) {

kadircet wrote:

> We can also handle \n and endl now. For example:

yes, but that'll be "new" behavior, and even if we do that, i'd rather do that 
in a separate patch that can be reviewed/reverted on it's own.

as mentioned, this is mostly to restore some of the "incidental" behavior that 
was relied on by codebases in the wild. so that changes in the new clang-format 
release will be minimal.

https://github.com/llvm/llvm-project/pull/76795
___
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-08 Thread Utkarsh Saxena 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;

usx95 wrote:

This is a false positive involving lambda with no capture list. The following 
code does not have lifetime issue but will be warned otherwise
```
auto x = []() -> coro { co_return 0; }();
```

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-08 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 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-08 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 curious why it is. Have you taken a look on that?

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] [clang] Fix a crash when referencing the result if the overload fails (PR #77288)

2024-01-08 Thread Haojian Wu via cfe-commits

https://github.com/hokein created 
https://github.com/llvm/llvm-project/pull/77288

after 20a05677f9394d4bc9467fe7bc93a4ebd3aeda61

If the overload fails, the `Best` might point to the `end()`, referencing it 
leads to asan crashes.

>From 5061fbfe8c8840dc49c12bb533fa5d537efc8333 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Mon, 8 Jan 2024 10:25:40 +0100
Subject: [PATCH] [clang] Fix a crash when referencing the result if the
 overload fails after 20a05677f9394d4bc9467fe7bc93a4ebd3aeda61

If the overload fails, the Best might point to the `end()`, referencing
it leads to asan crashes.
---
 clang/lib/Sema/SemaOverload.cpp | 23 ---
 1 file changed, 12 insertions(+), 11 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 9fb767101e1eb7..8e3a2d1288079b 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -13994,21 +13994,22 @@ ExprResult Sema::BuildOverloadedCallExpr(Scope *S, 
Expr *Fn,
   OverloadCandidateSet::iterator Best;
   OverloadingResult OverloadResult =
   CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
-  FunctionDecl *FDecl = Best->Function;
 
   // Model the case with a call to a templated function whose definition
   // encloses the call and whose return type contains a placeholder type as if
   // the UnresolvedLookupExpr was type-dependent.
-  if (OverloadResult == OR_Success && FDecl &&
-  FDecl->isTemplateInstantiation() &&
-  FDecl->getReturnType()->isUndeducedType()) {
-if (auto TP = FDecl->getTemplateInstantiationPattern(false)) {
-  if (TP->willHaveBody()) {
-CallExpr *CE =
-CallExpr::Create(Context, Fn, Args, Context.DependentTy, 
VK_PRValue,
- RParenLoc, CurFPFeatureOverrides());
-result = CE;
-return result;
+  if (OverloadResult == OR_Success) {
+FunctionDecl *FDecl = Best->Function;
+if (FDecl && FDecl->isTemplateInstantiation() &&
+FDecl->getReturnType()->isUndeducedType()) {
+  if (auto TP = FDecl->getTemplateInstantiationPattern(false)) {
+if (TP->willHaveBody()) {
+  CallExpr *CE =
+  CallExpr::Create(Context, Fn, Args, Context.DependentTy,
+   VK_PRValue, RParenLoc, CurFPFeatureOverrides());
+  result = CE;
+  return result;
+}
   }
 }
   }

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


[clang] [clang] Fix a crash when referencing the result if the overload fails (PR #77288)

2024-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Haojian Wu (hokein)


Changes

after 20a05677f9394d4bc9467fe7bc93a4ebd3aeda61

If the overload fails, the `Best` might point to the `end()`, referencing it 
leads to asan crashes.

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaOverload.cpp (+12-11) 


``diff
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 9fb767101e1eb7..8e3a2d1288079b 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -13994,21 +13994,22 @@ ExprResult Sema::BuildOverloadedCallExpr(Scope *S, 
Expr *Fn,
   OverloadCandidateSet::iterator Best;
   OverloadingResult OverloadResult =
   CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
-  FunctionDecl *FDecl = Best->Function;
 
   // Model the case with a call to a templated function whose definition
   // encloses the call and whose return type contains a placeholder type as if
   // the UnresolvedLookupExpr was type-dependent.
-  if (OverloadResult == OR_Success && FDecl &&
-  FDecl->isTemplateInstantiation() &&
-  FDecl->getReturnType()->isUndeducedType()) {
-if (auto TP = FDecl->getTemplateInstantiationPattern(false)) {
-  if (TP->willHaveBody()) {
-CallExpr *CE =
-CallExpr::Create(Context, Fn, Args, Context.DependentTy, 
VK_PRValue,
- RParenLoc, CurFPFeatureOverrides());
-result = CE;
-return result;
+  if (OverloadResult == OR_Success) {
+FunctionDecl *FDecl = Best->Function;
+if (FDecl && FDecl->isTemplateInstantiation() &&
+FDecl->getReturnType()->isUndeducedType()) {
+  if (auto TP = FDecl->getTemplateInstantiationPattern(false)) {
+if (TP->willHaveBody()) {
+  CallExpr *CE =
+  CallExpr::Create(Context, Fn, Args, Context.DependentTy,
+   VK_PRValue, RParenLoc, CurFPFeatureOverrides());
+  result = CE;
+  return result;
+}
   }
 }
   }

``




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


[clang] 442f67c - [Sema][test] Split format attribute test cases for _Float16

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

Author: Lu Haocong
Date: 2024-01-08T17:24:51+08:00
New Revision: 442f67c8702a792a135d61765909b732827d6bf2

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

LOG: [Sema][test] Split format attribute test cases for _Float16

Fixes https://github.com/llvm/llvm-project/pull/74439#issuecomment-1880528376

Added: 
clang/test/Sema/attr-format-Float16.c
clang/test/SemaCXX/attr-format-Float16.cpp

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

Removed: 




diff  --git a/clang/test/Sema/attr-format-Float16.c 
b/clang/test/Sema/attr-format-Float16.c
new file mode 100644
index 00..6c3dfe14cec3c7
--- /dev/null
+++ b/clang/test/Sema/attr-format-Float16.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -triple i686-linux-pc -target-feature 
+sse2 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple x86_64-linux-pc %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple spir-unknown-unknown %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple armv7a-linux-gnu %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple aarch64-linux-gnu %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple riscv32 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple riscv64 %s
+
+void a(const char *a, ...) __attribute__((format(printf, 1, 2)));// 
no-error
+
+void b(char *a, _Float16 b) __attribute__((format(printf, 1, 2))); // 
expected-warning {{GCC requires a function with the 'format' attribute to be 
variadic}}
+
+void call_no_default_promotion(void) {
+  a("%f", (_Float16)1.0); // expected-warning{{format specifies type 'double' 
but the argument has type '_Float16'}}
+  b("%f", (_Float16)1.0); // expected-warning{{format specifies type 'double' 
but the argument has type '_Float16'}}
+}

diff  --git a/clang/test/Sema/attr-format.c b/clang/test/Sema/attr-format.c
index bdfd8425c4e9a5..1f4c864d4f78bd 100644
--- a/clang/test/Sema/attr-format.c
+++ b/clang/test/Sema/attr-format.c
@@ -16,8 +16,6 @@ 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}}
 
@@ -95,11 +93,6 @@ 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-Float16.cpp 
b/clang/test/SemaCXX/attr-format-Float16.cpp
new file mode 100644
index 00..c61611d6b6a049
--- /dev/null
+++ b/clang/test/SemaCXX/attr-format-Float16.cpp
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -triple i686-linux-pc -target-feature 
+sse2 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple x86_64-linux-pc %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple spir-unknown-unknown %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple armv7a-linux-gnu %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple aarch64-linux-gnu %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple riscv32 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple riscv64 %s
+
+template 
+__attribute__((format(printf, 1, 2)))
+void format(const char *fmt, Args &&...args); // expected-warning{{GCC 
requires a function with the 'format' attribute to be variadic}}
+
+template
+__attribute__((format(scanf, 1, 2)))
+int scan(const char *fmt, Args &&...args); // expected-warning{{GCC requires a 
function with the 'format' attribute to be variadic}}
+
+void do_format() {
+  format("%f", (_Float16)123.f); // expected-warning{{format specifies type 
'double' but the argument has type '_Float16'}}
+
+  _Float16 Float16;
+  scan("%f", &Float16); // expected-warning{{format specifies type 'float *' 
but the argument has type '_Float16 *'}}
+  scan("%lf", &Float16); // expected-warning{{format specifies

[libcxx] [clang] [flang] [llvm] [mlir] [WebAssembly] Correctly consider signext/zext arg flags at function declaration (PR #77281)

2024-01-08 Thread Juneyoung Lee via cfe-commits

https://github.com/aqjune updated 
https://github.com/llvm/llvm-project/pull/77281

>From 1bbfe05bc50e1fbdb207f21a178b6fc7ab24e8cf Mon Sep 17 00:00:00 2001
From: Juneyoung Lee 
Date: Mon, 8 Jan 2024 02:01:41 -0600
Subject: [PATCH] [WebAssembly] Correctly consider signext/zext arg flags at
 function declaration

---
 .../WebAssembly/WebAssemblyFastISel.cpp   |   6 +-
 .../WebAssembly/signext-zeroext-callsite.ll   | 125 ++
 2 files changed, 129 insertions(+), 2 deletions(-)
 create mode 100644 llvm/test/CodeGen/WebAssembly/signext-zeroext-callsite.ll

diff --git a/llvm/lib/Target/WebAssembly/WebAssemblyFastISel.cpp 
b/llvm/lib/Target/WebAssembly/WebAssemblyFastISel.cpp
index 15dc44a0439573..80159974ecd691 100644
--- a/llvm/lib/Target/WebAssembly/WebAssemblyFastISel.cpp
+++ b/llvm/lib/Target/WebAssembly/WebAssemblyFastISel.cpp
@@ -839,9 +839,11 @@ bool WebAssemblyFastISel::selectCall(const Instruction *I) 
{
 
 unsigned Reg;
 
-if (Attrs.hasParamAttr(I, Attribute::SExt))
+if (Attrs.hasParamAttr(I, Attribute::SExt) ||
+(IsDirect && Func->hasParamAttribute(I, Attribute::SExt)))
   Reg = getRegForSignedValue(V);
-else if (Attrs.hasParamAttr(I, Attribute::ZExt))
+else if (Attrs.hasParamAttr(I, Attribute::ZExt) ||
+ (IsDirect && Func->hasParamAttribute(I, Attribute::ZExt)))
   Reg = getRegForUnsignedValue(V);
 else
   Reg = getRegForValue(V);
diff --git a/llvm/test/CodeGen/WebAssembly/signext-zeroext-callsite.ll 
b/llvm/test/CodeGen/WebAssembly/signext-zeroext-callsite.ll
new file mode 100644
index 00..02ca578716dc98
--- /dev/null
+++ b/llvm/test/CodeGen/WebAssembly/signext-zeroext-callsite.ll
@@ -0,0 +1,125 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -O0 | FileCheck %s
+
+target triple = "wasm32-unknown-unknown"
+
+
+declare i32 @foo(i1 signext noundef, i32 noundef)
+
+; callsite_signext and callsite_nosignext must emit equivalent codes
+
+define i32 @callsite_nosignext() {
+; CHECK-LABEL: callsite_nosignext:
+; CHECK: .functype callsite_nosignext () -> (i32)
+; CHECK-NEXT:.local i32, i32, i32, i32, i32, i32
+; CHECK-NEXT:  # %bb.0: # %start
+; CHECK-NEXT:i32.const 1
+; CHECK-NEXT:local.set 0
+; CHECK-NEXT:i32.const 0
+; CHECK-NEXT:local.set 1
+; CHECK-NEXT:i32.const 31
+; CHECK-NEXT:local.set 2
+; CHECK-NEXT:local.get 0
+; CHECK-NEXT:local.get 2
+; CHECK-NEXT:i32.shl
+; CHECK-NEXT:local.set 3
+; CHECK-NEXT:local.get 3
+; CHECK-NEXT:local.get 2
+; CHECK-NEXT:i32.shr_s
+; CHECK-NEXT:local.set 4
+; CHECK-NEXT:local.get 4
+; CHECK-NEXT:local.get 1
+; CHECK-NEXT:call foo
+; CHECK-NEXT:local.set 5
+; CHECK-NEXT:local.get 5
+; CHECK-NEXT:return
+start:
+  %0 = call i32 @foo(i1 1, i32 0)
+  ret i32 %0
+}
+
+define i32 @callsite_signext() {
+; CHECK-LABEL: callsite_signext:
+; CHECK: .functype callsite_signext () -> (i32)
+; CHECK-NEXT:.local i32, i32, i32, i32, i32, i32
+; CHECK-NEXT:  # %bb.0: # %start
+; CHECK-NEXT:i32.const 1
+; CHECK-NEXT:local.set 0
+; CHECK-NEXT:i32.const 0
+; CHECK-NEXT:local.set 1
+; CHECK-NEXT:i32.const 31
+; CHECK-NEXT:local.set 2
+; CHECK-NEXT:local.get 0
+; CHECK-NEXT:local.get 2
+; CHECK-NEXT:i32.shl
+; CHECK-NEXT:local.set 3
+; CHECK-NEXT:local.get 3
+; CHECK-NEXT:local.get 2
+; CHECK-NEXT:i32.shr_s
+; CHECK-NEXT:local.set 4
+; CHECK-NEXT:local.get 4
+; CHECK-NEXT:local.get 1
+; CHECK-NEXT:call foo
+; CHECK-NEXT:local.set 5
+; CHECK-NEXT:local.get 5
+; CHECK-NEXT:return
+start:
+  %0 = call i32 @foo(i1 signext 1, i32 0)
+  ret i32 %0
+}
+
+declare i32 @foo2(i1 zeroext noundef, i32 noundef)
+
+; callsite_zeroext and callsite_nozeroext must emit equivalent codes
+
+define i32 @callsite_nozeroext() {
+; CHECK-LABEL: callsite_nozeroext:
+; CHECK: .functype callsite_nozeroext () -> (i32)
+; CHECK-NEXT:.local i32, i32, i32, i32, i32
+; CHECK-NEXT:  # %bb.0: # %start
+; CHECK-NEXT:i32.const 1
+; CHECK-NEXT:local.set 0
+; CHECK-NEXT:i32.const 0
+; CHECK-NEXT:local.set 1
+; CHECK-NEXT:i32.const 1
+; CHECK-NEXT:local.set 2
+; CHECK-NEXT:local.get 0
+; CHECK-NEXT:local.get 2
+; CHECK-NEXT:i32.and
+; CHECK-NEXT:local.set 3
+; CHECK-NEXT:local.get 3
+; CHECK-NEXT:local.get 1
+; CHECK-NEXT:call foo2
+; CHECK-NEXT:local.set 4
+; CHECK-NEXT:local.get 4
+; CHECK-NEXT:return
+start:
+  %0 = call i32 @foo2(i1 1, i32 0)
+  ret i32 %0
+}
+
+define i32 @callsite_zeroext() {
+; CHECK-LABEL: callsite_zeroext:
+; CHECK: .functype callsite_zeroext () -> (i32)
+; CHECK-NEXT:.local i32, i32, i32, i32, i32
+; CHECK-NEXT:  # %bb.0: # %start
+; CHECK-NEXT:i32.const 1
+; CHECK-NEXT:local.set 0
+; CHECK-NEXT:i32.const 0
+; CHECK-NEXT:local.set 1
+; CHECK-NEXT:i32.const 1
+; CHECK-NEXT:local

[lld] [llvm] [compiler-rt] [libc] [clang] [flang] [libunwind] [clang-tools-extra] [libcxx] [lldb] [GVN] Disable GVN PRE on target hasBranchDivergence (PR #77069)

2024-01-08 Thread via cfe-commits

https://github.com/fengfeng09 updated 
https://github.com/llvm/llvm-project/pull/77069

>From 17a9072758d9f443d0f7bca8862fec5a793c3dba Mon Sep 17 00:00:00 2001
From: "feng.feng" 
Date: Mon, 11 Dec 2023 15:14:32 +0800
Subject: [PATCH] [GVN] Disable GVN PRE on target hasBranchDivergence

Signed-off-by: feng.feng 
---
 llvm/lib/Transforms/Scalar/GVN.cpp | 5 +
 1 file changed, 5 insertions(+)

diff --git a/llvm/lib/Transforms/Scalar/GVN.cpp 
b/llvm/lib/Transforms/Scalar/GVN.cpp
index e36578f3de7ac4..777dec04faf9f6 100644
--- a/llvm/lib/Transforms/Scalar/GVN.cpp
+++ b/llvm/lib/Transforms/Scalar/GVN.cpp
@@ -41,6 +41,7 @@
 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
 #include "llvm/Analysis/PHITransAddr.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -750,6 +751,10 @@ bool GVNPass::isMemDepEnabled() const {
 }
 
 PreservedAnalyses GVNPass::run(Function &F, FunctionAnalysisManager &AM) {
+  // Disable PRE on GPU.
+  auto &TTI = AM.getResult(F);
+  if (TTI.hasBranchDivergence())
+GVNEnablePRE = false;
   // FIXME: The order of evaluation of these 'getResult' calls is very
   // significant! Re-ordering these variables will cause GVN when run alone to
   // be less effective! We should fix memdep and basic-aa to not exhibit this

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


[clang] [clang][AST] Invalidate DecompositionDecl if it has invalid initializer. (PR #72428)

2024-01-08 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/72428

>From 662be3d00eed883db6b1babe489b981847e9b907 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Wed, 15 Nov 2023 20:31:12 +0100
Subject: [PATCH 1/3] [clang][AST] Invalidate DecompositionDecl if it has
 invalid initializer.

Fix #67495, #72198
---
 clang/lib/Sema/SemaDecl.cpp |  9 +
 clang/test/AST/ast-dump-invalid-initialized.cpp | 15 ++-
 2 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 8e46c4984d93dc9..f9fa9dc53cb2b47 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -13570,6 +13570,15 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr 
*Init, bool DirectInit) {
   CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
   if (RecoveryExpr.get())
 VDecl->setInit(RecoveryExpr.get());
+  // In general, for error recovery purposes, the initalizer doesn't play
+  // part in the valid bit of the declaration. There are a few exceptions:
+  //  1) if the var decl has a deduced auto type, and the type cannot be
+  // deduced by an invalid initializer;
+  //  2) if the var decl is decompsition decl with a concrete type (e.g.
+  //`int [a, b] = 1;`), and the initializer is invalid;
+  // Case 1) is already handled earlier in this function.
+  if (llvm::isa(VDecl)) // Case 2)
+VDecl->setInvalidDecl();
   return;
 }
 
diff --git a/clang/test/AST/ast-dump-invalid-initialized.cpp 
b/clang/test/AST/ast-dump-invalid-initialized.cpp
index 1c374ae716a9db5..a71a02f0f60039e 100644
--- a/clang/test/AST/ast-dump-invalid-initialized.cpp
+++ b/clang/test/AST/ast-dump-invalid-initialized.cpp
@@ -24,4 +24,17 @@ void test() {
   auto b4 = A(1);
   // CHECK: `-VarDecl {{.*}} invalid b5 'auto'
   auto b5 = A{1};
-}
\ No newline at end of file
+}
+
+void pr72198() {
+  // CHECK: DecompositionDecl {{.*}} invalid 'int'
+  int [_, b] = {0, 0};
+  [b]{};
+}
+
+int get_point();
+void pr67495() {
+  // CHECK: DecompositionDecl {{.*}} invalid 'int &'
+  auto& [x, y] = get_point();
+  [x, y] {};
+}

>From 851aa492d5e241abd9d4d621b84c137164845890 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 17 Nov 2023 10:54:33 +0100
Subject: [PATCH 2/3] Address comments.

---
 clang/lib/Sema/SemaDecl.cpp | 6 +++---
 clang/test/AST/ast-dump-invalid-initialized.cpp | 6 --
 2 files changed, 7 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index f9fa9dc53cb2b47..7c88731bebc9f2e 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -13574,9 +13574,9 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr 
*Init, bool DirectInit) {
   // part in the valid bit of the declaration. There are a few exceptions:
   //  1) if the var decl has a deduced auto type, and the type cannot be
   // deduced by an invalid initializer;
-  //  2) if the var decl is decompsition decl with a concrete type (e.g.
-  //`int [a, b] = 1;`), and the initializer is invalid;
-  // Case 1) is already handled earlier in this function.
+  //  2) if the var decl is decompsition decl with a non-deduced type, and
+  // the initialization fails (e.g. `int [a] = {1, 2};`);
+  // Case 1) was already handled elsewhere.
   if (llvm::isa(VDecl)) // Case 2)
 VDecl->setInvalidDecl();
   return;
diff --git a/clang/test/AST/ast-dump-invalid-initialized.cpp 
b/clang/test/AST/ast-dump-invalid-initialized.cpp
index a71a02f0f60039e..7fcbc41a7be4001 100644
--- a/clang/test/AST/ast-dump-invalid-initialized.cpp
+++ b/clang/test/AST/ast-dump-invalid-initialized.cpp
@@ -26,15 +26,17 @@ void test() {
   auto b5 = A{1};
 }
 
-void pr72198() {
+void GH72198() {
   // CHECK: DecompositionDecl {{.*}} invalid 'int'
   int [_, b] = {0, 0};
   [b]{};
 }
 
+namespace GH67495 {
 int get_point();
-void pr67495() {
+void f() {
   // CHECK: DecompositionDecl {{.*}} invalid 'int &'
   auto& [x, y] = get_point();
   [x, y] {};
 }
+}

>From 9eb93e95664b70092a56cf5e1a06c9d36c75ae3a Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 19 Dec 2023 10:11:50 +0100
Subject: [PATCH 3/3] Add release note.

---
 clang/docs/ReleaseNotes.rst | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c9b577bd549b1e2..da79b0a2f63fbed 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -696,6 +696,9 @@ Bug Fixes in This Version
 - Clang now accepts recursive non-dependent calls to functions with deduced
   return type.
   Fixes (`#71015 `_)
+- Fix crashes when using the binding decl from an invalid structured binding.
+  Fixes (`#67495 `_) and
+  (`#72198 

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

2024-01-08 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 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] [clang][AST] Invalidate DecompositionDecl if it has invalid initializer. (PR #72428)

2024-01-08 Thread Haojian Wu via cfe-commits

hokein wrote:

Friendly ping.

https://github.com/llvm/llvm-project/pull/72428
___
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-08 Thread David Chisnall via cfe-commits


@@ -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 {

davidchisnall wrote:

Ah, sorry, I didn't see the `re` bit.

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] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-08 Thread Utkarsh Saxena 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;

usx95 wrote:

I can explain. The lambda call operator is a coroutine and receives a lambda 
object as an implicit `this` param.
This lambda object would not be used or read in the coroutine body (as there is 
no capture list). But this analysis would still consider the object argument to 
be lifetime bound to the return object and would flag it the return object 
outlives the lambda object (which is true in the mentioned example).

Coro_lifetimebound, by design, has false positives because of it strictness. It 
considers all args to be lifetimebound but it might not be true in practice, 
for eg. if the arg is not used by the coro or used before first suspend.
Lambda with no capture list allows us to recognize one such instance where it 
can be proven to be a false positive always.

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-08 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 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] [clang-format] Break after string literals with trailing line breaks (PR #76795)

2024-01-08 Thread Owen Pan via cfe-commits

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


https://github.com/llvm/llvm-project/pull/76795
___
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-08 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:

Thanks for the explanation. Got it. Then it looks an optimization for lambdas 
for me.

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-08 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][coro_lifetimebound] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-08 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 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][coro_lifetimebound] Detect lifetime issues with lambda captures (PR #77066)

2024-01-08 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 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] [Serialization] Load Specializations Lazily (1/2) (PR #76774)

2024-01-08 Thread Vassil Vassilev 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); }

vgvassilev wrote:

If the example of @hahnjo works, perhaps a FIXME referring to this discussion 
should be sufficient and we can revisit the issue once we have an example that 
breaks. 

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


[llvm] [clang] [RISCV] CodeGen of RVE and ilp32e/lp64e ABIs (PR #76777)

2024-01-08 Thread Nemanja Ivanovic via cfe-commits

nemanjai wrote:

> @nemanjai I'm curious if you have an interest / need to support RVE or not?

I most certainly do. Thank you for alerting me to this PR.

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


[clang] 27f5479 - [clang-format] Break after string literals with trailing line breaks (#76795)

2024-01-08 Thread via cfe-commits

Author: kadir çetinkaya
Date: 2024-01-08T11:11:02+01:00
New Revision: 27f547968cce89d4706ae2b27a0c15254d1670ee

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

LOG: [clang-format] Break after string literals with trailing line breaks 
(#76795)

This restores a subset of functionality that was forego in
d68826dfbd987377ef6771d40c1d984f09ee3b9e.

Streaming multiple string literals is rare enough in practice, hence
that change makes sense in general. But it seems people were
incidentally relying on this for having line breaks after string
literals that ended with `\n`.

This patch tries to restore that behavior to prevent regressions in the
upcoming LLVM release, until we can implement some configuration based
approach as proposed in https://github.com/llvm/llvm-project/pull/69859.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3ac3aa3c5e3a22..8b43438c72dfe1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -5151,6 +5151,14 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
+  // FIXME: Breaking after newlines seems useful in general. Turn this into an
+  // option and recognize more cases like endl etc, and break independent of
+  // what comes after operator lessless.
+  if (Right.is(tok::lessless) && Right.Next &&
+  Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) &&
+  Left.TokenText.ends_with("\\n\"")) {
+return true;
+  }
   if (Right.is(TT_RequiresClause)) {
 switch (Style.RequiresClausePosition) {
 case FormatStyle::RCPS_OwnLine:

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 881993ede17c3d..25ef5c680af862 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26708,6 +26708,8 @@ TEST_F(FormatTest, PPBranchesInBracedInit) {
 
 TEST_F(FormatTest, StreamOutputOperator) {
   verifyFormat("std::cout << \"foo\" << \"bar\" << baz;");
+  verifyFormat("std::cout << \"foo\\n\"\n"
+   "  << \"bar\";");
 }
 
 TEST_F(FormatTest, BreakAdjacentStringLiterals) {

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 2cafc0438ffb46..decc0785c5cde7 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2499,6 +2499,15 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
   EXPECT_BRACE_KIND(Tokens[6], BK_Block);
 }
 
+TEST_F(TokenAnnotatorTest, StreamOperator) {
+  auto Tokens = annotate("\"foo\\n\" << aux << \"foo\\n\" << \"foo\";");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_FALSE(Tokens[1]->MustBreakBefore);
+  EXPECT_FALSE(Tokens[3]->MustBreakBefore);
+  // Only break between string literals if the former ends with \n.
+  EXPECT_TRUE(Tokens[5]->MustBreakBefore);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang



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


[clang] [clang-format] Break after string literals with trailing line breaks (PR #76795)

2024-01-08 Thread kadir çetinkaya via cfe-commits

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


[clang] [clang][Interp] Implement ComplexToReal casts (PR #77294)

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

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/77294

Add a new emitComplexReal() helper function and use that for the new casts as 
well as the old __real implementation.

>From 1d657e65f69f3b6d4be3ce08c5f39f73d8fc04b4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Mon, 8 Jan 2024 11:14:41 +0100
Subject: [PATCH] [clang][Interp] Implement ComplexToReal casts

Add a new emitComplexReal() helper function and use that for the
new casts as well as the old __real implementation.
---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 45 
 clang/lib/AST/Interp/ByteCodeExprGen.h   |  2 ++
 clang/test/AST/Interp/complex.cpp| 16 +++--
 3 files changed, 46 insertions(+), 17 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e6b3097a80d8f7..8a4f5a83b6f081 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -280,6 +280,10 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 return true;
   }
 
+  case CK_IntegralComplexToReal:
+  case CK_FloatingComplexToReal:
+return this->emitComplexReal(SubExpr);
+
   case CK_ToVoid:
 return discard(SubExpr);
 
@@ -2023,7 +2027,7 @@ bool ByteCodeExprGen::dereference(
   }
 
   if (LV->getType()->isAnyComplexType())
-return visit(LV);
+return this->delegate(LV);
 
   return false;
 }
@@ -2760,21 +2764,9 @@ bool ByteCodeExprGen::VisitUnaryOperator(const 
UnaryOperator *E) {
 if (!this->visit(SubExpr))
   return false;
 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
-  case UO_Real: { // __real x
+  case UO_Real: // __real x
 assert(!T);
-if (!this->visit(SubExpr))
-  return false;
-if (!this->emitConstUint8(0, E))
-  return false;
-if (!this->emitArrayElemPtrPopUint8(E))
-  return false;
-
-// Since our _Complex implementation does not map to a primitive type,
-// we sometimes have to do the lvalue-to-rvalue conversion here manually.
-if (!SubExpr->isLValue())
-  return this->emitLoadPop(classifyPrim(E->getType()), E);
-return true;
-  }
+return this->emitComplexReal(SubExpr);
   case UO_Imag: { // __imag x
 assert(!T);
 if (!this->visit(SubExpr))
@@ -2941,6 +2933,29 @@ bool ByteCodeExprGen::emitPrimCast(PrimType 
FromT, PrimType ToT,
   return false;
 }
 
+/// Emits __real(SubExpr)
+template 
+bool ByteCodeExprGen::emitComplexReal(const Expr *SubExpr) {
+  assert(SubExpr->getType()->isAnyComplexType());
+
+  if (DiscardResult)
+return this->discard(SubExpr);
+
+  if (!this->visit(SubExpr))
+return false;
+  if (!this->emitConstUint8(0, SubExpr))
+return false;
+  if (!this->emitArrayElemPtrPopUint8(SubExpr))
+return false;
+
+  // Since our _Complex implementation does not map to a primitive type,
+  // we sometimes have to do the lvalue-to-rvalue conversion here manually.
+  if (!SubExpr->isLValue())
+return this->emitLoadPop(*classifyComplexElementType(SubExpr->getType()),
+ SubExpr);
+  return true;
+}
+
 /// When calling this, we have a pointer of the local-to-destroy
 /// on the stack.
 /// Emit destruction of record types (or arrays of record types).
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index bbb13e97e72569..48005ce05724b5 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -294,6 +294,8 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
 return this->classify(ElemType);
   }
 
+  bool emitComplexReal(const Expr *SubExpr);
+
   bool emitRecordDestruction(const Descriptor *Desc);
   unsigned collectBaseOffset(const RecordType *BaseType,
  const RecordType *DerivedType);
diff --git a/clang/test/AST/Interp/complex.cpp 
b/clang/test/AST/Interp/complex.cpp
index 66490e973988bb..fd5cb8395550b5 100644
--- a/clang/test/AST/Interp/complex.cpp
+++ b/clang/test/AST/Interp/complex.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
-// RUN: %clang_cc1 -verify=ref %s
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify 
-Wno-unused-value %s
+// RUN: %clang_cc1 -verify=ref -Wno-unused-value %s
 
 // expected-no-diagnostics
 // ref-no-diagnostics
@@ -37,6 +37,18 @@ constexpr _Complex int I2 = {};
 static_assert(__real(I2) == 0, "");
 static_assert(__imag(I2) == 0, "");
 
+constexpr int ignoredCast() {
+  I2;
+  (int)I2;
+  /* (float)I2; FIXME*/
+  D1;
+  /* (int)D1; FIXME*/
+  (double)D1;
+  return 0;
+}
+static_assert(ignoredCast() == 0, "");
+static_assert((int)I1 == 1, "");
+
 
 /// Standalone complex expressions.
 static_assert(__real((_Complex float){1.0, 3.0}) == 1.0, "");

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

[clang] [clang][Interp] Implement ComplexToReal casts (PR #77294)

2024-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Add a new emitComplexReal() helper function and use that for the new casts as 
well as the old __real implementation.

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


3 Files Affected:

- (modified) clang/lib/AST/Interp/ByteCodeExprGen.cpp (+30-15) 
- (modified) clang/lib/AST/Interp/ByteCodeExprGen.h (+2) 
- (modified) clang/test/AST/Interp/complex.cpp (+14-2) 


``diff
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e6b3097a80d8f7..8a4f5a83b6f081 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -280,6 +280,10 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 return true;
   }
 
+  case CK_IntegralComplexToReal:
+  case CK_FloatingComplexToReal:
+return this->emitComplexReal(SubExpr);
+
   case CK_ToVoid:
 return discard(SubExpr);
 
@@ -2023,7 +2027,7 @@ bool ByteCodeExprGen::dereference(
   }
 
   if (LV->getType()->isAnyComplexType())
-return visit(LV);
+return this->delegate(LV);
 
   return false;
 }
@@ -2760,21 +2764,9 @@ bool ByteCodeExprGen::VisitUnaryOperator(const 
UnaryOperator *E) {
 if (!this->visit(SubExpr))
   return false;
 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
-  case UO_Real: { // __real x
+  case UO_Real: // __real x
 assert(!T);
-if (!this->visit(SubExpr))
-  return false;
-if (!this->emitConstUint8(0, E))
-  return false;
-if (!this->emitArrayElemPtrPopUint8(E))
-  return false;
-
-// Since our _Complex implementation does not map to a primitive type,
-// we sometimes have to do the lvalue-to-rvalue conversion here manually.
-if (!SubExpr->isLValue())
-  return this->emitLoadPop(classifyPrim(E->getType()), E);
-return true;
-  }
+return this->emitComplexReal(SubExpr);
   case UO_Imag: { // __imag x
 assert(!T);
 if (!this->visit(SubExpr))
@@ -2941,6 +2933,29 @@ bool ByteCodeExprGen::emitPrimCast(PrimType 
FromT, PrimType ToT,
   return false;
 }
 
+/// Emits __real(SubExpr)
+template 
+bool ByteCodeExprGen::emitComplexReal(const Expr *SubExpr) {
+  assert(SubExpr->getType()->isAnyComplexType());
+
+  if (DiscardResult)
+return this->discard(SubExpr);
+
+  if (!this->visit(SubExpr))
+return false;
+  if (!this->emitConstUint8(0, SubExpr))
+return false;
+  if (!this->emitArrayElemPtrPopUint8(SubExpr))
+return false;
+
+  // Since our _Complex implementation does not map to a primitive type,
+  // we sometimes have to do the lvalue-to-rvalue conversion here manually.
+  if (!SubExpr->isLValue())
+return this->emitLoadPop(*classifyComplexElementType(SubExpr->getType()),
+ SubExpr);
+  return true;
+}
+
 /// When calling this, we have a pointer of the local-to-destroy
 /// on the stack.
 /// Emit destruction of record types (or arrays of record types).
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index bbb13e97e72569..48005ce05724b5 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -294,6 +294,8 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
 return this->classify(ElemType);
   }
 
+  bool emitComplexReal(const Expr *SubExpr);
+
   bool emitRecordDestruction(const Descriptor *Desc);
   unsigned collectBaseOffset(const RecordType *BaseType,
  const RecordType *DerivedType);
diff --git a/clang/test/AST/Interp/complex.cpp 
b/clang/test/AST/Interp/complex.cpp
index 66490e973988bb..fd5cb8395550b5 100644
--- a/clang/test/AST/Interp/complex.cpp
+++ b/clang/test/AST/Interp/complex.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
-// RUN: %clang_cc1 -verify=ref %s
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify 
-Wno-unused-value %s
+// RUN: %clang_cc1 -verify=ref -Wno-unused-value %s
 
 // expected-no-diagnostics
 // ref-no-diagnostics
@@ -37,6 +37,18 @@ constexpr _Complex int I2 = {};
 static_assert(__real(I2) == 0, "");
 static_assert(__imag(I2) == 0, "");
 
+constexpr int ignoredCast() {
+  I2;
+  (int)I2;
+  /* (float)I2; FIXME*/
+  D1;
+  /* (int)D1; FIXME*/
+  (double)D1;
+  return 0;
+}
+static_assert(ignoredCast() == 0, "");
+static_assert((int)I1 == 1, "");
+
 
 /// Standalone complex expressions.
 static_assert(__real((_Complex float){1.0, 3.0}) == 1.0, "");

``




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


[clang] [clang] Fix a crash when referencing the result if the overload fails (PR #77288)

2024-01-08 Thread Mariya Podchishchaeva via cfe-commits

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

Thank you very much for the fix.
I apologize for the trouble. 


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


[clang] [clang][analyzer] Add missing stream related functions to StdLibraryFunctionsChecker. (PR #76979)

2024-01-08 Thread Balázs Kéri via cfe-commits

https://github.com/balazske updated 
https://github.com/llvm/llvm-project/pull/76979

From e24b90eebfff7a352dd2c0df7f948ffef26ea3b3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Thu, 4 Jan 2024 18:16:12 +0100
Subject: [PATCH 1/3] [clang][analyzer] Add missing stream related functions to
 StdCLibraryFunctionsChecker.

Some stream functions were recently added to StreamChecker that were not 
modeled by
StdCLibraryFunctionsChecker. To ensure consistency these functions are added
to the other checker too.
Some of the related tests are re-organized.
---
 .../Checkers/StdLibraryFunctionsChecker.cpp   | 88 +++
 clang/test/Analysis/std-c-library-functions.c |  4 +-
 clang/test/Analysis/stream-error.c| 26 --
 clang/test/Analysis/stream-noopen.c   | 68 ++
 clang/test/Analysis/stream-note.c |  1 +
 clang/test/Analysis/stream.c  | 25 +-
 6 files changed, 166 insertions(+), 46 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 20068653d530a3..f4bf68c3147fd1 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2023,13 +2023,6 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
{{EOFv, EOFv}, {0, UCharRangeMax}},
"an unsigned char value or EOF")));
 
-  // The getc() family of functions that returns either a char or an EOF.
-  addToFunctionSummaryMap(
-  {"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
-  Summary(NoEvalCall)
-  .Case({ReturnValueCondition(WithinRange,
-  {{EOFv, EOFv}, {0, UCharRangeMax}})},
-ErrnoIrrelevant));
   addToFunctionSummaryMap(
   "getchar", Signature(ArgTypes{}, RetType{IntTy}),
   Summary(NoEvalCall)
@@ -2139,7 +2132,17 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 std::move(GetenvSummary));
   }
 
-  if (ModelPOSIX) {
+  if (!ModelPOSIX) {
+// Without POSIX use of 'errno' is not specified (in these cases).
+// Add these functions without 'errno' checks.
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange,
+{{EOFv, EOFv}, {0, UCharRangeMax}})},
+  ErrnoIrrelevant)
+.ArgConstraint(NotNull(ArgNo(0;
+  } else {
 const auto ReturnsZeroOrMinusOne =
 ConstraintSet{ReturnValueCondition(WithinRange, Range(-1, 0))};
 const auto ReturnsZero =
@@ -2192,6 +2195,16 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(NotNull(ArgNo(1)))
 .ArgConstraint(NotNull(ArgNo(2;
 
+// FILE *fdopen(int fd, const char *mode);
+addToFunctionSummaryMap(
+"fdopen",
+Signature(ArgTypes{IntTy, ConstCharPtrTy}, RetType{FilePtrTy}),
+Summary(NoEvalCall)
+.Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
+.ArgConstraint(NotNull(ArgNo(1;
+
 // int fclose(FILE *stream);
 addToFunctionSummaryMap(
 "fclose", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
@@ -2201,6 +2214,56 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
+// int fgetc(FILE *stream);
+// 'getc' is the same as 'fgetc' but may be a macro
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, {{0, UCharRangeMax}})},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;
+
+// int fputc(int c, FILE *stream);
+// 'putc' is the same as 'fputc' but may be a macro
+addToFunctionSummaryMap(
+{"putc", "fputc"},
+Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(1)))
+.ArgConstraint(
+ArgumentCond

[clang] [clang][Interp] Fix discarded integral and floating casts (PR #77295)

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

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/77295

We need to handle this at the CastExpr level.

>From 4cecdb9bf613e7c4f42d6e735324a6d155467551 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Mon, 8 Jan 2024 11:23:45 +0100
Subject: [PATCH] [clang][Interp] Fix discarded integral and floating casts

We need to handle this at the CastExpr level.
---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 7 +++
 clang/test/AST/Interp/literals.cpp   | 4 
 2 files changed, 11 insertions(+)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e6b3097a80d8f7..7f8bbe78732481 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -114,6 +114,8 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
   }
 
   case CK_FloatingCast: {
+if (DiscardResult)
+  return this->discard(SubExpr);
 if (!this->visit(SubExpr))
   return false;
 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
@@ -121,6 +123,8 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
   }
 
   case CK_IntegralToFloating: {
+if (DiscardResult)
+  return this->discard(SubExpr);
 std::optional FromT = classify(SubExpr->getType());
 if (!FromT)
   return false;
@@ -135,6 +139,9 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
 
   case CK_FloatingToBoolean:
   case CK_FloatingToIntegral: {
+if (DiscardResult)
+  return this->discard(SubExpr);
+
 std::optional ToT = classify(CE->getType());
 
 if (!ToT)
diff --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index 85adfe551384d2..61825bc11438f6 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -1024,6 +1024,10 @@ namespace DiscardExprs {
 __null;
 __builtin_offsetof(A, a);
 1,2;
+(int)1.0;
+(float)1;
+(double)1.0f;
+(signed)4u;
 
 return 0;
   }

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


[clang] [clang][Interp] Fix discarded integral and floating casts (PR #77295)

2024-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

We need to handle this at the CastExpr level.

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


2 Files Affected:

- (modified) clang/lib/AST/Interp/ByteCodeExprGen.cpp (+7) 
- (modified) clang/test/AST/Interp/literals.cpp (+4) 


``diff
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e6b3097a80d8f7..7f8bbe78732481 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -114,6 +114,8 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
   }
 
   case CK_FloatingCast: {
+if (DiscardResult)
+  return this->discard(SubExpr);
 if (!this->visit(SubExpr))
   return false;
 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
@@ -121,6 +123,8 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
   }
 
   case CK_IntegralToFloating: {
+if (DiscardResult)
+  return this->discard(SubExpr);
 std::optional FromT = classify(SubExpr->getType());
 if (!FromT)
   return false;
@@ -135,6 +139,9 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
 
   case CK_FloatingToBoolean:
   case CK_FloatingToIntegral: {
+if (DiscardResult)
+  return this->discard(SubExpr);
+
 std::optional ToT = classify(CE->getType());
 
 if (!ToT)
diff --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index 85adfe551384d2..61825bc11438f6 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -1024,6 +1024,10 @@ namespace DiscardExprs {
 __null;
 __builtin_offsetof(A, a);
 1,2;
+(int)1.0;
+(float)1;
+(double)1.0f;
+(signed)4u;
 
 return 0;
   }

``




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


[clang] [clang][Interp] Implement ComplexToReal casts (PR #77294)

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


@@ -37,6 +37,18 @@ constexpr _Complex int I2 = {};
 static_assert(__real(I2) == 0, "");
 static_assert(__imag(I2) == 0, "");
 
+constexpr int ignoredCast() {
+  I2;
+  (int)I2;
+  /* (float)I2; FIXME*/
+  D1;
+  /* (int)D1; FIXME*/

tbaederr wrote:

The commented-out tests need https://github.com/llvm/llvm-project/pull/77295 
first.

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


[clang] Improve modeling of 'getcwd' in the StdLibraryFunctionsChecker (PR #77040)

2024-01-08 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/77040

>From 10a0e9aae5effdd6e26476e78a778b89373358df Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Fri, 5 Jan 2024 10:05:15 +0800
Subject: [PATCH 1/3] Improve modeling of 'getcwd' in the
 StdLibraryFunctionsChecker

1. Improve the 'errno' modeling.
2. Make the range of the buffer size argument more accurate.
---
 clang/docs/ReleaseNotes.rst   |  5 +++--
 .../Checkers/StdLibraryFunctionsChecker.cpp   |  7 +--
 clang/test/Analysis/errno-stdlibraryfunctions.c   | 11 +++
 .../Analysis/std-c-library-functions-path-notes.c |  6 ++
 4 files changed, 25 insertions(+), 4 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ce7599ad34beaf..f59fe77b447aec 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1138,9 +1138,10 @@ Improvements
 
 
 - Improved the ``unix.StdCLibraryFunctions`` checker by modeling more
-  functions like ``send``, ``recv``, ``readlink``, ``fflush``, ``mkdtemp`` and
-  ``errno`` behavior.
+  functions like ``send``, ``recv``, ``readlink``, ``fflush``, ``mkdtemp``,
+  ``getcwd`` and ``errno`` behavior.
   (`52ac71f92d38 
`_,
+  `#77040 `_,
   `#76671 `_,
   `#71373 `_,
   `#76557 `_,
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 20068653d530a3..759de10601d08f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2516,12 +2516,15 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(NotNull(ArgNo(0;
 
 // char *getcwd(char *buf, size_t size);
-// FIXME: Improve for errno modeling.
 addToFunctionSummaryMap(
 "getcwd", Signature(ArgTypes{CharPtrTy, SizeTy}, RetType{CharPtrTy}),
 Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0)))
 .ArgConstraint(
-ArgumentCondition(1, WithinRange, Range(0, SizeMax;
+ArgumentCondition(1, WithinRange, Range(1, SizeMax;
 
 // int mkdir(const char *pathname, mode_t mode);
 addToFunctionSummaryMap(
diff --git a/clang/test/Analysis/errno-stdlibraryfunctions.c 
b/clang/test/Analysis/errno-stdlibraryfunctions.c
index 80e14c4e2923ca..b1317a2e2582de 100644
--- a/clang/test/Analysis/errno-stdlibraryfunctions.c
+++ b/clang/test/Analysis/errno-stdlibraryfunctions.c
@@ -74,3 +74,14 @@ void errno_mkdtemp(char *template) {
 if (errno) {} // expected-warning{{An undefined 
value may be read from 'errno'}}
   }
 }
+
+void errno_getcwd(char *Buf, size_t sz) {
+  char *Path = getcwd(Buf, sz);
+  if (Path == NULL) {
+clang_analyzer_eval(errno != 0);  // expected-warning{{TRUE}}
+if (errno) {} // no warning
+  } else {
+clang_analyzer_eval(Path == Buf); // expected-warning{{TRUE}}
+if (errno) {} // expected-warning{{An undefined 
value may be read from 'errno'}}
+  }
+}
diff --git a/clang/test/Analysis/std-c-library-functions-path-notes.c 
b/clang/test/Analysis/std-c-library-functions-path-notes.c
index 4df00fe1e60646..0f5b9c08e9c0f3 100644
--- a/clang/test/Analysis/std-c-library-functions-path-notes.c
+++ b/clang/test/Analysis/std-c-library-functions-path-notes.c
@@ -89,3 +89,9 @@ int test_readlink_bufsize_zero(char *Buf, size_t Bufsize) {
   // expected-warning{{Division by zero}} \
   // expected-note{{Division by zero}}
 }
+
+char *test_getcwd_bufsize_zero(char *Buf) {
+  return getcwd(Buf, 0); // \
+  // expected-warning {{The 2nd argument to 'getcwd' is 0 but should be > 0}} \
+  // expected-note{{The 2nd argument to 'getcwd' is 0 but should be > 0}}
+}

>From 2e76ecea9d86eb4d759feada271dd2e26b7cac82 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Sat, 6 Jan 2024 19:35:42 +0800
Subject: [PATCH 2/3] Improve modeling of 'getcwd' in the
 StdLibraryFunctionsChecker

---
 .../Checkers/StdLibraryFunctionsChecker.cpp |  9 +++--
 clang/test/Analysis/errno-stdlibraryfunctions.c | 17 ++---
 .../std-c-library-functions-path-notes.c|  6 --
 3 files changed, 17 insertions(+), 15 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 

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

2024-01-08 Thread Simon Pilgrim via cfe-commits


@@ -933,6 +933,9 @@ X86 Support
 - Support ISA of ``AVX10.1``.
 - ``-march=pantherlake`` and ``-march=clearwaterforest`` are now supported.
 - Added ABI handling for ``__float128`` to match with GCC.
+- Emit Warnings for clang options to enable knl/knm. From next version
+  (LLVM 19), all-end supports on knl/knm and other Xeon Phi targets will be
+  removed.

RKSimon wrote:

This needs rephrasing - to list all the ISAs that are deprecated and the 
intrinsics will be removed.

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] [clang] Bounds checking on unclosed parentheses, brackets or braces in Expanded Tokens (PR #69849)

2024-01-08 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

I second everything that @HighCommander4 said. It would be really useful to add 
an assertion that we never get out-of-bounds here, but this indicates a logic 
error somewhere in the code that should be fixed.

I am slightly suspicious of source locations pointing at `eof` in the AST in 
the first place, even in invalid code. I wonder if we would be better off just 
having an invalid source location there instead of pointing at `eof`.

Asserting that `tok::eof` should not be passed to `spelledForExpandedToken` and 
returning `nullopt` in `spelledForExpanded` looks like a reasonable workaround 
until we fix this. (The semantics looks reasonable as we don't really have a 
spelled token we can map `eof` back to).

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


[clang] 10b5b5d - [clang] Fix a crash when referencing the result if the overload fails (#77288)

2024-01-08 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-01-08T11:49:36+01:00
New Revision: 10b5b5d6e2df25dab86fe89a78c5df6f507f6e50

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

LOG: [clang] Fix a crash when referencing the result if the overload fails 
(#77288)

after 20a05677f9394d4bc9467fe7bc93a4ebd3aeda61

If the overload fails, the `Best` might point to the `end()`,
referencing it leads to asan crashes.

Added: 


Modified: 
clang/lib/Sema/SemaOverload.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 9fb767101e1eb7..8e3a2d1288079b 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -13994,21 +13994,22 @@ ExprResult Sema::BuildOverloadedCallExpr(Scope *S, 
Expr *Fn,
   OverloadCandidateSet::iterator Best;
   OverloadingResult OverloadResult =
   CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
-  FunctionDecl *FDecl = Best->Function;
 
   // Model the case with a call to a templated function whose definition
   // encloses the call and whose return type contains a placeholder type as if
   // the UnresolvedLookupExpr was type-dependent.
-  if (OverloadResult == OR_Success && FDecl &&
-  FDecl->isTemplateInstantiation() &&
-  FDecl->getReturnType()->isUndeducedType()) {
-if (auto TP = FDecl->getTemplateInstantiationPattern(false)) {
-  if (TP->willHaveBody()) {
-CallExpr *CE =
-CallExpr::Create(Context, Fn, Args, Context.DependentTy, 
VK_PRValue,
- RParenLoc, CurFPFeatureOverrides());
-result = CE;
-return result;
+  if (OverloadResult == OR_Success) {
+FunctionDecl *FDecl = Best->Function;
+if (FDecl && FDecl->isTemplateInstantiation() &&
+FDecl->getReturnType()->isUndeducedType()) {
+  if (auto TP = FDecl->getTemplateInstantiationPattern(false)) {
+if (TP->willHaveBody()) {
+  CallExpr *CE =
+  CallExpr::Create(Context, Fn, Args, Context.DependentTy,
+   VK_PRValue, RParenLoc, CurFPFeatureOverrides());
+  result = CE;
+  return result;
+}
   }
 }
   }



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


[clang] [clang] Fix a crash when referencing the result if the overload fails (PR #77288)

2024-01-08 Thread Haojian Wu via cfe-commits

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


[clang] [clang] Fix a crash when referencing the result if the overload fails (PR #77288)

2024-01-08 Thread Haojian Wu via cfe-commits

hokein wrote:

Thanks for the review.

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


[clang] [clang][coverage] fixing "if constexpr" and "if consteval" coverage report (PR #77214)

2024-01-08 Thread Hana Dusíková via cfe-commits

https://github.com/hanickadot updated 
https://github.com/llvm/llvm-project/pull/77214

From 2dc9d821aa3d100f99ac603a0880498226c94323 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Hana=20Dusi=CC=81kova=CC=81?= 
Date: Sun, 7 Jan 2024 00:13:08 +0100
Subject: [PATCH 1/2] [coverage] fix incorrect coverage reporting for "if
 constexpr" and "if consteval"

---
 clang/docs/ReleaseNotes.rst  |  3 +++
 clang/include/clang/AST/Stmt.h   |  6 --
 clang/lib/CodeGen/CoverageMappingGen.cpp | 13 +++--
 clang/lib/Sema/TreeTransform.h   | 10 +-
 4 files changed, 27 insertions(+), 5 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c9b577bd549b1e..c36e051d055b72 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -696,6 +696,9 @@ Bug Fixes in This Version
 - Clang now accepts recursive non-dependent calls to functions with deduced
   return type.
   Fixes (`#71015 `_)
+- Clang now emits correct source location for code-coverage regions in `if 
constexpr`
+  and `if consteval` branches.
+  Fixes (`#54419 `_)
 
 
 Bug Fixes to Compiler Builtins
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index da7b37ce0e1211..e1fde24e647789 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -1631,8 +1631,10 @@ class CompoundStmt final
   SourceLocation RB);
 
   // Build an empty compound statement with a location.
-  explicit CompoundStmt(SourceLocation Loc)
-  : Stmt(CompoundStmtClass), LBraceLoc(Loc), RBraceLoc(Loc) {
+  explicit CompoundStmt(SourceLocation Loc) : CompoundStmt(Loc, Loc) {}
+
+  CompoundStmt(SourceLocation Loc, SourceLocation EndLoc)
+  : Stmt(CompoundStmtClass), LBraceLoc(Loc), RBraceLoc(EndLoc) {
 CompoundStmtBits.NumStmts = 0;
 CompoundStmtBits.HasFPFeatures = 0;
   }
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index bf227386a71b78..b245abd16c3f4a 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1712,7 +1712,11 @@ struct CounterCoverageMappingBuilder
   extendRegion(S->getCond());
 
 Counter ParentCount = getRegion().getCounter();
-Counter ThenCount = getRegionCounter(S);
+
+// If this is "if !consteval" the then-branch will never be taken, we don't
+// need to change counter
+Counter ThenCount =
+S->isNegatedConsteval() ? ParentCount : getRegionCounter(S);
 
 if (!S->isConsteval()) {
   // Emitting a counter for the condition makes it easier to interpret the
@@ -1729,7 +1733,12 @@ struct CounterCoverageMappingBuilder
 extendRegion(S->getThen());
 Counter OutCount = propagateCounts(ThenCount, S->getThen());
 
-Counter ElseCount = subtractCounters(ParentCount, ThenCount);
+// If this is "if consteval" the else-branch will never be taken, we don't
+// need to change counter
+Counter ElseCount = S->isNonNegatedConsteval()
+? ParentCount
+: subtractCounters(ParentCount, ThenCount);
+
 if (const Stmt *Else = S->getElse()) {
   bool ThenHasTerminateStmt = HasTerminateStmt;
   HasTerminateStmt = false;
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index c8c5a51bf9f94e..19266a7ffa2fe0 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -7732,7 +7732,11 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
 if (Then.isInvalid())
   return StmtError();
   } else {
-Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
+// Discarded branch is replaced with empty CompoundStmt so we can keep
+// proper source location for start and end of original branch, so
+// subsequent transformations like CoverageMapping work properly
+Then = new (getSema().Context)
+CompoundStmt(S->getThen()->getBeginLoc(), S->getThen()->getEndLoc());
   }
 
   // Transform the "else" branch.
@@ -7741,6 +7745,10 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
 Else = getDerived().TransformStmt(S->getElse());
 if (Else.isInvalid())
   return StmtError();
+  } else if (S->getElse() && ConstexprConditionValue &&
+ *ConstexprConditionValue) {
+Else = new (getSema().Context)
+CompoundStmt(S->getElse()->getBeginLoc(), S->getElse()->getEndLoc());
   }
 
   if (!getDerived().AlwaysRebuild() &&

From 37879a5b7ec3f98ce423672d2bf43efe826ab5af Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Hana=20Dusi=CC=81kova=CC=81?= 
Date: Sun, 7 Jan 2024 00:13:08 +0100
Subject: [PATCH 2/2] [coverage] fix incorrect coverage reporting for "if
 constexpr" and "if consteval"

---
 clang/test/CoverageMapping/if.cpp | 86 +--
 1 file changed, 69 insertions(+), 17 deletions(-)


[clang] [mlir] [llvm] [clang][coverage] fixing "if constexpr" and "if consteval" coverage report (PR #77214)

2024-01-08 Thread Hana Dusíková via cfe-commits

https://github.com/hanickadot updated 
https://github.com/llvm/llvm-project/pull/77214

From 8f1370aae4db2048c35516a85fb72c742557942b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Hana=20Dusi=CC=81kova=CC=81?= 
Date: Sun, 7 Jan 2024 00:13:08 +0100
Subject: [PATCH] [coverage] fix incorrect coverage reporting for "if
 constexpr" and "if consteval"

---
 clang/include/clang/AST/Stmt.h   |  6 --
 clang/lib/CodeGen/CoverageMappingGen.cpp | 13 +++--
 clang/lib/Sema/TreeTransform.h   |  7 ++-
 3 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index da7b37ce0e1211..e1fde24e647789 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -1631,8 +1631,10 @@ class CompoundStmt final
   SourceLocation RB);
 
   // Build an empty compound statement with a location.
-  explicit CompoundStmt(SourceLocation Loc)
-  : Stmt(CompoundStmtClass), LBraceLoc(Loc), RBraceLoc(Loc) {
+  explicit CompoundStmt(SourceLocation Loc) : CompoundStmt(Loc, Loc) {}
+
+  CompoundStmt(SourceLocation Loc, SourceLocation EndLoc)
+  : Stmt(CompoundStmtClass), LBraceLoc(Loc), RBraceLoc(EndLoc) {
 CompoundStmtBits.NumStmts = 0;
 CompoundStmtBits.HasFPFeatures = 0;
   }
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index bf227386a71b78..b245abd16c3f4a 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1712,7 +1712,11 @@ struct CounterCoverageMappingBuilder
   extendRegion(S->getCond());
 
 Counter ParentCount = getRegion().getCounter();
-Counter ThenCount = getRegionCounter(S);
+
+// If this is "if !consteval" the then-branch will never be taken, we don't
+// need to change counter
+Counter ThenCount =
+S->isNegatedConsteval() ? ParentCount : getRegionCounter(S);
 
 if (!S->isConsteval()) {
   // Emitting a counter for the condition makes it easier to interpret the
@@ -1729,7 +1733,12 @@ struct CounterCoverageMappingBuilder
 extendRegion(S->getThen());
 Counter OutCount = propagateCounts(ThenCount, S->getThen());
 
-Counter ElseCount = subtractCounters(ParentCount, ThenCount);
+// If this is "if consteval" the else-branch will never be taken, we don't
+// need to change counter
+Counter ElseCount = S->isNonNegatedConsteval()
+? ParentCount
+: subtractCounters(ParentCount, ThenCount);
+
 if (const Stmt *Else = S->getElse()) {
   bool ThenHasTerminateStmt = HasTerminateStmt;
   HasTerminateStmt = false;
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index c8c5a51bf9f94e..0033c851b618a1 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -7732,7 +7732,8 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
 if (Then.isInvalid())
   return StmtError();
   } else {
-Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
+Then = new (getSema().Context)
+CompoundStmt(S->getThen()->getBeginLoc(), S->getThen()->getEndLoc());
   }
 
   // Transform the "else" branch.
@@ -7741,6 +7742,10 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
 Else = getDerived().TransformStmt(S->getElse());
 if (Else.isInvalid())
   return StmtError();
+  } else if (S->getElse() && ConstexprConditionValue &&
+ *ConstexprConditionValue) {
+Else = new (getSema().Context)
+CompoundStmt(S->getElse()->getBeginLoc(), S->getElse()->getEndLoc());
   }
 
   if (!getDerived().AlwaysRebuild() &&

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


[clang] [clang][coverage] fixing "if constexpr" and "if consteval" coverage report (PR #77214)

2024-01-08 Thread Hana Dusíková via cfe-commits

https://github.com/hanickadot updated 
https://github.com/llvm/llvm-project/pull/77214

From 413517b2a1d4e45b6c58ab282c7990e83f429ab9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Hana=20Dusi=CC=81kova=CC=81?= 
Date: Mon, 8 Jan 2024 11:54:45 +0100
Subject: [PATCH] [coverage] fix incorrect coverage reporting for "if
 constexpr" and "if consteval"

---
 clang/docs/ReleaseNotes.rst  |  3 +
 clang/include/clang/AST/Stmt.h   |  6 +-
 clang/lib/CodeGen/CoverageMappingGen.cpp | 13 +++-
 clang/lib/Sema/TreeTransform.h   | 10 ++-
 clang/test/CoverageMapping/if.cpp| 86 +++-
 5 files changed, 96 insertions(+), 22 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c9b577bd549b1e..c36e051d055b72 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -696,6 +696,9 @@ Bug Fixes in This Version
 - Clang now accepts recursive non-dependent calls to functions with deduced
   return type.
   Fixes (`#71015 `_)
+- Clang now emits correct source location for code-coverage regions in `if 
constexpr`
+  and `if consteval` branches.
+  Fixes (`#54419 `_)
 
 
 Bug Fixes to Compiler Builtins
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index da7b37ce0e1211..e1fde24e647789 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -1631,8 +1631,10 @@ class CompoundStmt final
   SourceLocation RB);
 
   // Build an empty compound statement with a location.
-  explicit CompoundStmt(SourceLocation Loc)
-  : Stmt(CompoundStmtClass), LBraceLoc(Loc), RBraceLoc(Loc) {
+  explicit CompoundStmt(SourceLocation Loc) : CompoundStmt(Loc, Loc) {}
+
+  CompoundStmt(SourceLocation Loc, SourceLocation EndLoc)
+  : Stmt(CompoundStmtClass), LBraceLoc(Loc), RBraceLoc(EndLoc) {
 CompoundStmtBits.NumStmts = 0;
 CompoundStmtBits.HasFPFeatures = 0;
   }
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index bf227386a71b78..b245abd16c3f4a 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1712,7 +1712,11 @@ struct CounterCoverageMappingBuilder
   extendRegion(S->getCond());
 
 Counter ParentCount = getRegion().getCounter();
-Counter ThenCount = getRegionCounter(S);
+
+// If this is "if !consteval" the then-branch will never be taken, we don't
+// need to change counter
+Counter ThenCount =
+S->isNegatedConsteval() ? ParentCount : getRegionCounter(S);
 
 if (!S->isConsteval()) {
   // Emitting a counter for the condition makes it easier to interpret the
@@ -1729,7 +1733,12 @@ struct CounterCoverageMappingBuilder
 extendRegion(S->getThen());
 Counter OutCount = propagateCounts(ThenCount, S->getThen());
 
-Counter ElseCount = subtractCounters(ParentCount, ThenCount);
+// If this is "if consteval" the else-branch will never be taken, we don't
+// need to change counter
+Counter ElseCount = S->isNonNegatedConsteval()
+? ParentCount
+: subtractCounters(ParentCount, ThenCount);
+
 if (const Stmt *Else = S->getElse()) {
   bool ThenHasTerminateStmt = HasTerminateStmt;
   HasTerminateStmt = false;
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index c8c5a51bf9f94e..19266a7ffa2fe0 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -7732,7 +7732,11 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
 if (Then.isInvalid())
   return StmtError();
   } else {
-Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
+// Discarded branch is replaced with empty CompoundStmt so we can keep
+// proper source location for start and end of original branch, so
+// subsequent transformations like CoverageMapping work properly
+Then = new (getSema().Context)
+CompoundStmt(S->getThen()->getBeginLoc(), S->getThen()->getEndLoc());
   }
 
   // Transform the "else" branch.
@@ -7741,6 +7745,10 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
 Else = getDerived().TransformStmt(S->getElse());
 if (Else.isInvalid())
   return StmtError();
+  } else if (S->getElse() && ConstexprConditionValue &&
+ *ConstexprConditionValue) {
+Else = new (getSema().Context)
+CompoundStmt(S->getElse()->getBeginLoc(), S->getElse()->getEndLoc());
   }
 
   if (!getDerived().AlwaysRebuild() &&
diff --git a/clang/test/CoverageMapping/if.cpp 
b/clang/test/CoverageMapping/if.cpp
index 65e3d62df79db4..cc18f791c2f79e 100644
--- a/clang/test/CoverageMapping/if.cpp
+++ b/clang/test/CoverageMapping/if.cpp
@@ -23,19 +23,29 @@ void foo() {// CHECK-NEXT: Gap,File 0, 
[[@LINE+1]]:21 -> [[@
 }  

[clang] [Format] Fix isStartOfName to recognize attributes (PR #76804)

2024-01-08 Thread Ilya Biryukov via cfe-commits


@@ -1698,8 +1698,6 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind 
Language) {
   /*BasedOnStyle=*/"google",
   },
   };
-  GoogleStyle.AttributeMacros.push_back("GUARDED_BY");

ilya-biryukov wrote:

@HazardyKnusperkeks friendly ping. Any thoughts on including a few more 
attributes into the (the first list of 4 elements) vs landing this change and 
relying on implicit formatting of those as function names?

I am happy to choose one of the two options arbitrarily, but I don't have 
enough context on `clang-format` to understand which approach is preferable, so 
I would love to get an opinion from someone in the `clang-format` community.

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


[clang] [Format] Fix isStartOfName to recognize attributes (PR #76804)

2024-01-08 Thread kadir çetinkaya via cfe-commits


@@ -1698,8 +1698,6 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind 
Language) {
   /*BasedOnStyle=*/"google",
   },
   };
-  GoogleStyle.AttributeMacros.push_back("GUARDED_BY");

kadircet wrote:

FWIW, not recognizing `foo` in `int foo BAR` as start-of-name looks like a big 
enough regression (which seems to be the main reason behind the line-braking 
behavior change), independent of whatever we do with the list of 
attribute-macros, I believe we should still make sure annotations for `foo` are 
correct rather urgently. so I am actually still in favor of landing this patch 
as-is, rather than trying to fix final formatting in a bunch of special cases 
by updating `AtrributeMacros` list.

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


[clang] [clang][coverage] fixing "if constexpr" and "if consteval" coverage report (PR #77214)

2024-01-08 Thread Hana Dusíková via cfe-commits

hanickadot wrote:

Added some tests. And also adding @ornata for review.

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


[clang] [clang][dataflow] Fix bug in `Value` comparison. (PR #76746)

2024-01-08 Thread via cfe-commits

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


[clang] [clang][dataflow] Fix bug in `Value` comparison. (PR #76746)

2024-01-08 Thread via cfe-commits

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


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


[clang] [clang][dataflow] Fix bug in `Value` comparison. (PR #76746)

2024-01-08 Thread via cfe-commits


@@ -27,9 +27,13 @@ static bool areEquivalentIndirectionValues(const Value &Val1,
 }
 
 bool areEquivalentValues(const Value &Val1, const Value &Val2) {
-  return &Val1 == &Val2 || (Val1.getKind() == Val2.getKind() &&
-(isa(&Val1) ||
- areEquivalentIndirectionValues(Val1, Val2)));
+  // If values are distinct and have properties, we don't consider them equal,
+  // leaving equality up to the user model.
+  return &Val1 == &Val2 ||
+ (Val1.getKind() == Val2.getKind() &&
+  (Val1.properties().empty() && Val2.properties().empty()) &&
+  (isa(&Val1) ||
+   areEquivalentIndirectionValues(Val1, Val2)));

martinboehme wrote:

Converting the nested boolean formula into a sequence of early-out checks would 
make this eaiser to read IMO. It also makes it easier to anchor the comment to 
the line that it actually refers to.

```suggestion
  if (&Val1 == &Val2) return true;
  if (Val1.getKind() != Val2.getKind()) return false;
  // If values are distinct and have properties, we don't consider them equal,
  // leaving equality up to the user model.
  if (!Val1.properties().empty() || !Val2.properties().empty()) return false;
  if (isa(&Val1)) return true;
  return areEquivalentIndirectionValues(Val1, Val2);
```

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


[clang] [clang][dataflow] Fix bug in `Value` comparison. (PR #76746)

2024-01-08 Thread via cfe-commits


@@ -53,8 +53,8 @@ TEST(ValueTest, EquivalentValuesWithDifferentPropsEquivalent) 
{
   TopBoolValue V2(A.makeAtomRef(Atom(3)));
   V1.setProperty("foo", Prop1);
   V2.setProperty("bar", Prop2);
-  EXPECT_TRUE(areEquivalentValues(V1, V2));
-  EXPECT_TRUE(areEquivalentValues(V2, V1));
+  EXPECT_FALSE(areEquivalentValues(V1, V2));

martinboehme wrote:

Name of test needs to be changed to reflect the changed behavior.

Also, can you add more tests for these cases:

* Only of of the values has properties
* Both values actually have the same properties, but we still consider them to 
be not equivalent (because we leave checking of properties up to the analysis)

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


[clang] [clang] Fix assertion failure when initializing union with FAM (PR #77298)

2024-01-08 Thread Nikita Popov via cfe-commits

https://github.com/nikic created https://github.com/llvm/llvm-project/pull/77298

When initializing a union that constrain a struct with a flexible array member, 
and the initializer list is empty, we currently trigger an assertion failure. 
This happens because getFlexibleArrayInitChars() assumes that the initializer 
list is non-empty.

The relevant code is only executed in assertion-enabled builds: 
https://github.com/llvm/llvm-project/blob/main/clang/lib/CodeGen/CodeGenModule.cpp#L5318-L5324

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

>From 68e21b7604964b7b391d9a077ca52175af21b65a Mon Sep 17 00:00:00 2001
From: Nikita Popov 
Date: Mon, 8 Jan 2024 12:41:34 +0100
Subject: [PATCH] [clang] Fix assertion failure when initializing union with
 FAM

When initializing a union that constrain a struct with a flexible
array member, and the initializer list is empty, we currently
trigger an assertion failure. This happens because
getFlexibleArrayInitChars() assumes that the initializer list is
non-empty.

Fixes https://github.com/llvm/llvm-project/issues/77085.
---
 clang/lib/AST/Decl.cpp   | 2 +-
 clang/test/CodeGen/flexible-array-init.c | 8 
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 12e0a6faa4c33d..e1440e5183a4e6 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -2835,7 +2835,7 @@ CharUnits VarDecl::getFlexibleArrayInitChars(const 
ASTContext &Ctx) const {
   if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
 return CharUnits::Zero();
   auto *List = dyn_cast(getInit()->IgnoreParens());
-  if (!List)
+  if (!List || List->getNumInits() == 0)
 return CharUnits::Zero();
   const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
   auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
diff --git a/clang/test/CodeGen/flexible-array-init.c 
b/clang/test/CodeGen/flexible-array-init.c
index b2cf959f7e1220..bae926da5feb07 100644
--- a/clang/test/CodeGen/flexible-array-init.c
+++ b/clang/test/CodeGen/flexible-array-init.c
@@ -20,3 +20,11 @@ struct __attribute((packed, aligned(4))) { char a; int x; 
char z[]; } e = { 1, 2
 
 struct { int x; char y[]; } f = { 1, { 13, 15 } };
 // CHECK: @f ={{.*}} global <{ i32, [2 x i8] }> <{ i32 1, [2 x i8] c"\0D\0F" }>
+
+union {
+  struct {
+int a;
+char b[];
+  } x;
+} in_union = {};
+// CHECK: @in_union ={{.*}} global %union.anon zeroinitializer

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


[clang] [clang] Fix assertion failure when initializing union with FAM (PR #77298)

2024-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Nikita Popov (nikic)


Changes

When initializing a union that constrain a struct with a flexible array member, 
and the initializer list is empty, we currently trigger an assertion failure. 
This happens because getFlexibleArrayInitChars() assumes that the initializer 
list is non-empty.

The relevant code is only executed in assertion-enabled builds: 
https://github.com/llvm/llvm-project/blob/main/clang/lib/CodeGen/CodeGenModule.cpp#L5318-L5324

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

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


2 Files Affected:

- (modified) clang/lib/AST/Decl.cpp (+1-1) 
- (modified) clang/test/CodeGen/flexible-array-init.c (+8) 


``diff
diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 12e0a6faa4c33d..e1440e5183a4e6 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -2835,7 +2835,7 @@ CharUnits VarDecl::getFlexibleArrayInitChars(const 
ASTContext &Ctx) const {
   if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
 return CharUnits::Zero();
   auto *List = dyn_cast(getInit()->IgnoreParens());
-  if (!List)
+  if (!List || List->getNumInits() == 0)
 return CharUnits::Zero();
   const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
   auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
diff --git a/clang/test/CodeGen/flexible-array-init.c 
b/clang/test/CodeGen/flexible-array-init.c
index b2cf959f7e1220..bae926da5feb07 100644
--- a/clang/test/CodeGen/flexible-array-init.c
+++ b/clang/test/CodeGen/flexible-array-init.c
@@ -20,3 +20,11 @@ struct __attribute((packed, aligned(4))) { char a; int x; 
char z[]; } e = { 1, 2
 
 struct { int x; char y[]; } f = { 1, { 13, 15 } };
 // CHECK: @f ={{.*}} global <{ i32, [2 x i8] }> <{ i32 1, [2 x i8] c"\0D\0F" }>
+
+union {
+  struct {
+int a;
+char b[];
+  } x;
+} in_union = {};
+// CHECK: @in_union ={{.*}} global %union.anon zeroinitializer

``




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


[compiler-rt] [libc] [lldb] [clang] [llvm] [flang] [libcxx] [clang-tools-extra] [flang] FDATE extension implementation: get date and time in ctime format (PR #71222)

2024-01-08 Thread Yi Wu via cfe-commits

yi-wu-arm wrote:

Hi @jeanPerier I have made some changes, mainly on test cases and use `char *` 
instead of `std::int_8t` for arg input. Saw your activity on GitHub, could you 
review the changes? Thanks in advance!

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


[flang] [clang] [llvm] [clang-tools-extra] [flang] Add EXECUTE_COMMAND_LINE runtime and lowering intrinsics implementation (PR #74077)

2024-01-08 Thread Yi Wu via cfe-commits

yi-wu-arm wrote:

Hi, @jeanPerier welcome back! I've made quite a few changes, mainly on memory 
allocate and deallocate, test improvements, and have moved some commonly used 
descriptor functions into `tools.cpp` to re-use some code instead of creating 
duplicates of them. Could you review the recent changes? Thanks in advance!

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


[libc] [libcxx] [compiler-rt] [llvm] [lld] [clang] [clang-tools-extra] [lldb] [mlir] [MLIR][LLVM] Add Continuous Loop Peeling transform to SCF (PR #71555)

2024-01-08 Thread via cfe-commits

https://github.com/muneebkhan85 updated 
https://github.com/llvm/llvm-project/pull/71555

>From 7bb2f9793b2a2cccbaa401f6e2ac850b587f2b59 Mon Sep 17 00:00:00 2001
From: Muneeb Khan 
Date: Tue, 7 Nov 2023 23:52:17 +0800
Subject: [PATCH 01/11] [MLIR][LLVM] Add Continuous Loop Peeling transform to
 SCF

This patch adds continuous loop peeling to scf loop transforms
in the MLIR backend. This transforms the target loop into a
chain of loops, with step sizes that are powers of two and
decrease exponetially across subsequent loops. Originally
authored by Litu Zhou litu.z...@huawei.com.
---
 .../SCF/TransformOps/SCFTransformOps.td   |  36 +
 .../SCF/TransformOps/SCFTransformOps.cpp  | 147 ++
 .../Dialect/SCF/loop-continuous-peel.mlir |  98 
 3 files changed, 281 insertions(+)
 create mode 100644 mlir/test/Dialect/SCF/loop-continuous-peel.mlir

diff --git a/mlir/include/mlir/Dialect/SCF/TransformOps/SCFTransformOps.td 
b/mlir/include/mlir/Dialect/SCF/TransformOps/SCFTransformOps.td
index 14df7e23a430fb..e3d79a7f0ae40f 100644
--- a/mlir/include/mlir/Dialect/SCF/TransformOps/SCFTransformOps.td
+++ b/mlir/include/mlir/Dialect/SCF/TransformOps/SCFTransformOps.td
@@ -147,6 +147,42 @@ def LoopPeelOp : Op {
+  let description = [{
+Transforms the loop into a chain of loops, with step sizes that are
+powers of two and decrease exponetially across subsequent loops.
+The transform is similar to loop.peel in the effect that it creates a loop
+with a step (that is power of 2) to divide the range evenly, with the
+difference that the remaining iterations are spread across similar loops
+with exponentially decreasing step sizes, with the last loop with step size
+of 2^0 = 1.
+
+ Return modes
+
+This operation consumes the `target` handles and produces the
+continuously-peeled loop.
+  }];
+
+  let arguments =
+  (ins TransformHandleTypeInterface:$target,
+   DefaultValuedAttr:$single_iter_opt);
+  // TODO: Return both the peeled loop and the remainder loop.
+  let results = (outs TransformHandleTypeInterface:$transformed);
+
+  let assemblyFormat =
+"$target attr-dict `:` functional-type(operands, results)";
+
+  let extraClassDeclaration = [{
+::mlir::DiagnosedSilenceableFailure applyToOne(
+::mlir::transform::TransformRewriter &rewriter,
+::mlir::Operation *target,
+::mlir::transform::ApplyToEachResultList &results,
+::mlir::transform::TransformState &state);
+  }];
+}
+
 def LoopPipelineOp : Op {
diff --git a/mlir/lib/Dialect/SCF/TransformOps/SCFTransformOps.cpp 
b/mlir/lib/Dialect/SCF/TransformOps/SCFTransformOps.cpp
index 62370604142cd5..dcba6a8b406b21 100644
--- a/mlir/lib/Dialect/SCF/TransformOps/SCFTransformOps.cpp
+++ b/mlir/lib/Dialect/SCF/TransformOps/SCFTransformOps.cpp
@@ -206,6 +206,153 @@ 
transform::LoopPeelOp::applyToOne(transform::TransformRewriter &rewriter,
   return DiagnosedSilenceableFailure::success();
 }
 
+//===-===//
+// LoopContinuousPeelOp
+//===-===//
+
+static LogicalResult splitLoopHelper(RewriterBase &b, scf::ForOp &forOp,
+ scf::ForOp &partialIteration,
+ Value &splitBound) {
+  RewriterBase::InsertionGuard guard(b);
+  auto lbInt = getConstantIntValue(forOp.getLowerBound());
+  auto ubInt = getConstantIntValue(forOp.getUpperBound());
+  auto stepInt = getConstantIntValue(forOp.getStep());
+
+  // No specialization necessary if step already divides upper bound evenly.
+  if (lbInt && ubInt && stepInt && (*ubInt - *lbInt) % *stepInt == 0)
+return failure();
+  // No specialization necessary if step size is 1.
+  if (stepInt == static_cast(1))
+return failure();
+
+  // Create ForOp for partial iteration.
+  b.setInsertionPointAfter(forOp);
+  partialIteration = cast(b.clone(*forOp.getOperation()));
+  partialIteration.getLowerBoundMutable().assign(splitBound);
+  forOp.replaceAllUsesWith(partialIteration->getResults());
+  partialIteration.getInitArgsMutable().assign(forOp->getResults());
+
+  // Set new upper loop bound.
+  b.updateRootInPlace(
+  forOp, [&]() { forOp.getUpperBoundMutable().assign(splitBound); });
+
+  return success();
+}
+
+static scf::IfOp convertSingleIterFor(RewriterBase &b, scf::ForOp &forOp) {
+  Location loc = forOp->getLoc();
+  IRMapping mapping;
+  mapping.map(forOp.getInductionVar(), forOp.getLowerBound());
+  for (auto [arg, operand] :
+   llvm::zip(forOp.getRegionIterArgs(), forOp.getInitsMutable())) {
+mapping.map(arg, operand.get());
+  }
+  b.setInsertionPoint(forOp);
+  auto cond =
+  b.create(loc, arith::CmpIPredicate::slt,
+  forOp.getLowerBound(), forOp.getUpperBound());
+  auto ifOp = b.create(loc, forOp->getResultTypes(), cond, true);
+  // then branch
+  b.setIns

[clang-tools-extra] [clang] [llvm] [AArch64] Add an AArch64 pass for loop idiom transformations (PR #72273)

2024-01-08 Thread David Green via cfe-commits

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


[clang] [llvm] [clang-tools-extra] [AArch64] Add an AArch64 pass for loop idiom transformations (PR #72273)

2024-01-08 Thread David Green via cfe-commits


@@ -0,0 +1,816 @@
+//===- AArch64LoopIdiomTransform.cpp - Loop idiom recognition 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This pass implements a pass that recognizes certain loop idioms and
+// transforms them into more optimized versions of the same loop. In cases
+// where this happens, it can be a significant performance win.
+//
+// We currently only recognize one loop that finds the first mismatched byte
+// in an array and returns the index, i.e. something like:
+//
+//  while (++i != n) {
+//if (a[i] != b[i])
+//  break;
+//  }
+//
+// In this example we can actually vectorize the loop despite the early exit,
+// although the loop vectorizer does not support it. It requires some extra
+// checks to deal with the possibility of faulting loads when crossing page
+// boundaries. However, even with these checks it is still profitable to do the
+// transformation.
+//
+//===--===//
+//
+// TODO List:
+//
+// * When optimizing for code size we may want to avoid some transformations.
+// * We can also support the inverse case where we scan for a matching element.
+//
+//===--===//
+
+#include "AArch64LoopIdiomTransform.h"
+#include "llvm/Analysis/DomTreeUpdater.h"
+#include "llvm/Analysis/LoopPass.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
+#include "llvm/IR/Dominators.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/MDBuilder.h"
+#include "llvm/IR/PatternMatch.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "aarch64-loop-idiom-transform"
+
+static cl::opt
+DisableAll("disable-aarch64-lit-all", cl::Hidden, cl::init(false),
+   cl::desc("Disable AArch64 Loop Idiom Transform Pass."));
+
+static cl::opt DisableByteCmp(
+"disable-aarch64-lit-bytecmp", cl::Hidden, cl::init(false),
+cl::desc("Proceed with AArch64 Loop Idiom Transform Pass, but do "
+ "not convert byte-compare loop(s)."));
+
+static cl::opt VerifyLoops(
+"aarch64-lit-verify", cl::Hidden, cl::init(false),
+cl::desc("Verify loops generated AArch64 Loop Idiom Transform Pass."));
+
+namespace llvm {
+
+void initializeAArch64LoopIdiomTransformLegacyPassPass(PassRegistry &);
+Pass *createAArch64LoopIdiomTransformPass();
+
+} // end namespace llvm
+
+namespace {
+
+class AArch64LoopIdiomTransform {
+  Loop *CurLoop = nullptr;
+  DominatorTree *DT;
+  LoopInfo *LI;
+  const TargetTransformInfo *TTI;
+  const DataLayout *DL;
+
+public:
+  explicit AArch64LoopIdiomTransform(DominatorTree *DT, LoopInfo *LI,
+ const TargetTransformInfo *TTI,
+ const DataLayout *DL)
+  : DT(DT), LI(LI), TTI(TTI), DL(DL) {}
+
+  bool run(Loop *L);
+
+private:
+  /// \name Countable Loop Idiom Handling
+  /// @{
+
+  bool runOnCountableLoop();
+  bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
+  SmallVectorImpl &ExitBlocks);
+
+  bool recognizeByteCompare();
+  Value *expandFindMismatch(IRBuilder<> &Builder, GetElementPtrInst *GEPA,
+GetElementPtrInst *GEPB, Instruction *Index,
+Value *Start, Value *MaxLen);
+  void transformByteCompare(GetElementPtrInst *GEPA, GetElementPtrInst *GEPB,
+PHINode *IndPhi, Value *MaxLen, Instruction *Index,
+Value *Start, bool IncIdx, BasicBlock *FoundBB,
+BasicBlock *EndBB);
+  /// @}
+};
+
+class AArch64LoopIdiomTransformLegacyPass : public LoopPass {
+public:
+  static char ID;
+
+  explicit AArch64LoopIdiomTransformLegacyPass() : LoopPass(ID) {
+initializeAArch64LoopIdiomTransformLegacyPassPass(
+*PassRegistry::getPassRegistry());
+  }
+
+  StringRef getPassName() const override {
+return "Transform AArch64-specific loop idioms";
+  }
+
+  void getAnalysisUsage(AnalysisUsage &AU) const override {
+AU.addRequired();
+AU.addRequired();
+AU.addRequired();
+  }
+
+  bool runOnLoop(Loop *L, LPPassManager &LPM) override;
+};
+
+bool AArch64LoopIdiomTransformLegacyPass::runOnLoop(Loop *L,
+LPPassManager &LPM) {
+
+  if (skipLoop(L))
+return false;
+
+  auto *DT = &getAnalysis().getDomTree();
+  auto *LI = &getAnalysis().getLoopInfo();
+  auto &TTI = getAnalysis().getTTI(
+  *L->getHeader()->getParent());
+  return AArch64LoopIdiomTransform(
+ DT, LI, &TTI, &L->getHeader()->getModule()->getDataLayout

[llvm] [clang] [clang-tools-extra] [AArch64] Add an AArch64 pass for loop idiom transformations (PR #72273)

2024-01-08 Thread David Green via cfe-commits

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

Thanks for the updates. From what I can tell this LGTM, but it will need a 
rebase.

You might want to commit it with the option disabled, and then flip the switch 
in a followup to avoid the commit-revert cycles in case there are any issues.

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


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

2024-01-08 Thread Ilya Biryukov 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;

ilya-biryukov wrote:

There is also a similar use of the name in `CheckCoroutineWrapper`, I suggest 
to unify the check for matching this particular function across the two call 
sites.

The motivation to disable this for `get_return_object` is clear: it's often 
used as an implementation detail, so warning there creates noise. There could 
be better ways to do it, though.

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][coro_lifetimebound] Detect lifetime issues with lambda captures (PR #77066)

2024-01-08 Thread Ilya Biryukov 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;

ilya-biryukov wrote:

It may not result in runtime errors (even in sanitizers), because this is never 
accessed, but I wonder if it is actually legal or UB in the standard?

AFAIK, calling a method if the object argument is `null` is UB, even if `this` 
is never accessed inside the method itself (citation needed, though, I looked 
at section of class member access and function call, but couldn't find a 
decisive wording there).

So, a coroutine frame ends up keeping a pointer to a lambda that goes out of 
scope. After initial suspension and on resume, it will probably **still call a 
method on that same pointer** per C++ standard.
Which makes me skew in the direction of warning for these cases two (but we 
need some proof from the standard gurus here)



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][coro_lifetimebound] Detect lifetime issues with lambda captures (PR #77066)

2024-01-08 Thread Ilya Biryukov 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;

ilya-biryukov wrote:

There are simple workarounds to silence these warnings in those cases:
- converting to a function pointer before call `(+[](){ ... co_await foo(); ... 
})()`,
- declaring a lambda as static  `[]() static { ... co_await foo(); ...}()` 
(starting with C++23).

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] [clang][Interp] Implement __builtin_addressof (PR #77303)

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

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/77303

We don't need to do anything here, since the input is already a Pointer. The 
only complexity is that we pre-classify the parameters as PT_Ptr, but they 
might end up being of a different pointer type, e.g. PT_FnPtr.

>From aa7ebd9f13d8b7a58f87dc8b00b99acca7f69196 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Mon, 11 Dec 2023 15:12:37 +0100
Subject: [PATCH] [clang][Interp] Implement __builtin_addressof

We don't need to do anything here, since the input is already a Pointer.
The only complexity is that we pre-classify the parameters as PT_Ptr,
but they might end up being of a different pointer type, e.g. PT_FnPtr.
---
 clang/lib/AST/Interp/Interp.cpp| 12 ++
 clang/lib/AST/Interp/InterpBuiltin.cpp | 33 +++---
 clang/test/AST/Interp/functions.cpp| 24 +++
 3 files changed, 66 insertions(+), 3 deletions(-)

diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 21ea2503b94bff..9de0926b9dba9c 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -134,6 +134,18 @@ void cleanupAfterFunctionCall(InterpState &S, CodePtr 
OpPC) {
   if (CurFunc->isUnevaluatedBuiltin())
 return;
 
+  // Some builtin functions require us to only look at the call site, since
+  // the classified parameter types do not match.
+  if (CurFunc->isBuiltin()) {
+const auto *CE =
+cast(S.Current->Caller->getExpr(S.Current->getRetPC()));
+for (int32_t I = CE->getNumArgs() - 1; I >= 0; --I) {
+  const Expr *A = CE->getArg(I);
+  popArg(S, A);
+}
+return;
+  }
+
   if (S.Current->Caller && CurFunc->isVariadic()) {
 // CallExpr we're look for is at the return PC of the current function, 
i.e.
 // in the caller.
diff --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index b55b1569a25983..d8df81961cc813 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -164,6 +164,8 @@ static bool retPrimValue(InterpState &S, CodePtr OpPC, 
APValue &Result,
   case X:  
\
 return Ret(S, OpPC, Result);
   switch (*T) {
+RET_CASE(PT_Ptr);
+RET_CASE(PT_FnPtr);
 RET_CASE(PT_Float);
 RET_CASE(PT_Bool);
 RET_CASE(PT_Sint8);
@@ -613,15 +615,34 @@ static bool interp__builtin_ffs(InterpState &S, CodePtr 
OpPC,
   return true;
 }
 
+static bool interp__builtin_addressof(InterpState &S, CodePtr OpPC,
+  const InterpFrame *Frame,
+  const Function *Func,
+  const CallExpr *Call) {
+  PrimType PtrT =
+  S.getContext().classify(Call->getArg(0)->getType()).value_or(PT_Ptr);
+
+  if (PtrT == PT_FnPtr) {
+const FunctionPointer &Arg = S.Stk.peek();
+S.Stk.push(Arg);
+  } else if (PtrT == PT_Ptr) {
+const Pointer &Arg = S.Stk.peek();
+S.Stk.push(Arg);
+  } else {
+assert(false);
+  }
+  return true;
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call) {
   InterpFrame *Frame = S.Current;
   APValue Dummy;
 
-  QualType ReturnType = Call->getCallReturnType(S.getCtx());
-  std::optional ReturnT = S.getContext().classify(ReturnType);
+  std::optional ReturnT = S.getContext().classify(Call->getType());
+
   // If classify failed, we assume void.
-  assert(ReturnT || ReturnType->isVoidType());
+  assert(ReturnT || Call->getType()->isVoidType());
 
   switch (F->getBuiltinID()) {
   case Builtin::BI__builtin_is_constant_evaluated:
@@ -820,6 +841,12 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const 
Function *F,
 if (!interp__builtin_ffs(S, OpPC, Frame, F, Call))
   return false;
 break;
+  case Builtin::BIaddressof:
+  case Builtin::BI__addressof:
+  case Builtin::BI__builtin_addressof:
+if (!interp__builtin_addressof(S, OpPC, Frame, F, Call))
+  return false;
+break;
 
   default:
 return false;
diff --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index 179a195098b132..75f3c5d192b2cf 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -389,3 +389,27 @@ namespace Packs {
   static_assert(foo() == 2, "");
   static_assert(foo<>() == 0, "");
 }
+
+namespace AddressOf {
+  struct S {} s;
+  static_assert(__builtin_addressof(s) == &s, "");
+
+  struct T { constexpr T *operator&() const { return nullptr; } int n; } t;
+  constexpr T *pt = __builtin_addressof(t);
+  static_assert(&pt->n == &t.n, "");
+
+  struct U { int n : 5; } u;
+  int *pbf = __builtin_addressof(u.n); // expected-error {{address of 
bit-field requested}} \
+   // ref-error {{address of bit-field 
requested}}
+
+  S *ptmp = __builtin_add

[clang] [clang][Interp] Implement __builtin_addressof (PR #77303)

2024-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

We don't need to do anything here, since the input is already a Pointer. The 
only complexity is that we pre-classify the parameters as PT_Ptr, but they 
might end up being of a different pointer type, e.g. PT_FnPtr.

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


3 Files Affected:

- (modified) clang/lib/AST/Interp/Interp.cpp (+12) 
- (modified) clang/lib/AST/Interp/InterpBuiltin.cpp (+30-3) 
- (modified) clang/test/AST/Interp/functions.cpp (+24) 


``diff
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 21ea2503b94bff..9de0926b9dba9c 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -134,6 +134,18 @@ void cleanupAfterFunctionCall(InterpState &S, CodePtr 
OpPC) {
   if (CurFunc->isUnevaluatedBuiltin())
 return;
 
+  // Some builtin functions require us to only look at the call site, since
+  // the classified parameter types do not match.
+  if (CurFunc->isBuiltin()) {
+const auto *CE =
+cast(S.Current->Caller->getExpr(S.Current->getRetPC()));
+for (int32_t I = CE->getNumArgs() - 1; I >= 0; --I) {
+  const Expr *A = CE->getArg(I);
+  popArg(S, A);
+}
+return;
+  }
+
   if (S.Current->Caller && CurFunc->isVariadic()) {
 // CallExpr we're look for is at the return PC of the current function, 
i.e.
 // in the caller.
diff --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index b55b1569a25983..d8df81961cc813 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -164,6 +164,8 @@ static bool retPrimValue(InterpState &S, CodePtr OpPC, 
APValue &Result,
   case X:  
\
 return Ret(S, OpPC, Result);
   switch (*T) {
+RET_CASE(PT_Ptr);
+RET_CASE(PT_FnPtr);
 RET_CASE(PT_Float);
 RET_CASE(PT_Bool);
 RET_CASE(PT_Sint8);
@@ -613,15 +615,34 @@ static bool interp__builtin_ffs(InterpState &S, CodePtr 
OpPC,
   return true;
 }
 
+static bool interp__builtin_addressof(InterpState &S, CodePtr OpPC,
+  const InterpFrame *Frame,
+  const Function *Func,
+  const CallExpr *Call) {
+  PrimType PtrT =
+  S.getContext().classify(Call->getArg(0)->getType()).value_or(PT_Ptr);
+
+  if (PtrT == PT_FnPtr) {
+const FunctionPointer &Arg = S.Stk.peek();
+S.Stk.push(Arg);
+  } else if (PtrT == PT_Ptr) {
+const Pointer &Arg = S.Stk.peek();
+S.Stk.push(Arg);
+  } else {
+assert(false);
+  }
+  return true;
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call) {
   InterpFrame *Frame = S.Current;
   APValue Dummy;
 
-  QualType ReturnType = Call->getCallReturnType(S.getCtx());
-  std::optional ReturnT = S.getContext().classify(ReturnType);
+  std::optional ReturnT = S.getContext().classify(Call->getType());
+
   // If classify failed, we assume void.
-  assert(ReturnT || ReturnType->isVoidType());
+  assert(ReturnT || Call->getType()->isVoidType());
 
   switch (F->getBuiltinID()) {
   case Builtin::BI__builtin_is_constant_evaluated:
@@ -820,6 +841,12 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const 
Function *F,
 if (!interp__builtin_ffs(S, OpPC, Frame, F, Call))
   return false;
 break;
+  case Builtin::BIaddressof:
+  case Builtin::BI__addressof:
+  case Builtin::BI__builtin_addressof:
+if (!interp__builtin_addressof(S, OpPC, Frame, F, Call))
+  return false;
+break;
 
   default:
 return false;
diff --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index 179a195098b132..75f3c5d192b2cf 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -389,3 +389,27 @@ namespace Packs {
   static_assert(foo() == 2, "");
   static_assert(foo<>() == 0, "");
 }
+
+namespace AddressOf {
+  struct S {} s;
+  static_assert(__builtin_addressof(s) == &s, "");
+
+  struct T { constexpr T *operator&() const { return nullptr; } int n; } t;
+  constexpr T *pt = __builtin_addressof(t);
+  static_assert(&pt->n == &t.n, "");
+
+  struct U { int n : 5; } u;
+  int *pbf = __builtin_addressof(u.n); // expected-error {{address of 
bit-field requested}} \
+   // ref-error {{address of bit-field 
requested}}
+
+  S *ptmp = __builtin_addressof(S{}); // expected-error {{taking the address 
of a temporary}} \
+  // expected-warning {{temporary whose 
address is used as value of local variable 'ptmp' will be destroyed at the end 
of the full-expression}} \
+  // ref-error {{taking the address of a 
temporary}} \
+  // ref-w

[clang] [CLANG] Add warning when comparing to INF or NAN in fast math mode. (PR #76873)

2024-01-08 Thread Zahira Ammarguellat via cfe-commits

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


[clang] [CLANG] Add warning when comparing to INF or NAN in fast math mode. (PR #76873)

2024-01-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Zahira Ammarguellat (zahiraam)


Changes

Check for comparisons to INF and NaN when in ffast-math mode and generate a 
warning.

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


5 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) 
- (modified) clang/include/clang/Sema/Sema.h (+7-2) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+74-6) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+5-2) 
- (added) clang/test/Sema/warn-fp-fast-compare.cpp (+245) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index e54f969c19039d..d19be567a1bf66 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6771,6 +6771,9 @@ def warn_pointer_sub_null_ptr : Warning<
 def warn_floatingpoint_eq : Warning<
   "comparing floating point with == or != is unsafe">,
   InGroup>, DefaultIgnore;
+def warn_fast_floatingpoint_eq : Warning<
+  "explicit comparison with %0 when the program is assumed to not use or 
produce %0">,
+  InGroup;
 
 def err_setting_eval_method_used_in_unsafe_context : Error <
   "%select{'#pragma clang fp eval_method'|option 'ffp-eval-method'}0 cannot be 
used with "
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5e3b57ea33220b..b19ce6312e83bc 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13893,8 +13893,9 @@ class Sema final {
 
   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
-  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
-  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
+  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
+  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
+   unsigned BuiltinID);
   bool SemaBuiltinComplex(CallExpr *TheCall);
   bool SemaBuiltinVSX(CallExpr *TheCall);
   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
@@ -13998,6 +13999,8 @@ class Sema final {
 SourceRange range,
 llvm::SmallBitVector &CheckedVarArgs);
 
+  void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
+
   void CheckAbsoluteValueFunction(const CallExpr *Call,
   const FunctionDecl *FDecl);
 
@@ -14024,6 +14027,8 @@ class Sema final {
 public:
   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
 BinaryOperatorKind Opcode);
+  void CheckInfNaNFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
+  BinaryOperatorKind Opcode);
 
 private:
   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 3168d38dd66c36..2c4d628ab160d2 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2169,6 +2169,7 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, 
unsigned BuiltinID,
 ICEArguments &= ~(1 << ArgNo);
   }
 
+  FPOptions FPO;
   switch (BuiltinID) {
   case Builtin::BI__builtin___CFStringMakeConstantString:
 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
@@ -2245,15 +2246,15 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, 
unsigned BuiltinID,
   case Builtin::BI__builtin_islessequal:
   case Builtin::BI__builtin_islessgreater:
   case Builtin::BI__builtin_isunordered:
-if (SemaBuiltinUnorderedCompare(TheCall))
+if (SemaBuiltinUnorderedCompare(TheCall, BuiltinID))
   return ExprError();
 break;
   case Builtin::BI__builtin_fpclassify:
-if (SemaBuiltinFPClassification(TheCall, 6))
+if (SemaBuiltinFPClassification(TheCall, 6, BuiltinID))
   return ExprError();
 break;
   case Builtin::BI__builtin_isfpclass:
-if (SemaBuiltinFPClassification(TheCall, 2))
+if (SemaBuiltinFPClassification(TheCall, 2, BuiltinID))
   return ExprError();
 break;
   case Builtin::BI__builtin_isfinite:
@@ -2267,7 +2268,7 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, 
unsigned BuiltinID,
   case Builtin::BI__builtin_signbit:
   case Builtin::BI__builtin_signbitf:
   case Builtin::BI__builtin_signbitl:
-if (SemaBuiltinFPClassification(TheCall, 1))
+if (SemaBuiltinFPClassification(TheCall, 1, BuiltinID))
   return ExprError();
 break;
   case Builtin::BI__builtin_shufflevector:
@@ -7621,6 +7622,7 @@ bool Sema::CheckFunctionCall(FunctionDecl *FDecl, 
CallExpr *TheCall,
 
   CheckAbsoluteValueFunction(TheCall, FDecl);
   CheckMaxUnsignedZero(TheCall, FDecl);
+  CheckInfNaNFunction(TheCall, FDecl);
 
   if (getLangOpts().ObjC)
 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
@@ -9090,10 +90

[clang] [CLANG] Add warning when INF or NAN are used in a binary operation or as function argument in fast math mode. (PR #76873)

2024-01-08 Thread Zahira Ammarguellat via cfe-commits

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


[clang] [CLANG] Add warning when INF or NAN are used in a binary operation or as function argument in fast math mode. (PR #76873)

2024-01-08 Thread Zahira Ammarguellat via cfe-commits

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


[llvm] [clang] [ASan][Driver] Add sanitize-target flag to support enabling ASan in device or host compilation (PR #76127)

2024-01-08 Thread via cfe-commits

jinge90 wrote:

Hi, @MaskRay and @AaronBallman 
Kind ping~.
Thanks very much.

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


[clang] [clang] Fix assertion failure when initializing union with FAM (PR #77298)

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

tbaederr wrote:

Needs a short release note.

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


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

2024-01-08 Thread Phoebe Wang via cfe-commits


@@ -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

phoebewang wrote:

Do you mean AVX512PF? By clang-cl?

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


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

2024-01-08 Thread via cfe-commits

agozillon 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 believe Flang inherits this functionality via the addOpenMPDeviceLibC 
function in CommonArgs.cpp, which gets called after the Fortran runtime 
libraries are added for each of the relevant ToolChains (gnu etc.) from what I 
can tell! It's where the gpulibc/nogpulibc flags are also handled. However, the 
desired library doesn't reside in those directories with a regular build 
command, you seem to require adding the building of GPU libc specifically to 
your build options and then subsequently installing the build into a directory! 
The build I've tested with is an amalgamation of Clang/OpenMP/Flang/GPU LIBC.

That is to say the auto find and include seems to work quite happily for Flang 
(at least when the whole host of projects are enabled and installed), but 
having the options available would be desirable, the most important cases being 
to be able to turn off GPU libc inclusion in an installed build and turn it on 
in a regular non-installed build (provided it can find it in your environments 
path). Just more flexibility to replicate what Clang has just now.

> > 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 :)

True, thank you :-)! 

> 
> > 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.

Thank you I'll add a similar test to the PR in the 
flang/test/Driver/omp-driver-offload.f90 test file, I believe this is still the 
closest equivalent we have to openmp-offload-gpu.c, but please do correct me if 
I am wrong!


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] f0f16be - [clang][Sema][NFC] Clean up BuildOverloadedCallExpr

2024-01-08 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-01-08T15:04:52+01:00
New Revision: f0f16be77e1977d04535556ef69eaccd5bfef36f

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

LOG: [clang][Sema][NFC] Clean up BuildOverloadedCallExpr

Added: 


Modified: 
clang/lib/Sema/SemaOverload.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 8e3a2d1288079b..07da5cb150b467 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -13999,17 +13999,14 @@ ExprResult Sema::BuildOverloadedCallExpr(Scope *S, 
Expr *Fn,
   // encloses the call and whose return type contains a placeholder type as if
   // the UnresolvedLookupExpr was type-dependent.
   if (OverloadResult == OR_Success) {
-FunctionDecl *FDecl = Best->Function;
+const FunctionDecl *FDecl = Best->Function;
 if (FDecl && FDecl->isTemplateInstantiation() &&
 FDecl->getReturnType()->isUndeducedType()) {
-  if (auto TP = FDecl->getTemplateInstantiationPattern(false)) {
-if (TP->willHaveBody()) {
-  CallExpr *CE =
-  CallExpr::Create(Context, Fn, Args, Context.DependentTy,
-   VK_PRValue, RParenLoc, CurFPFeatureOverrides());
-  result = CE;
-  return result;
-}
+  if (const auto *TP =
+  FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
+  TP && TP->willHaveBody()) {
+return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
+VK_PRValue, RParenLoc, 
CurFPFeatureOverrides());
   }
 }
   }



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


[clang] [ARM] arm_acle.h add Coprocessor Instrinsics (PR #75440)

2024-01-08 Thread via cfe-commits

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

>From ee562f7e8e8577ee93631a8425efd80e7ce64c18 Mon Sep 17 00:00:00 2001
From: hstk30-hw 
Date: Thu, 14 Dec 2023 15:40:03 +0800
Subject: [PATCH] feat: arm_acle.h add Coprocessor Instrinsics

---
 clang/lib/Basic/Targets/ARM.cpp   |  64 +++
 clang/lib/Basic/Targets/ARM.h |  13 +
 clang/lib/Headers/arm_acle.h  |  59 +++
 clang/test/CodeGen/arm-acle-coproc.c  | 383 ++
 .../Preprocessor/aarch64-target-features.c|   1 +
 5 files changed, 520 insertions(+)
 create mode 100644 clang/test/CodeGen/arm-acle-coproc.c

diff --git a/clang/lib/Basic/Targets/ARM.cpp b/clang/lib/Basic/Targets/ARM.cpp
index ce7e4d4639ceac..c705d30cf6bf42 100644
--- a/clang/lib/Basic/Targets/ARM.cpp
+++ b/clang/lib/Basic/Targets/ARM.cpp
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
+#include "llvm/TargetParser/ARMTargetParser.h"
 
 using namespace clang;
 using namespace clang::targets;
@@ -836,6 +837,69 @@ void ARMTargetInfo::getTargetDefines(const LangOptions 
&Opts,
   if (Opts.RWPI)
 Builder.defineMacro("__ARM_RWPI", "1");
 
+  // Macros for enabling co-proc intrinsics
+  uint64_t FeatureCoprocBF = 0;
+  switch (ArchKind) {
+  default:
+break;
+  case llvm::ARM::ArchKind::ARMV4:
+  case llvm::ARM::ArchKind::ARMV4T:
+// Filter __arm_ldcl and __arm_stcl in acle.h
+FeatureCoprocBF = isThumb() ? 0 : FEATURE_COPROC_B1;
+break;
+  case llvm::ARM::ArchKind::ARMV5T:
+FeatureCoprocBF = isThumb() ? 0 : FEATURE_COPROC_B1 | FEATURE_COPROC_B2;
+break;
+  case llvm::ARM::ArchKind::ARMV5TE:
+  case llvm::ARM::ArchKind::ARMV5TEJ:
+if (!isThumb())
+  FeatureCoprocBF =
+  FEATURE_COPROC_B1 | FEATURE_COPROC_B2 | FEATURE_COPROC_B3;
+break;
+  case llvm::ARM::ArchKind::ARMV6:
+  case llvm::ARM::ArchKind::ARMV6K:
+  case llvm::ARM::ArchKind::ARMV6KZ:
+  case llvm::ARM::ArchKind::ARMV6T2:
+if (!isThumb() || ArchKind == llvm::ARM::ArchKind::ARMV6T2)
+  FeatureCoprocBF = FEATURE_COPROC_B1 | FEATURE_COPROC_B2 |
+FEATURE_COPROC_B3 | FEATURE_COPROC_B4;
+break;
+  case llvm::ARM::ArchKind::ARMV7A:
+  case llvm::ARM::ArchKind::ARMV7R:
+  case llvm::ARM::ArchKind::ARMV7M:
+  case llvm::ARM::ArchKind::ARMV7S:
+  case llvm::ARM::ArchKind::ARMV7EM:
+FeatureCoprocBF = FEATURE_COPROC_B1 | FEATURE_COPROC_B2 |
+  FEATURE_COPROC_B3 | FEATURE_COPROC_B4;
+break;
+  case llvm::ARM::ArchKind::ARMV8A:
+  case llvm::ARM::ArchKind::ARMV8R:
+  case llvm::ARM::ArchKind::ARMV8_1A:
+  case llvm::ARM::ArchKind::ARMV8_2A:
+  case llvm::ARM::ArchKind::ARMV8_3A:
+  case llvm::ARM::ArchKind::ARMV8_4A:
+  case llvm::ARM::ArchKind::ARMV8_5A:
+  case llvm::ARM::ArchKind::ARMV8_6A:
+  case llvm::ARM::ArchKind::ARMV8_7A:
+  case llvm::ARM::ArchKind::ARMV8_8A:
+  case llvm::ARM::ArchKind::ARMV8_9A:
+  case llvm::ARM::ArchKind::ARMV9A:
+  case llvm::ARM::ArchKind::ARMV9_1A:
+  case llvm::ARM::ArchKind::ARMV9_2A:
+  case llvm::ARM::ArchKind::ARMV9_3A:
+  case llvm::ARM::ArchKind::ARMV9_4A:
+// Filter __arm_cdp, __arm_ldcl, __arm_stcl in arm_acle.h
+FeatureCoprocBF = FEATURE_COPROC_B1 | FEATURE_COPROC_B3;
+break;
+  case llvm::ARM::ArchKind::ARMV8MMainline:
+  case llvm::ARM::ArchKind::ARMV8_1MMainline:
+FeatureCoprocBF = FEATURE_COPROC_B1 | FEATURE_COPROC_B2 |
+  FEATURE_COPROC_B3 | FEATURE_COPROC_B4;
+break;
+  }
+  Builder.defineMacro("__ARM_FEATURE_COPROC",
+  "0x" + Twine::utohexstr(FeatureCoprocBF));
+
   if (ArchKind == llvm::ARM::ArchKind::XSCALE)
 Builder.defineMacro("__XSCALE__");
 
diff --git a/clang/lib/Basic/Targets/ARM.h b/clang/lib/Basic/Targets/ARM.h
index b1aa2794c7e4c3..9802eb01abf3c4 100644
--- a/clang/lib/Basic/Targets/ARM.h
+++ b/clang/lib/Basic/Targets/ARM.h
@@ -100,6 +100,19 @@ class LLVM_LIBRARY_VISIBILITY ARMTargetInfo : public 
TargetInfo {
   };
   uint32_t HW_FP;
 
+  enum {
+/// __arm_cdp __arm_ldc, __arm_ldcl, __arm_stc,
+/// __arm_stcl, __arm_mcr and __arm_mrc
+FEATURE_COPROC_B1 = (1 << 0),
+/// __arm_cdp2, __arm_ldc2, __arm_stc2, __arm_ldc2l,
+/// __arm_stc2l, __arm_mcr2 and __arm_mrc2
+FEATURE_COPROC_B2 = (1 << 1),
+/// __arm_mcrr, __arm_mrrc
+FEATURE_COPROC_B3 = (1 << 2),
+/// __arm_mcrr2,  __arm_mrrc2
+FEATURE_COPROC_B4 = (1 << 3),
+  };
+
   void setABIAAPCS();
   void setABIAPCS(bool IsAAPCS16);
 
diff --git a/clang/lib/Headers/arm_acle.h b/clang/lib/Headers/arm_acle.h
index 61d80258d166a1..9aae2285aeb1d8 100644
--- a/clang/lib/Headers/arm_acle.h
+++ b/clang/lib/Headers/arm_acle.h
@@ -756,6 +756,65 @@ __arm_st64bv0(void *__addr, data512_t __value) {
   __builtin_arm_mops_memset_tag(__tagged_address, __value, __size)
 #endif
 
+/* Coprocessor Intrinsics */
+#if defined(__ARM_FEATURE_COPROC)
+
+#if (__ARM_FEATURE_COPROC &

[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-08 Thread via cfe-commits

agozillon wrote:

> > I am gonna sign off for the weekend as it's quite late here, so I'll reply 
> > in a little more detail on Monday and update the PR further. but I'd be 
> > happy to add a further flang test, although not too sure what it'd be, so 
> > suggestions are welcome.
> > I tested this with an out of tree build of GPU libc (basically two seperate 
> > build directories) and found that -lgpuc wouldn't get the ordering correct 
> > to link the library correctly to the fortran runtime, so it seemed for this 
> > specific case of an out of tree build of GPU libc the option was the 
> > correct way to get it linked in in the correct order. In the case of it 
> > finding it in the correct directory i didn't quite manage the perfect build 
> > recipe for it (suggestions welcome here as well) and tend to not use the 
> > install option myself, but perhaps it would auto detect for Flang as well! 
> > However, in the case where it's an separately compiled and installed gpu 
> > libc it might be nice to have this option activated as well for Flang to 
> > make both methods of linking possible. However, i am a little bit of a 
> > driver and build environment/system noob so ill defer to everyone else's 
> > better judgement in this case!
> 
> If you have the static library, and it contains an entry for the desired 
> architecture, it should just work so long as you're using the "new" driver 
> pipeline. However, ordering is important here. It behaves similarly to the 
> GNU BFD linker, where a static library is only checked against the current 
> state of the symbol table as it reads the files in input order. So `uses.o 
> -lfoo` will extract but `-lfoo uses.o` will not.
> 
> It's possible that this just was being linked too late with however Fortran 
> handles it. I decided to be conservative with the default here because I'm 
> assuming very few people will actually have the GPU `libc`.

I think it might just have been a little too late, or perhaps I was doing it 
incorrectly, always a possibility, but in either case it's possible to have it 
auto-included similarly to Clang with Flang, if the library resides in the 
correct directory and if it's not available in the directory enabling these 
options will allow it to still be linked into the runtime correctly when the 
correct one is specified on the command line! So I believe it will work fine in 
the above cases, just passing the library directly on the command line via 
-lcgpu  just won't work to resolve the necessary calls in the fortran runtime 
for now unfortunately, but as the other two methods work fine it's not 
particularly necessary! 

> It would be very interesting to see something like `puts` working from 
> Fortran, so let me know if there's anything I can do to help.

I'd love to try more complex programs in the near future that depend on more 
runtime features (in particular the stdout you mentioned previously would be 
interesting to try, but I'm not too sure how the print functionality in 
flang-new actually works at the moment), for the moment this has primarily just 
been me trying to fix a test I came across that will utilise a Fortran runtime 
function on device without a user explicitly calling it (an assign operation 
that lowers to a runtime function call) and it works quite nicely with a 
fortran runtime compiled for GPU and then linked into the GPU libc library for 
now (with some other not driver or library related changes)! I imagine we'll be 
running into more uses for the runtime on device in the near future to test.  

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] [AST] Teach TextNodeDumper to print the "implicit" bit for coroutine AST nodes (PR #77311)

2024-01-08 Thread Haojian Wu via cfe-commits

https://github.com/hokein created 
https://github.com/llvm/llvm-project/pull/77311

None

>From b0efa2e20f1ca7bc9e18b81231574895fe2281c3 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Mon, 8 Jan 2024 14:43:40 +0100
Subject: [PATCH] [AST] TextNodeDumper print the "implicit" bit for coroutine
 AST nodes

---
 clang/include/clang/AST/TextNodeDumper.h |  2 ++
 clang/lib/AST/TextNodeDumper.cpp | 10 ++
 clang/test/AST/ast-dump-coroutine.cpp| 46 
 3 files changed, 58 insertions(+)
 create mode 100644 clang/test/AST/ast-dump-coroutine.cpp

diff --git a/clang/include/clang/AST/TextNodeDumper.h 
b/clang/include/clang/AST/TextNodeDumper.h
index 2f4ed082a0c7ad..dd9ed56fc584a7 100644
--- a/clang/include/clang/AST/TextNodeDumper.h
+++ b/clang/include/clang/AST/TextNodeDumper.h
@@ -252,6 +252,8 @@ class TextNodeDumper
   void VisitGotoStmt(const GotoStmt *Node);
   void VisitCaseStmt(const CaseStmt *Node);
   void VisitReturnStmt(const ReturnStmt *Node);
+  void VisitCoawaitExpr(const CoawaitExpr* Node);
+  void VisitCoreturnStmt(const CoreturnStmt *Node);
   void VisitCompoundStmt(const CompoundStmt *Node);
   void VisitConstantExpr(const ConstantExpr *Node);
   void VisitCallExpr(const CallExpr *Node);
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index e8274fcd5cfe9c..d53688ea862e34 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -1094,6 +1094,16 @@ void clang::TextNodeDumper::VisitReturnStmt(const 
ReturnStmt *Node) {
   }
 }
 
+void clang::TextNodeDumper::VisitCoawaitExpr(const CoawaitExpr* Node) {
+  if (Node->isImplicit())
+OS << " implicit";
+}
+
+void clang::TextNodeDumper::VisitCoreturnStmt(const CoreturnStmt *Node) {
+  if (Node->isImplicit())
+OS << " implicit";
+}
+
 void TextNodeDumper::VisitConstantExpr(const ConstantExpr *Node) {
   if (Node->hasAPValueResult())
 AddChild("value",
diff --git a/clang/test/AST/ast-dump-coroutine.cpp 
b/clang/test/AST/ast-dump-coroutine.cpp
new file mode 100644
index 00..f760809f53689a
--- /dev/null
+++ b/clang/test/AST/ast-dump-coroutine.cpp
@@ -0,0 +1,46 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -std=c++20 \
+// RUN:-fsyntax-only -ast-dump -ast-dump-filter test | FileCheck %s
+
+#include "Inputs/std-coroutine.h"
+
+using namespace std;
+
+struct Task {
+  struct promise_type {
+std::suspend_always initial_suspend() { return {}; }
+Task get_return_object() {
+  return std::coroutine_handle::from_promise(*this);
+}
+std::suspend_always final_suspend() noexcept { return {}; }
+std::suspend_always return_void() { return {}; }
+void unhandled_exception() {}
+
+auto await_transform(int s) {
+  struct awaiter {
+promise_type *promise;
+bool await_ready() { return true; }
+int await_resume() { return 1; }
+void await_suspend(std::coroutine_handle<>) {}
+  };
+
+  return awaiter{this};
+}
+  };
+
+  Task(std::coroutine_handle promise);
+
+  std::coroutine_handle handle;
+};
+
+// Verify the implicit AST nodes for coroutines.
+Task test()  {
+  co_await 1;
+}
+// CHECK:|-DeclStmt {{.*}}
+// CHECK-NEXT:   | `-VarDecl {{.*}} implicit used __promise
+// CHECK-NEXT:   |   `-CXXConstructExpr {{.*}}
+// CHECK-NEXT:   |-ExprWithCleanups {{.*}} 'void'
+// CHECK-NEXT:   | `-CoawaitExpr {{.*}} 'void' implicit
+// ...
+// FIXME: the CoreturnStmt should be marked as implicit
+// CHECK: CoreturnStmt {{.*}} 

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


[clang-tools-extra] [libc] [mlir] [clang] [lld] [lldb] [compiler-rt] [libcxx] [llvm] [MLIR][LLVM] Add Continuous Loop Peeling transform to SCF (PR #71555)

2024-01-08 Thread Matthias Springer via cfe-commits


@@ -105,6 +106,167 @@ static void specializeForLoopForUnrolling(ForOp op) {
   op.erase();
 }
 
+/// Create a new for loop for the remaining iterations (partiaIteration)
+/// after a for loop has been peeled. This is followed by correcting the
+/// loop bounds for both loops given the index (splitBound) where the
+/// iteration space is to be split up.
+static LogicalResult splitLoopHelper(RewriterBase &b, scf::ForOp forOp,
+ scf::ForOp &partialIteration,
+ Value &splitBound) {
+  RewriterBase::InsertionGuard guard(b);
+  auto lbInt = getConstantIntValue(forOp.getLowerBound());
+  auto ubInt = getConstantIntValue(forOp.getUpperBound());
+  auto stepInt = getConstantIntValue(forOp.getStep());
+
+  // No specialization necessary if step already divides upper bound evenly.
+  if (lbInt && ubInt && stepInt && (*ubInt - *lbInt) % *stepInt == 0)
+return failure();
+  // No specialization necessary if step size is 1.
+  if (stepInt == static_cast(1))
+return failure();
+
+  // Create ForOp for partial iteration.
+  b.setInsertionPointAfter(forOp);
+  partialIteration = cast(b.clone(*forOp.getOperation()));
+  partialIteration.getLowerBoundMutable().assign(splitBound);
+  forOp.replaceAllUsesWith(partialIteration->getResults());
+  partialIteration.getInitArgsMutable().assign(forOp->getResults());
+
+  // Set new upper loop bound.
+  b.updateRootInPlace(
+  forOp, [&]() { forOp.getUpperBoundMutable().assign(splitBound); });
+
+  return success();
+}
+
+/// Convert single-iteration for loop to if-else block.
+static scf::IfOp convertSingleIterFor(RewriterBase &b, scf::ForOp &forOp) {
+  Location loc = forOp->getLoc();
+  IRMapping mapping;
+  mapping.map(forOp.getInductionVar(), forOp.getLowerBound());
+  for (auto [arg, operand] :
+   llvm::zip_equal(forOp.getRegionIterArgs(), forOp.getInitsMutable())) {
+mapping.map(arg, operand.get());
+  }
+  b.setInsertionPoint(forOp);
+  auto cond =
+  b.create(loc, arith::CmpIPredicate::slt,
+  forOp.getLowerBound(), forOp.getUpperBound());
+  auto ifOp = b.create(loc, forOp->getResultTypes(), cond, true);

matthias-springer wrote:

`/*withElseRegion=*/true`

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


[libcxx] [mlir] [lldb] [llvm] [compiler-rt] [clang] [libc] [clang-tools-extra] [lld] [MLIR][LLVM] Add Continuous Loop Peeling transform to SCF (PR #71555)

2024-01-08 Thread Matthias Springer via cfe-commits


@@ -105,6 +106,167 @@ static void specializeForLoopForUnrolling(ForOp op) {
   op.erase();
 }
 
+/// Create a new for loop for the remaining iterations (partiaIteration)
+/// after a for loop has been peeled. This is followed by correcting the
+/// loop bounds for both loops given the index (splitBound) where the
+/// iteration space is to be split up.
+static LogicalResult splitLoopHelper(RewriterBase &b, scf::ForOp forOp,
+ scf::ForOp &partialIteration,
+ Value &splitBound) {

matthias-springer wrote:

Do not pass `splitBound` as reference. Otherwise it looks like a return value.

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


  1   2   3   4   5   >