[llvm] [clang] [NFC][InstrProf] Refactor InstrProfiling lowering pass (PR #74970)

2023-12-10 Thread Kazu Hirata via cfe-commits

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

LGTM module stylistic comments.

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


[clang] [llvm] [NFC][InstrProf] Refactor InstrProfiling lowering pass (PR #74970)

2023-12-10 Thread Kazu Hirata via cfe-commits


@@ -31,31 +31,45 @@ using LoadStorePair = std::pair;
 /// Instrumentation based profiling lowering pass. This pass lowers
 /// the profile instrumented code generated by FE or the IR based
 /// instrumentation pass.
-class InstrProfiling : public PassInfoMixin {
+class InstrProfilingLoweringPass
+: public PassInfoMixin {
+  const InstrProfOptions Options;
+  // Is this lowering for the context-sensitive instrumentation.
+  const bool IsCS;
+
 public:
-  InstrProfiling() : IsCS(false) {}
-  InstrProfiling(const InstrProfOptions &Options, bool IsCS = false)
+  InstrProfilingLoweringPass() : IsCS(false) {}
+  InstrProfilingLoweringPass(const InstrProfOptions &Options, bool IsCS = 
false)
   : Options(Options), IsCS(IsCS) {}
 
   PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
-  bool run(Module &M,
-   std::function GetTLI);
+};
+class InstrProfiling final {

kazutakahirata wrote:

May I suggest an empty line just before `class InstrProfiling final {`?

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


[clang] [llvm] [NFC][InstrProf] Refactor InstrProfiling lowering pass (PR #74970)

2023-12-10 Thread Kazu Hirata via cfe-commits

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


[clang] [llvm] [NFC][InstrProf] Refactor InstrProfiling lowering pass (PR #74970)

2023-12-10 Thread Kazu Hirata via cfe-commits


@@ -31,31 +31,45 @@ using LoadStorePair = std::pair;
 /// Instrumentation based profiling lowering pass. This pass lowers
 /// the profile instrumented code generated by FE or the IR based
 /// instrumentation pass.
-class InstrProfiling : public PassInfoMixin {
+class InstrProfilingLoweringPass
+: public PassInfoMixin {
+  const InstrProfOptions Options;
+  // Is this lowering for the context-sensitive instrumentation.
+  const bool IsCS;
+
 public:
-  InstrProfiling() : IsCS(false) {}
-  InstrProfiling(const InstrProfOptions &Options, bool IsCS = false)
+  InstrProfilingLoweringPass() : IsCS(false) {}

kazutakahirata wrote:

We could "move" `false` to the declaration above:

`InstrProfilingLoweringPass() = default;`


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


[clang] [llvm] [NFC][InstrProf] Refactor InstrProfiling lowering pass (PR #74970)

2023-12-10 Thread Kazu Hirata via cfe-commits


@@ -31,31 +31,45 @@ using LoadStorePair = std::pair;
 /// Instrumentation based profiling lowering pass. This pass lowers
 /// the profile instrumented code generated by FE or the IR based
 /// instrumentation pass.
-class InstrProfiling : public PassInfoMixin {
+class InstrProfilingLoweringPass
+: public PassInfoMixin {
+  const InstrProfOptions Options;
+  // Is this lowering for the context-sensitive instrumentation.
+  const bool IsCS;

kazutakahirata wrote:

Could we say `const bool IsCS = false;`here  to enable the defaulted default 
constructor below?

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


[clang] [Cygwin] Cygwin driver (PR #74933)

2023-12-10 Thread 徐持恒 Xu Chiheng via cfe-commits

https://github.com/xu-chiheng updated 
https://github.com/llvm/llvm-project/pull/74933

From daa6702f698724655b91c4fa52272c09924d2d83 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BE=90=E6=8C=81=E6=81=92=20Xu=20Chiheng?=
 
Date: Sat, 9 Dec 2023 21:51:29 +0800
Subject: [PATCH 1/6] 1

---
 clang/lib/Driver/CMakeLists.txt|   1 +
 clang/lib/Driver/Driver.cpp|   4 +
 clang/lib/Driver/ToolChains/Cygwin.cpp | 731 +
 clang/lib/Driver/ToolChains/Cygwin.h   | 125 +
 clang/lib/Lex/InitHeaderSearch.cpp |  30 +-
 5 files changed, 865 insertions(+), 26 deletions(-)
 create mode 100644 clang/lib/Driver/ToolChains/Cygwin.cpp
 create mode 100644 clang/lib/Driver/ToolChains/Cygwin.h

diff --git a/clang/lib/Driver/CMakeLists.txt b/clang/lib/Driver/CMakeLists.txt
index 58427e3f83c420..7ab5a1ee963515 100644
--- a/clang/lib/Driver/CMakeLists.txt
+++ b/clang/lib/Driver/CMakeLists.txt
@@ -51,6 +51,7 @@ add_clang_library(clangDriver
   ToolChains/CrossWindows.cpp
   ToolChains/CSKYToolChain.cpp
   ToolChains/Cuda.cpp
+  ToolChains/Cygwin.cpp
   ToolChains/Darwin.cpp
   ToolChains/DragonFly.cpp
   ToolChains/Flang.cpp
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index e241706b9082ee..b6f3da3a006f4e 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -17,6 +17,7 @@
 #include "ToolChains/Clang.h"
 #include "ToolChains/CrossWindows.h"
 #include "ToolChains/Cuda.h"
+#include "ToolChains/Cygwin.h"
 #include "ToolChains/Darwin.h"
 #include "ToolChains/DragonFly.h"
 #include "ToolChains/FreeBSD.h"
@@ -6263,6 +6264,9 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
 else
   TC = std::make_unique(*this, Target, Args);
 break;
+  case llvm::Triple::Cygnus:
+TC = std::make_unique(*this, Target, Args);
+break;
   case llvm::Triple::GNU:
 TC = std::make_unique(*this, Target, Args);
 break;
diff --git a/clang/lib/Driver/ToolChains/Cygwin.cpp 
b/clang/lib/Driver/ToolChains/Cygwin.cpp
new file mode 100644
index 00..8aa9cf5c8ec034
--- /dev/null
+++ b/clang/lib/Driver/ToolChains/Cygwin.cpp
@@ -0,0 +1,731 @@
+//===--- Cygwin.cpp - CygwinToolChain Implementation 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "Cygwin.h"
+#include "CommonArgs.h"
+#include "clang/Config/config.h"
+#include "clang/Driver/Compilation.h"
+#include "clang/Driver/Driver.h"
+#include "clang/Driver/DriverDiagnostic.h"
+#include "clang/Driver/InputInfo.h"
+#include "clang/Driver/Options.h"
+#include "clang/Driver/SanitizerArgs.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include 
+
+using namespace clang::diag;
+using namespace clang::driver;
+using namespace clang;
+using namespace llvm::opt;
+
+/// Cygwin Tools
+void tools::Cygwin::Assembler::ConstructJob(Compilation &C, const JobAction 
&JA,
+   const InputInfo &Output,
+   const InputInfoList &Inputs,
+   const ArgList &Args,
+   const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
+  ArgStringList CmdArgs;
+
+  if (getToolChain().getArch() == llvm::Triple::x86) {
+CmdArgs.push_back("--32");
+  } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
+CmdArgs.push_back("--64");
+  }
+
+  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, 
options::OPT_Xassembler);
+
+  CmdArgs.push_back("-o");
+  CmdArgs.push_back(Output.getFilename());
+
+  for (const auto &II : Inputs)
+CmdArgs.push_back(II.getFilename());
+
+  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
+  C.addCommand(std::make_unique(JA, *this, 
ResponseFileSupport::None(),
+ Exec, CmdArgs, Inputs, Output));
+
+  if (Args.hasArg(options::OPT_gsplit_dwarf))
+SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
+   SplitDebugName(JA, Args, Inputs[0], Output));
+}
+
+void tools::Cygwin::Linker::AddLibGCC(const ArgList &Args,
+ ArgStringList &CmdArgs) const {
+  // Make use of compiler-rt if --rtlib option is used
+  ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
+  if (RLT == ToolChain::RLT_Libgcc) {
+bool Static = Args.hasArg(options::OPT_static_libgcc) ||
+  Args.hasArg(options::OPT_static);
+bool Shared = Args.hasArg(options::OPT_shared);
+bool CXX = getToolChain().getDriver().CCCIsCXX();
+
+if (Static || (!CXX && !S

[clang] [Cygwin] Reduced number of inline elements of CallArgList. (PR #74977)

2023-12-10 Thread 徐持恒 Xu Chiheng via cfe-commits

xu-chiheng wrote:

> Just FYI submitting lots of PRs with all of them having commits with a commit 
> message of 1 is not going to go anywhere. They need to be revised with proper 
> meaningful commit messages.

This fix bootstraping on Cygwin, using GCC 13.2.0 as stage 0 compiler.
It seems that the size of CallArgList can't exceed an unknown limit.


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


[llvm] [clang] [llvm] Add support for building on illumos (PR #74930)

2023-12-10 Thread Brad Smith via cfe-commits

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


[clang-tools-extra] [clangd] Initialize HighlightingsBuilder::Resolver (PR #74971)

2023-12-10 Thread Younan Zhang via cfe-commits

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

Thank you! LGTM modulo one nit: could you please remove the nullptr member 
initializer for `Resolver`? That looks unnecessary now.

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


[flang] [clang] [llvm] [Flang][WIP/RFC] Enable TSan for Flang (PR #74643)

2023-12-10 Thread Andrzej Warzyński via cfe-commits

banach-space wrote:

Hi @jprotze , thank you for working on this!

One thing that would be very nice to see are tests :) It would really help if 
we could see how to use and how to test this. Any chance for an end-to-end PoC 
or a demonstrator? @kiranchandramohan , would an e2e test with OpenMP enabled 
make sense to exercise this?

> Is it the right place to run the ThreadSanitizer pass?

These are uncharted waters for me, but it looks like in Clang the sanitizers 
are added [before default optimisation pipleines are 
built](https://github.com/llvm/llvm-project/blob/435ba72afda756183a1ddc7a3a160152ad630951/clang/lib/CodeGen/BackendUtil.cpp#L1006).
 I would make sure that Flang does the same or justify the rationale for any 
divergence. As far as the Flang driver is concerned, I think that you have 
correctly identified the most suitable place. I would probably extract the 
"sanitzer" logic into a dedicated hook, but that's an implementation detail for 
later.

> We see different options for an actual solution:
>run a separate pass before the TSan pass that adds the attribute to all 
> functions while considering the blacklist

How does Clang decide when to add such attributes? Why not replicate that 
logic? Also, if you are looking for a somewhat relevant/similar pass in Flang, 
check `VScaleAttrPass`: 
https://github.com/llvm/llvm-project/blob/435ba72afda756183a1ddc7a3a160152ad630951/flang/lib/Optimizer/Transforms/VScaleAttr.cpp#L61-L79

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


[clang] [Clang][LoongArch] Comply with the lp64d ABI to pass vector arguments (PR #74990)

2023-12-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (yjijd)


Changes

LoongArch gcc complies with the lp64d calling convention to pass vector 
arguments currently. This patch makes clang be consistent with gcc.

---

Patch is 1.89 MiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/74990.diff


5 Files Affected:

- (modified) clang/lib/CodeGen/Targets/LoongArch.cpp (-7) 
- (modified) clang/test/CodeGen/LoongArch/lasx/builtin-alias.c (+3416-1460) 
- (modified) clang/test/CodeGen/LoongArch/lasx/builtin.c (+3415-1459) 
- (modified) clang/test/CodeGen/LoongArch/lsx/builtin-alias.c (+3327-1419) 
- (modified) clang/test/CodeGen/LoongArch/lsx/builtin.c (+3327-1419) 


``diff
diff --git a/clang/lib/CodeGen/Targets/LoongArch.cpp 
b/clang/lib/CodeGen/Targets/LoongArch.cpp
index 7b2c31139b0b2a..63b9a1fdb988ce 100644
--- a/clang/lib/CodeGen/Targets/LoongArch.cpp
+++ b/clang/lib/CodeGen/Targets/LoongArch.cpp
@@ -324,13 +324,6 @@ ABIArgInfo LoongArchABIInfo::classifyArgumentType(QualType 
Ty, bool IsFixed,
 return ABIArgInfo::getDirect();
   }
 
-  // Pass 128-bit/256-bit vector values via vector registers directly.
-  if (Ty->isVectorType() && (((getContext().getTypeSize(Ty) == 128) &&
-  (getTarget().hasFeature("lsx"))) ||
- ((getContext().getTypeSize(Ty) == 256) &&
-  getTarget().hasFeature("lasx"
-return ABIArgInfo::getDirect();
-
   // Complex types for the *f or *d ABI must be passed directly rather than
   // using CoerceAndExpand.
   if (IsFixed && Ty->isComplexType() && FRLen && FARsLeft >= 2) {
diff --git a/clang/test/CodeGen/LoongArch/lasx/builtin-alias.c 
b/clang/test/CodeGen/LoongArch/lasx/builtin-alias.c
index 09b2d5fcacf530..9a8ce224bcfd09 100644
--- a/clang/test/CodeGen/LoongArch/lasx/builtin-alias.c
+++ b/clang/test/CodeGen/LoongArch/lasx/builtin-alias.c
@@ -5,4426 +5,6382 @@
 
 // CHECK-LABEL: @xvsll_b(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call <32 x i8> 
@llvm.loongarch.lasx.xvsll.b(<32 x i8> [[_1:%.*]], <32 x i8> [[_2:%.*]])
-// CHECK-NEXT:ret <32 x i8> [[TMP0]]
+// CHECK-NEXT:[[_124:%.*]] = load <32 x i8>, ptr [[TMP0:%.*]], align 32, 
!tbaa [[TBAA2:![0-9]+]]
+// CHECK-NEXT:[[_235:%.*]] = load <32 x i8>, ptr [[TMP1:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[TMP2:%.*]] = tail call <32 x i8> 
@llvm.loongarch.lasx.xvsll.b(<32 x i8> [[_124]], <32 x i8> [[_235]])
+// CHECK-NEXT:store <32 x i8> [[TMP2]], ptr [[AGG_RESULT:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:ret void
 //
 v32i8 xvsll_b(v32i8 _1, v32i8 _2) { return __lasx_xvsll_b(_1, _2); }
 // CHECK-LABEL: @xvsll_h(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call <16 x i16> 
@llvm.loongarch.lasx.xvsll.h(<16 x i16> [[_1:%.*]], <16 x i16> [[_2:%.*]])
-// CHECK-NEXT:ret <16 x i16> [[TMP0]]
+// CHECK-NEXT:[[_124:%.*]] = load <16 x i16>, ptr [[TMP0:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[_235:%.*]] = load <16 x i16>, ptr [[TMP1:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[TMP2:%.*]] = tail call <16 x i16> 
@llvm.loongarch.lasx.xvsll.h(<16 x i16> [[_124]], <16 x i16> [[_235]])
+// CHECK-NEXT:store <16 x i16> [[TMP2]], ptr [[AGG_RESULT:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:ret void
 //
 v16i16 xvsll_h(v16i16 _1, v16i16 _2) { return __lasx_xvsll_h(_1, _2); }
 // CHECK-LABEL: @xvsll_w(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call <8 x i32> 
@llvm.loongarch.lasx.xvsll.w(<8 x i32> [[_1:%.*]], <8 x i32> [[_2:%.*]])
-// CHECK-NEXT:ret <8 x i32> [[TMP0]]
+// CHECK-NEXT:[[_124:%.*]] = load <8 x i32>, ptr [[TMP0:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[_235:%.*]] = load <8 x i32>, ptr [[TMP1:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[TMP2:%.*]] = tail call <8 x i32> 
@llvm.loongarch.lasx.xvsll.w(<8 x i32> [[_124]], <8 x i32> [[_235]])
+// CHECK-NEXT:store <8 x i32> [[TMP2]], ptr [[AGG_RESULT:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:ret void
 //
 v8i32 xvsll_w(v8i32 _1, v8i32 _2) { return __lasx_xvsll_w(_1, _2); }
 // CHECK-LABEL: @xvsll_d(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call <4 x i64> 
@llvm.loongarch.lasx.xvsll.d(<4 x i64> [[_1:%.*]], <4 x i64> [[_2:%.*]])
-// CHECK-NEXT:ret <4 x i64> [[TMP0]]
+// CHECK-NEXT:[[_1:%.*]] = load <4 x i64>, ptr [[TMP0:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[_2:%.*]] = load <4 x i64>, ptr [[TMP1:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[TMP2:%.*]] = tail call <4 x i64> 
@llvm.loongarch.lasx.xvsll.d(<4 x i64> [[_1]], <4 x i64> [[_2]])
+// CHECK-NEXT:store <4 x i64> [[TMP2]], ptr [[AGG_RESULT:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:ret void
 //
 v4i64 xvsll_d(v4i64 _1, v4i64 _2) { return __lasx_xvsll_d(_1, _2); }
 // CHECK-LABEL: @xvslli_b(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = ta

[clang] [Clang][LoongArch] Comply with the lp64d ABI to pass vector arguments (PR #74990)

2023-12-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: None (yjijd)


Changes

LoongArch gcc complies with the lp64d calling convention to pass vector 
arguments currently. This patch makes clang be consistent with gcc.

---

Patch is 1.89 MiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/74990.diff


5 Files Affected:

- (modified) clang/lib/CodeGen/Targets/LoongArch.cpp (-7) 
- (modified) clang/test/CodeGen/LoongArch/lasx/builtin-alias.c (+3416-1460) 
- (modified) clang/test/CodeGen/LoongArch/lasx/builtin.c (+3415-1459) 
- (modified) clang/test/CodeGen/LoongArch/lsx/builtin-alias.c (+3327-1419) 
- (modified) clang/test/CodeGen/LoongArch/lsx/builtin.c (+3327-1419) 


``diff
diff --git a/clang/lib/CodeGen/Targets/LoongArch.cpp 
b/clang/lib/CodeGen/Targets/LoongArch.cpp
index 7b2c31139b0b2..63b9a1fdb988c 100644
--- a/clang/lib/CodeGen/Targets/LoongArch.cpp
+++ b/clang/lib/CodeGen/Targets/LoongArch.cpp
@@ -324,13 +324,6 @@ ABIArgInfo LoongArchABIInfo::classifyArgumentType(QualType 
Ty, bool IsFixed,
 return ABIArgInfo::getDirect();
   }
 
-  // Pass 128-bit/256-bit vector values via vector registers directly.
-  if (Ty->isVectorType() && (((getContext().getTypeSize(Ty) == 128) &&
-  (getTarget().hasFeature("lsx"))) ||
- ((getContext().getTypeSize(Ty) == 256) &&
-  getTarget().hasFeature("lasx"
-return ABIArgInfo::getDirect();
-
   // Complex types for the *f or *d ABI must be passed directly rather than
   // using CoerceAndExpand.
   if (IsFixed && Ty->isComplexType() && FRLen && FARsLeft >= 2) {
diff --git a/clang/test/CodeGen/LoongArch/lasx/builtin-alias.c 
b/clang/test/CodeGen/LoongArch/lasx/builtin-alias.c
index 09b2d5fcacf53..9a8ce224bcfd0 100644
--- a/clang/test/CodeGen/LoongArch/lasx/builtin-alias.c
+++ b/clang/test/CodeGen/LoongArch/lasx/builtin-alias.c
@@ -5,4426 +5,6382 @@
 
 // CHECK-LABEL: @xvsll_b(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call <32 x i8> 
@llvm.loongarch.lasx.xvsll.b(<32 x i8> [[_1:%.*]], <32 x i8> [[_2:%.*]])
-// CHECK-NEXT:ret <32 x i8> [[TMP0]]
+// CHECK-NEXT:[[_124:%.*]] = load <32 x i8>, ptr [[TMP0:%.*]], align 32, 
!tbaa [[TBAA2:![0-9]+]]
+// CHECK-NEXT:[[_235:%.*]] = load <32 x i8>, ptr [[TMP1:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[TMP2:%.*]] = tail call <32 x i8> 
@llvm.loongarch.lasx.xvsll.b(<32 x i8> [[_124]], <32 x i8> [[_235]])
+// CHECK-NEXT:store <32 x i8> [[TMP2]], ptr [[AGG_RESULT:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:ret void
 //
 v32i8 xvsll_b(v32i8 _1, v32i8 _2) { return __lasx_xvsll_b(_1, _2); }
 // CHECK-LABEL: @xvsll_h(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call <16 x i16> 
@llvm.loongarch.lasx.xvsll.h(<16 x i16> [[_1:%.*]], <16 x i16> [[_2:%.*]])
-// CHECK-NEXT:ret <16 x i16> [[TMP0]]
+// CHECK-NEXT:[[_124:%.*]] = load <16 x i16>, ptr [[TMP0:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[_235:%.*]] = load <16 x i16>, ptr [[TMP1:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[TMP2:%.*]] = tail call <16 x i16> 
@llvm.loongarch.lasx.xvsll.h(<16 x i16> [[_124]], <16 x i16> [[_235]])
+// CHECK-NEXT:store <16 x i16> [[TMP2]], ptr [[AGG_RESULT:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:ret void
 //
 v16i16 xvsll_h(v16i16 _1, v16i16 _2) { return __lasx_xvsll_h(_1, _2); }
 // CHECK-LABEL: @xvsll_w(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call <8 x i32> 
@llvm.loongarch.lasx.xvsll.w(<8 x i32> [[_1:%.*]], <8 x i32> [[_2:%.*]])
-// CHECK-NEXT:ret <8 x i32> [[TMP0]]
+// CHECK-NEXT:[[_124:%.*]] = load <8 x i32>, ptr [[TMP0:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[_235:%.*]] = load <8 x i32>, ptr [[TMP1:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[TMP2:%.*]] = tail call <8 x i32> 
@llvm.loongarch.lasx.xvsll.w(<8 x i32> [[_124]], <8 x i32> [[_235]])
+// CHECK-NEXT:store <8 x i32> [[TMP2]], ptr [[AGG_RESULT:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:ret void
 //
 v8i32 xvsll_w(v8i32 _1, v8i32 _2) { return __lasx_xvsll_w(_1, _2); }
 // CHECK-LABEL: @xvsll_d(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call <4 x i64> 
@llvm.loongarch.lasx.xvsll.d(<4 x i64> [[_1:%.*]], <4 x i64> [[_2:%.*]])
-// CHECK-NEXT:ret <4 x i64> [[TMP0]]
+// CHECK-NEXT:[[_1:%.*]] = load <4 x i64>, ptr [[TMP0:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[_2:%.*]] = load <4 x i64>, ptr [[TMP1:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:[[TMP2:%.*]] = tail call <4 x i64> 
@llvm.loongarch.lasx.xvsll.d(<4 x i64> [[_1]], <4 x i64> [[_2]])
+// CHECK-NEXT:store <4 x i64> [[TMP2]], ptr [[AGG_RESULT:%.*]], align 32, 
!tbaa [[TBAA2]]
+// CHECK-NEXT:ret void
 //
 v4i64 xvsll_d(v4i64 _1, v4i64 _2) { return __lasx_xvsll_d(_1, _2); }
 // CHECK-LABEL: @xvslli_b(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] 

[clang] [clang][ASTImporter] delay import funtion return type (PR #74991)

2023-12-10 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky created 
https://github.com/llvm/llvm-project/pull/74991

Import return type of a function would lead infinite recursion when 
`getAssociatedDecl()` returns itself in 
`ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr`. Delay import the return 
type whether it is auto would make sense. This patch try to fix [this 
issue](https://github.com/llvm/llvm-project/issues/74839)

>From 1527cc2046d4c9881ca536a2dbf59330d9291ba2 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Sun, 10 Dec 2023 21:01:49 +0800
Subject: [PATCH] [clang][ASTImporter] delay import funtion return type

---
 clang/lib/AST/ASTImporter.cpp   |  8 ++--
 clang/unittests/AST/ASTImporterTest.cpp | 20 
 2 files changed, 22 insertions(+), 6 deletions(-)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index f1f335118f37a4..335d10016f2060 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -3739,16 +3739,13 @@ ExpectedDecl 
ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
   // do the same with TypeSourceInfo.
   bool UsedDifferentProtoType = false;
   if (const auto *FromFPT = FromTy->getAs()) {
-QualType FromReturnTy = FromFPT->getReturnType();
 // Functions with auto return type may define a struct inside their body
 // and the return type could refer to that struct.
 // E.g.: auto foo() { struct X{}; return X(); }
 // To avoid an infinite recursion when importing, create the FunctionDecl
 // with a simplified return type.
-if (hasAutoReturnTypeDeclaredInside(D)) {
-  FromReturnTy = Importer.getFromContext().VoidTy;
-  UsedDifferentProtoType = true;
-}
+QualType FromReturnTy = Importer.getFromContext().VoidTy;
+UsedDifferentProtoType = true;
 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
 // FunctionDecl that we are importing the FunctionProtoType for.
@@ -3759,7 +3756,6 @@ ExpectedDecl 
ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
 FromEPI.ExceptionSpec.NoexceptExpr) {
   FunctionProtoType::ExtProtoInfo DefaultEPI;
   FromEPI = DefaultEPI;
-  UsedDifferentProtoType = true;
 }
 FromTy = Importer.getFromContext().getFunctionType(
 FromReturnTy, FromFPT->getParamTypes(), FromEPI);
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 4dd7510bf8ddf8..7ab9db4251e80b 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -9284,6 +9284,26 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   // EXPECT_EQ(ToF1Imported->getPreviousDecl(), ToF1);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportFunctionAutoType) {
+  const char *Code =
+  R"(
+  template
+  struct array {};
+
+  template 
+  auto foo() { return array(); }
+
+  void bar() { foo<0>(); }
+  )";
+  Decl *FromTU = getTuDecl(Code, Lang_CXX17);
+
+  auto *FromBar = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("bar")));
+
+  auto *ToBar = Import(FromBar, Lang_CXX17);
+  EXPECT_TRUE(ToBar);
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 

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


[clang] [clang][ASTImporter] delay import funtion return type (PR #74991)

2023-12-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Qizhi Hu (jcsxky)


Changes

Import return type of a function would lead infinite recursion when 
`getAssociatedDecl()` returns itself in 
`ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr`. Delay import the return 
type whether it is auto would make sense. This patch try to fix [this 
issue](https://github.com/llvm/llvm-project/issues/74839)

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


2 Files Affected:

- (modified) clang/lib/AST/ASTImporter.cpp (+2-6) 
- (modified) clang/unittests/AST/ASTImporterTest.cpp (+20) 


``diff
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index f1f335118f37a..335d10016f206 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -3739,16 +3739,13 @@ ExpectedDecl 
ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
   // do the same with TypeSourceInfo.
   bool UsedDifferentProtoType = false;
   if (const auto *FromFPT = FromTy->getAs()) {
-QualType FromReturnTy = FromFPT->getReturnType();
 // Functions with auto return type may define a struct inside their body
 // and the return type could refer to that struct.
 // E.g.: auto foo() { struct X{}; return X(); }
 // To avoid an infinite recursion when importing, create the FunctionDecl
 // with a simplified return type.
-if (hasAutoReturnTypeDeclaredInside(D)) {
-  FromReturnTy = Importer.getFromContext().VoidTy;
-  UsedDifferentProtoType = true;
-}
+QualType FromReturnTy = Importer.getFromContext().VoidTy;
+UsedDifferentProtoType = true;
 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
 // FunctionDecl that we are importing the FunctionProtoType for.
@@ -3759,7 +3756,6 @@ ExpectedDecl 
ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
 FromEPI.ExceptionSpec.NoexceptExpr) {
   FunctionProtoType::ExtProtoInfo DefaultEPI;
   FromEPI = DefaultEPI;
-  UsedDifferentProtoType = true;
 }
 FromTy = Importer.getFromContext().getFunctionType(
 FromReturnTy, FromFPT->getParamTypes(), FromEPI);
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 4dd7510bf8ddf..7ab9db4251e80 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -9284,6 +9284,26 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   // EXPECT_EQ(ToF1Imported->getPreviousDecl(), ToF1);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportFunctionAutoType) {
+  const char *Code =
+  R"(
+  template
+  struct array {};
+
+  template 
+  auto foo() { return array(); }
+
+  void bar() { foo<0>(); }
+  )";
+  Decl *FromTU = getTuDecl(Code, Lang_CXX17);
+
+  auto *FromBar = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("bar")));
+
+  auto *ToBar = Import(FromBar, Lang_CXX17);
+  EXPECT_TRUE(ToBar);
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 

``




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


[clang] [clang][ASTImporter] skip TemplateTypeParmDecl in VisitTypeAliasTemplateDecl (PR #74919)

2023-12-10 Thread Qizhi Hu via cfe-commits

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

>From e656aa2a3850f845987bb0ddc56b308d22d2dafd Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Sat, 9 Dec 2023 12:00:02 +0800
Subject: [PATCH] [clang][ASTImporter] skip TemplateTypeParmDecl in
 VisitTypeAliasTemplateDecl

---
 clang/lib/AST/ASTImporter.cpp   |  3 ++-
 clang/unittests/AST/ASTImporterTest.cpp | 23 +++
 2 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index f1f335118f37a..bfe9af648e603 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -2769,7 +2769,8 @@ 
ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
 unsigned IDNS = Decl::IDNS_Ordinary;
 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
 for (auto *FoundDecl : FoundDecls) {
-  if (!FoundDecl->isInIdentifierNamespace(IDNS))
+  if (!FoundDecl->isInIdentifierNamespace(IDNS) ||
+  isa_and_nonnull(FoundDecl))
 continue;
   if (auto *FoundAlias = dyn_cast(FoundDecl))
 return Importer.MapImported(D, FoundAlias);
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 4dd7510bf8ddf..b53cf11f315c8 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -9284,6 +9284,29 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   // EXPECT_EQ(ToF1Imported->getPreviousDecl(), ToF1);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportTypeAliasTemplateDecl) {
+  const char *Code =
+  R"(
+  struct S;
+  template 
+  using Callable = S;
+  template 
+  int bindingFunctionVTable;
+  )";
+  Decl *FromTU = getTuDecl(Code, Lang_CXX17);
+
+  auto *FromCallable1 = FirstDeclMatcher().match(
+  FromTU, typeAliasTemplateDecl(hasName("Callable")));
+
+  auto *FromCallable2 = FirstDeclMatcher().match(
+  FromTU, templateTypeParmDecl(hasName("Callable")));
+
+  auto *ToCallable2 = Import(FromCallable2, Lang_CXX17);
+  auto *ToCallable1 = Import(FromCallable1, Lang_CXX17);
+  EXPECT_TRUE(ToCallable1);
+  EXPECT_TRUE(ToCallable2);
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 

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


[llvm] [clang] [llvm] Add support for building on illumos (PR #74930)

2023-12-10 Thread Brad Smith via cfe-commits

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


[clang-tools-extra] create new clang-tidy check to add namespaces to symbol references (PR #70621)

2023-12-10 Thread Piotr Zegar via cfe-commits

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


[clang] [clang] Correctly implement CWG 2672 (PR #75001)

2023-12-10 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 created 
https://github.com/llvm/llvm-project/pull/75001

This is a follow-up patch for [D156993](https://reviews.llvm.org/D156993), that 
marks only the lambda body as non-immediate context.

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

>From 8681b3c9f5e19b6ae977321d5d4154113273c2a0 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 12 Nov 2023 13:21:03 +0800
Subject: [PATCH] [clang] Correctly implement CWG 2672

This is a follow-up patch for [D156993](https://reviews.llvm.org/D156993),
that marks only the lambda body as non-immediate context.

Fixes https://github.com/llvm/llvm-project/issues/71684
---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 11 +---
 clang/lib/Sema/TreeTransform.h|  7 +
 clang/test/CXX/drs/dr26xx.cpp |  2 +-
 .../expr.prim.lambda/default-arguments.cpp|  6 ++--
 .../expr.prim/expr.prim.lambda/p11-1y.cpp |  2 --
 .../expr/expr.prim/expr.prim.lambda/p23.cpp   |  1 -
 .../expr/expr.prim/expr.prim.lambda/p4.cpp|  3 +-
 clang/test/CXX/temp/temp.deduct/p9.cpp|  8 ++
 clang/test/SemaCXX/cxx1y-init-captures.cpp|  8 +++---
 clang/test/SemaCXX/cxx1z-lambda-star-this.cpp |  4 +--
 clang/test/SemaCXX/lambda-expressions.cpp |  4 +--
 clang/test/SemaCXX/lambda-pack-expansion.cpp  |  1 -
 clang/test/SemaCXX/vartemplate-lambda.cpp |  1 -
 .../SemaCXX/warn-unused-lambda-capture.cpp| 28 +--
 .../SemaTemplate/instantiate-local-class.cpp  |  4 +--
 15 files changed, 37 insertions(+), 53 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index df6b40999e645c..88bd44f7d6934d 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -35,7 +35,6 @@
 #include "clang/Sema/Template.h"
 #include "clang/Sema/TemplateDeduction.h"
 #include "clang/Sema/TemplateInstCallback.h"
-#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TimeProfiler.h"
@@ -1142,8 +1141,7 @@ std::optional 
Sema::isSFINAEContext() const {
 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
   // We're either substituting explicitly-specified template arguments,
   // deduced template arguments. SFINAE applies unless we are in a lambda
-  // expression, see [temp.deduct]p9.
-  [[fallthrough]];
+  // body, see [temp.deduct]p9.
 case CodeSynthesisContext::ConstraintSubstitution:
 case CodeSynthesisContext::RequirementInstantiation:
 case CodeSynthesisContext::RequirementParameterInstantiation:
@@ -1444,13 +1442,6 @@ namespace {
   LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
   Sema::ConstraintEvalRAII RAII(*this);
 
-  Sema::CodeSynthesisContext C;
-  C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
-  C.PointOfInstantiation = E->getBeginLoc();
-  SemaRef.pushCodeSynthesisContext(C);
-  auto PopCtx =
-  llvm::make_scope_exit([this] { SemaRef.popCodeSynthesisContext(); });
-
   ExprResult Result = inherited::TransformLambdaExpr(E);
   if (Result.isInvalid())
 return Result;
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 1ad843d0bf4e0c..55e5c3c9dedc56 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -13648,10 +13648,17 @@ 
TreeTransform::TransformLambdaExpr(LambdaExpr *E) {
   getSema().PushExpressionEvaluationContext(
   Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
 
+  Sema::CodeSynthesisContext C;
+  C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
+  C.PointOfInstantiation = E->getBody()->getBeginLoc();
+  getSema().pushCodeSynthesisContext(C);
+
   // Instantiate the body of the lambda expression.
   StmtResult Body =
   Invalid ? StmtError() : getDerived().TransformLambdaBody(E, 
E->getBody());
 
+  getSema().popCodeSynthesisContext();
+
   // ActOnLambda* will pop the function scope for us.
   FuncScopeCleanup.disable();
 
diff --git a/clang/test/CXX/drs/dr26xx.cpp b/clang/test/CXX/drs/dr26xx.cpp
index dd4bb1ff6ae2e1..8a22dbeb98a3d5 100644
--- a/clang/test/CXX/drs/dr26xx.cpp
+++ b/clang/test/CXX/drs/dr26xx.cpp
@@ -211,7 +211,7 @@ void f(...);
 
 template 
 void bar(T) requires requires {
-   decltype([]() -> T {})::foo();
+   []() -> decltype(T::foo()) {};
 };
 void bar(...);
 
diff --git 
a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp 
b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp
index c5d08ec404a7c3..72265d77700aaf 100644
--- a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp
+++ b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp
@@ -35,8 +35,7 @@ struct NoDefaultCtor {
 template
 void defargs_in_template_unused(T t) {
   auto l1 = [](const T& value

[clang] [clang] Correctly implement CWG 2672 (PR #75001)

2023-12-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Younan Zhang (zyn0217)


Changes

This is a follow-up patch for [D156993](https://reviews.llvm.org/D156993), that 
marks only the lambda body as non-immediate context.

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

---

Patch is 20.37 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/75001.diff


15 Files Affected:

- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+1-10) 
- (modified) clang/lib/Sema/TreeTransform.h (+7) 
- (modified) clang/test/CXX/drs/dr26xx.cpp (+1-1) 
- (modified) 
clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp (+2-4) 
- (modified) clang/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp (-2) 
- (modified) clang/test/CXX/expr/expr.prim/expr.prim.lambda/p23.cpp (-1) 
- (modified) clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4.cpp (+1-2) 
- (modified) clang/test/CXX/temp/temp.deduct/p9.cpp (+2-6) 
- (modified) clang/test/SemaCXX/cxx1y-init-captures.cpp (+4-4) 
- (modified) clang/test/SemaCXX/cxx1z-lambda-star-this.cpp (+2-2) 
- (modified) clang/test/SemaCXX/lambda-expressions.cpp (+2-2) 
- (modified) clang/test/SemaCXX/lambda-pack-expansion.cpp (-1) 
- (modified) clang/test/SemaCXX/vartemplate-lambda.cpp (-1) 
- (modified) clang/test/SemaCXX/warn-unused-lambda-capture.cpp (+14-14) 
- (modified) clang/test/SemaTemplate/instantiate-local-class.cpp (+1-3) 


``diff
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index df6b40999e645c..88bd44f7d6934d 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -35,7 +35,6 @@
 #include "clang/Sema/Template.h"
 #include "clang/Sema/TemplateDeduction.h"
 #include "clang/Sema/TemplateInstCallback.h"
-#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TimeProfiler.h"
@@ -1142,8 +1141,7 @@ std::optional 
Sema::isSFINAEContext() const {
 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
   // We're either substituting explicitly-specified template arguments,
   // deduced template arguments. SFINAE applies unless we are in a lambda
-  // expression, see [temp.deduct]p9.
-  [[fallthrough]];
+  // body, see [temp.deduct]p9.
 case CodeSynthesisContext::ConstraintSubstitution:
 case CodeSynthesisContext::RequirementInstantiation:
 case CodeSynthesisContext::RequirementParameterInstantiation:
@@ -1444,13 +1442,6 @@ namespace {
   LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
   Sema::ConstraintEvalRAII RAII(*this);
 
-  Sema::CodeSynthesisContext C;
-  C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
-  C.PointOfInstantiation = E->getBeginLoc();
-  SemaRef.pushCodeSynthesisContext(C);
-  auto PopCtx =
-  llvm::make_scope_exit([this] { SemaRef.popCodeSynthesisContext(); });
-
   ExprResult Result = inherited::TransformLambdaExpr(E);
   if (Result.isInvalid())
 return Result;
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 1ad843d0bf4e0c..55e5c3c9dedc56 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -13648,10 +13648,17 @@ 
TreeTransform::TransformLambdaExpr(LambdaExpr *E) {
   getSema().PushExpressionEvaluationContext(
   Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
 
+  Sema::CodeSynthesisContext C;
+  C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
+  C.PointOfInstantiation = E->getBody()->getBeginLoc();
+  getSema().pushCodeSynthesisContext(C);
+
   // Instantiate the body of the lambda expression.
   StmtResult Body =
   Invalid ? StmtError() : getDerived().TransformLambdaBody(E, 
E->getBody());
 
+  getSema().popCodeSynthesisContext();
+
   // ActOnLambda* will pop the function scope for us.
   FuncScopeCleanup.disable();
 
diff --git a/clang/test/CXX/drs/dr26xx.cpp b/clang/test/CXX/drs/dr26xx.cpp
index dd4bb1ff6ae2e1..8a22dbeb98a3d5 100644
--- a/clang/test/CXX/drs/dr26xx.cpp
+++ b/clang/test/CXX/drs/dr26xx.cpp
@@ -211,7 +211,7 @@ void f(...);
 
 template 
 void bar(T) requires requires {
-   decltype([]() -> T {})::foo();
+   []() -> decltype(T::foo()) {};
 };
 void bar(...);
 
diff --git 
a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp 
b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp
index c5d08ec404a7c3..72265d77700aaf 100644
--- a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp
+++ b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp
@@ -35,8 +35,7 @@ struct NoDefaultCtor {
 template
 void defargs_in_template_unused(T t) {
   auto l1 = [](const T& value = T()) { };  // expected-error{{no matching 
constructor for initialization of 'NoDefaultCtor'}} \
-   

[clang] [clang] Correctly implement CWG 2672 (PR #75001)

2023-12-10 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Note I'm not adding an extra release note since the previous implementation has 
done that and hasn't been cherry-picked or released yet.

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


[llvm] [libcxx] [clang] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits

https://github.com/H-G-Hristov updated 
https://github.com/llvm/llvm-project/pull/74994

>From 6e26ca239c49e1b7d9ab72217db7339e92df163f Mon Sep 17 00:00:00 2001
From: Zingam 
Date: Sun, 10 Dec 2023 14:16:02 +0200
Subject: [PATCH 1/2] [libc++][span] P2821R5: span.at()

---
 libcxx/include/span   |  30 +++
 .../views/views.span/span.elem/at.pass.cpp| 246 ++
 .../views.span/span.elem/op_idx.pass.cpp  |   1 -
 3 files changed, 276 insertions(+), 1 deletion(-)
 create mode 100644 
libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp

diff --git a/libcxx/include/span b/libcxx/include/span
index 69b0a2875e26cc..b015d7cf1c15b6 100644
--- a/libcxx/include/span
+++ b/libcxx/include/span
@@ -92,6 +92,7 @@ public:
 
 // [span.elem], span element access
 constexpr reference operator[](size_type idx) const;
+constexpr reference at(size_type idx) const; // since C++26
 constexpr reference front() const;
 constexpr reference back() const;
 constexpr pointer data() const noexcept;
@@ -146,6 +147,9 @@ template
 #include <__utility/forward.h>
 #include // for array
 #include   // for byte
+#if _LIBCPP_STD_VER >= 26
+#  include 
+#endif
 #include 
 
 // standard-mandated includes
@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -383,6 +396,10 @@ public:
 
 private:
 pointer__data_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 
@@ -510,6 +527,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -552,6 +578,10 @@ public:
 private:
 pointer   __data_;
 size_type __size_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 template 
diff --git a/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp 
b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
new file mode 100644
index 00..2a9ce2baeec1a5
--- /dev/null
+++ b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
@@ -0,0 +1,246 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+// template 
+// constexpr bool testConstexprSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// return r1 == r2;
+// }
+
+// template 
+// void testRuntimeSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// assert(r1 == r2);
+// }
+
+// struct A{};
+// constexpr int iArr1[] = { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9};
+//   int iArr2[] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
+
+// int main(int, char**)
+// {
+// static_assert(testConstexprSpan(std::span(iArr1, 1), 0), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 1), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 2), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 2), "");
+// static_assert(tes

[llvm] [clang-tools-extra] [libcxx] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits

https://github.com/H-G-Hristov updated 
https://github.com/llvm/llvm-project/pull/74994

>From 6e26ca239c49e1b7d9ab72217db7339e92df163f Mon Sep 17 00:00:00 2001
From: Zingam 
Date: Sun, 10 Dec 2023 14:16:02 +0200
Subject: [PATCH 1/3] [libc++][span] P2821R5: span.at()

---
 libcxx/include/span   |  30 +++
 .../views/views.span/span.elem/at.pass.cpp| 246 ++
 .../views.span/span.elem/op_idx.pass.cpp  |   1 -
 3 files changed, 276 insertions(+), 1 deletion(-)
 create mode 100644 
libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp

diff --git a/libcxx/include/span b/libcxx/include/span
index 69b0a2875e26cc..b015d7cf1c15b6 100644
--- a/libcxx/include/span
+++ b/libcxx/include/span
@@ -92,6 +92,7 @@ public:
 
 // [span.elem], span element access
 constexpr reference operator[](size_type idx) const;
+constexpr reference at(size_type idx) const; // since C++26
 constexpr reference front() const;
 constexpr reference back() const;
 constexpr pointer data() const noexcept;
@@ -146,6 +147,9 @@ template
 #include <__utility/forward.h>
 #include // for array
 #include   // for byte
+#if _LIBCPP_STD_VER >= 26
+#  include 
+#endif
 #include 
 
 // standard-mandated includes
@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -383,6 +396,10 @@ public:
 
 private:
 pointer__data_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 
@@ -510,6 +527,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -552,6 +578,10 @@ public:
 private:
 pointer   __data_;
 size_type __size_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 template 
diff --git a/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp 
b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
new file mode 100644
index 00..2a9ce2baeec1a5
--- /dev/null
+++ b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
@@ -0,0 +1,246 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+// template 
+// constexpr bool testConstexprSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// return r1 == r2;
+// }
+
+// template 
+// void testRuntimeSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// assert(r1 == r2);
+// }
+
+// struct A{};
+// constexpr int iArr1[] = { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9};
+//   int iArr2[] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
+
+// int main(int, char**)
+// {
+// static_assert(testConstexprSpan(std::span(iArr1, 1), 0), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 1), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 2), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 2), "");
+// static_assert(tes

[clang] [llvm] [libcxx] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits

https://github.com/H-G-Hristov updated 
https://github.com/llvm/llvm-project/pull/74994

>From 6e26ca239c49e1b7d9ab72217db7339e92df163f Mon Sep 17 00:00:00 2001
From: Zingam 
Date: Sun, 10 Dec 2023 14:16:02 +0200
Subject: [PATCH 1/4] [libc++][span] P2821R5: span.at()

---
 libcxx/include/span   |  30 +++
 .../views/views.span/span.elem/at.pass.cpp| 246 ++
 .../views.span/span.elem/op_idx.pass.cpp  |   1 -
 3 files changed, 276 insertions(+), 1 deletion(-)
 create mode 100644 
libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp

diff --git a/libcxx/include/span b/libcxx/include/span
index 69b0a2875e26cc..b015d7cf1c15b6 100644
--- a/libcxx/include/span
+++ b/libcxx/include/span
@@ -92,6 +92,7 @@ public:
 
 // [span.elem], span element access
 constexpr reference operator[](size_type idx) const;
+constexpr reference at(size_type idx) const; // since C++26
 constexpr reference front() const;
 constexpr reference back() const;
 constexpr pointer data() const noexcept;
@@ -146,6 +147,9 @@ template
 #include <__utility/forward.h>
 #include // for array
 #include   // for byte
+#if _LIBCPP_STD_VER >= 26
+#  include 
+#endif
 #include 
 
 // standard-mandated includes
@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -383,6 +396,10 @@ public:
 
 private:
 pointer__data_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 
@@ -510,6 +527,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -552,6 +578,10 @@ public:
 private:
 pointer   __data_;
 size_type __size_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 template 
diff --git a/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp 
b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
new file mode 100644
index 00..2a9ce2baeec1a5
--- /dev/null
+++ b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
@@ -0,0 +1,246 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+// template 
+// constexpr bool testConstexprSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// return r1 == r2;
+// }
+
+// template 
+// void testRuntimeSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// assert(r1 == r2);
+// }
+
+// struct A{};
+// constexpr int iArr1[] = { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9};
+//   int iArr2[] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
+
+// int main(int, char**)
+// {
+// static_assert(testConstexprSpan(std::span(iArr1, 1), 0), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 1), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 2), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 2), "");
+// static_assert(tes

[libcxx] [llvm] [clang-tools-extra] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits

https://github.com/H-G-Hristov updated 
https://github.com/llvm/llvm-project/pull/74994

>From 6e26ca239c49e1b7d9ab72217db7339e92df163f Mon Sep 17 00:00:00 2001
From: Zingam 
Date: Sun, 10 Dec 2023 14:16:02 +0200
Subject: [PATCH 1/5] [libc++][span] P2821R5: span.at()

---
 libcxx/include/span   |  30 +++
 .../views/views.span/span.elem/at.pass.cpp| 246 ++
 .../views.span/span.elem/op_idx.pass.cpp  |   1 -
 3 files changed, 276 insertions(+), 1 deletion(-)
 create mode 100644 
libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp

diff --git a/libcxx/include/span b/libcxx/include/span
index 69b0a2875e26c..b015d7cf1c15b 100644
--- a/libcxx/include/span
+++ b/libcxx/include/span
@@ -92,6 +92,7 @@ public:
 
 // [span.elem], span element access
 constexpr reference operator[](size_type idx) const;
+constexpr reference at(size_type idx) const; // since C++26
 constexpr reference front() const;
 constexpr reference back() const;
 constexpr pointer data() const noexcept;
@@ -146,6 +147,9 @@ template
 #include <__utility/forward.h>
 #include // for array
 #include   // for byte
+#if _LIBCPP_STD_VER >= 26
+#  include 
+#endif
 #include 
 
 // standard-mandated includes
@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -383,6 +396,10 @@ public:
 
 private:
 pointer__data_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 
@@ -510,6 +527,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -552,6 +578,10 @@ public:
 private:
 pointer   __data_;
 size_type __size_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 template 
diff --git a/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp 
b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
new file mode 100644
index 0..2a9ce2baeec1a
--- /dev/null
+++ b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
@@ -0,0 +1,246 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+// template 
+// constexpr bool testConstexprSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// return r1 == r2;
+// }
+
+// template 
+// void testRuntimeSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// assert(r1 == r2);
+// }
+
+// struct A{};
+// constexpr int iArr1[] = { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9};
+//   int iArr2[] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
+
+// int main(int, char**)
+// {
+// static_assert(testConstexprSpan(std::span(iArr1, 1), 0), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 1), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 2), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 2), "");
+// static_assert(testCon

[libcxx] [llvm] [clang-tools-extra] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits

https://github.com/H-G-Hristov updated 
https://github.com/llvm/llvm-project/pull/74994

>From 6e26ca239c49e1b7d9ab72217db7339e92df163f Mon Sep 17 00:00:00 2001
From: Zingam 
Date: Sun, 10 Dec 2023 14:16:02 +0200
Subject: [PATCH 1/6] [libc++][span] P2821R5: span.at()

---
 libcxx/include/span   |  30 +++
 .../views/views.span/span.elem/at.pass.cpp| 246 ++
 .../views.span/span.elem/op_idx.pass.cpp  |   1 -
 3 files changed, 276 insertions(+), 1 deletion(-)
 create mode 100644 
libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp

diff --git a/libcxx/include/span b/libcxx/include/span
index 69b0a2875e26c..b015d7cf1c15b 100644
--- a/libcxx/include/span
+++ b/libcxx/include/span
@@ -92,6 +92,7 @@ public:
 
 // [span.elem], span element access
 constexpr reference operator[](size_type idx) const;
+constexpr reference at(size_type idx) const; // since C++26
 constexpr reference front() const;
 constexpr reference back() const;
 constexpr pointer data() const noexcept;
@@ -146,6 +147,9 @@ template
 #include <__utility/forward.h>
 #include // for array
 #include   // for byte
+#if _LIBCPP_STD_VER >= 26
+#  include 
+#endif
 #include 
 
 // standard-mandated includes
@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -383,6 +396,10 @@ public:
 
 private:
 pointer__data_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 
@@ -510,6 +527,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_INLINE_VISIBILITY constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -552,6 +578,10 @@ public:
 private:
 pointer   __data_;
 size_type __size_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 template 
diff --git a/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp 
b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
new file mode 100644
index 0..2a9ce2baeec1a
--- /dev/null
+++ b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
@@ -0,0 +1,246 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+// template 
+// constexpr bool testConstexprSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// return r1 == r2;
+// }
+
+// template 
+// void testRuntimeSpan(Span sp, std::size_t idx)
+// {
+// LIBCPP_ASSERT(noexcept(sp[idx]));
+
+// typename Span::reference r1 = sp[idx];
+// typename Span::reference r2 = *(sp.data() + idx);
+
+// assert(r1 == r2);
+// }
+
+// struct A{};
+// constexpr int iArr1[] = { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9};
+//   int iArr2[] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
+
+// int main(int, char**)
+// {
+// static_assert(testConstexprSpan(std::span(iArr1, 1), 0), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 2), 1), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 3), 2), "");
+
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 0), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 1), "");
+// static_assert(testConstexprSpan(std::span(iArr1, 4), 2), "");
+// static_assert(testCon

[libcxx] [llvm] [clang] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits

https://github.com/H-G-Hristov ready_for_review 
https://github.com/llvm/llvm-project/pull/74994
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] [llvm] [clang] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-libcxx

Author: Hristo Hristov (H-G-Hristov)


Changes

Implements: [P2821R5](https://wg21.link/P2821R5)

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


5 Files Affected:

- (modified) libcxx/docs/ReleaseNotes/18.rst (+1) 
- (modified) libcxx/docs/Status/Cxx2cPapers.csv (+1-1) 
- (modified) libcxx/include/span (+30) 
- (added) libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp 
(+136) 
- (modified) 
libcxx/test/std/containers/views/views.span/span.elem/op_idx.pass.cpp (-1) 


``diff
diff --git a/libcxx/docs/ReleaseNotes/18.rst b/libcxx/docs/ReleaseNotes/18.rst
index 9e509db6359c4a..f3e8281e74da2f 100644
--- a/libcxx/docs/ReleaseNotes/18.rst
+++ b/libcxx/docs/ReleaseNotes/18.rst
@@ -55,6 +55,7 @@ Implemented Papers
 - P2871R3 - Remove Deprecated Unicode Conversion Facets from C++26
 - P2870R3 - Remove basic_string::reserve()
 - P2909R4 - Fix formatting of code units as integers (Dude, where’s my 
``char``?)
+- P2821R5 - span.at()
 
 
 Improvements and New Features
diff --git a/libcxx/docs/Status/Cxx2cPapers.csv 
b/libcxx/docs/Status/Cxx2cPapers.csv
index ff83648aa76830..fa4a112d143673 100644
--- a/libcxx/docs/Status/Cxx2cPapers.csv
+++ b/libcxx/docs/Status/Cxx2cPapers.csv
@@ -35,7 +35,7 @@
 "`P2909R4 `__","LWG","Fix formatting of code units 
as integers (Dude, where’s my ``char``?)","Kona November 
2023","|Complete|","18.0","|format| |DR|"
 "`P0952R2 `__","LWG","A new specification for 
``std::generate_canonical``","Kona November 2023","","",""
 "`P2447R6 `__","LWG","``std::span`` over an 
initializer list","Kona November 2023","","",""
-"`P2821R5 `__","LWG","``span.at()``","Kona November 
2023","","",""
+"`P2821R5 `__","LWG","``span.at()``","Kona November 
2023","|Complete|","18.0",""
 "`P2868R3 `__","LWG","Remove Deprecated 
``std::allocator`` Typedef From C++26","Kona November 2023","","",""
 "`P2870R3 `__","LWG","Remove 
``basic_string::reserve()`` From C++26","Kona November 
2023","|Complete|","18.0",""
 "`P2871R3 `__","LWG","Remove Deprecated Unicode 
Conversion Facets from C++26","Kona November 2023","|Complete|","18.0",""
diff --git a/libcxx/include/span b/libcxx/include/span
index f94bda40fa7350..9af8dabb3ebd34 100644
--- a/libcxx/include/span
+++ b/libcxx/include/span
@@ -92,6 +92,7 @@ public:
 
 // [span.elem], span element access
 constexpr reference operator[](size_type idx) const;
+constexpr reference at(size_type idx) const; // since C++26
 constexpr reference front() const;
 constexpr reference back() const;
 constexpr pointer data() const noexcept;
@@ -146,6 +147,9 @@ template
 #include <__utility/forward.h>
 #include // for array
 #include   // for byte
+#if _LIBCPP_STD_VER >= 26
+#  include 
+#endif
 #include 
 
 // standard-mandated includes
@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_HIDE_FROM_ABI constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -383,6 +396,10 @@ public:
 
 private:
 pointer__data_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 
@@ -510,6 +527,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);
+}
+#  endif
+
 _LIBCPP_HIDE_FROM_ABI constexpr reference front() const noexcept
 {
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(!empty(), "span::front() on 
empty span");
@@ -552,6 +578,10 @@ public:
 private:
 pointer   __data_;
 size_type __size_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }
+#  endif
 };
 
 template 
diff --git a/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp 
b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
new file mode 100644
index 00..75a45171185cf3
--- /dev/null
+++ b/libcxx/test/std/containers/views/views.span/span.elem/at.pass.cpp
@@ -0,0 +1,136 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license i

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

2023-12-10 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-webassembly

@llvm/pr-subscribers-clang

Author: Nathan Sidwell (urnathan)


Changes

Reimplement the SysV (non-Microsoft) bitfield access unit computation. For 
avoidance of doubt, this is not an ABI change, but the memory accesses Clang 
emits to access bitfields.

This is a stack of two commits, to make it easier to see the change in 
behaviour.  The first commit is a set of new tests that verify the placement of 
access units under the current algorith.  The second commit is the change, and 
alters those tests as required. The guts of the change is in 
`clang/lib/CodeGen/CGRecordLayoutBuilder.cpp`.

The SysV ABI describes placing bitfields in 'storage units', which may end up 
overlapping eachother or other data members (for instance 'int bf :4;' may be 
in a 32-bit storage unit that overlaps a plan 'char c;' field). LLVM doesn't 
represent structures at that level, and Clang
must create a non-overlapping representation of the structure. That's what's 
happening here. To avoid confusion, I'm using the phrase 'access unit' to refer 
to the integer type Clang uses.

There are two aspects to chosing access units:

1) bitfields that share bits of a single byte must be in the same access unit 
-- you can't touch only one of those bitfields. This computation is unchanged.

2) adjacent bitfields that occupy  distinct bytes, might want to share an 
access  unit. One wants  to do this if  that makes a  better access size. This 
computation is changed.

The current algorithm computes both of these in a single pass. Computing if the 
next bitfield extends the current access unit by requiring it exacly abut the 
previous, and a few other constraints. But there are some issues with this:

a) If there's even a single bit of padding between the two, no concatenation 
occurs. This seems suboptimal.

b) Because of the above-mentioned overlapping, bitfield access units might not 
start on an aligned boundary, and some architectures do not support unaligned 
accesses.

c) Likewise, the access unit might not be able to be a natural 2^n size, and 
the adjacent bytes occupied (with either other data members, or with C++, a 
derived class occupying tail-padding bytes). We must emit exactly a (say) 
24-bit access (to avoid aliasing issues?) (example below).

d) Concatentating access units can lead to an unaligned larger access, and 
again, that's problematic for strict alignment ISA. (consider `struct C { char 
a : 8; char b : 8;};` `C` has alignment 1, but a 2 byte access unit would 
naturally want 2-byte alignment.

My understanding is that larger access units were desired, to reduce the total 
number of accesses, and there was an assertion that the access would be 
narrowed if only some of the bytes changed.

That's not what we've observed, and its demonstrable on x86_64:
```
struct B {
  int a : 16;
  int b : 8;
  char c;
};
```
Here, B::a and B::b could be placed into a 3 byte access unit, but we can't use 
4-byte accesses due to the 4th byte containing `c`. The code we end up 
generating for an increment of B::b is:
```
movzbl  2(%rdi), %eax
shll$16, %eax
movzwl  (%rdi), %ecx
addl%ecx, %eax
addl$65536, %eax# imm = 0x1
movw%ax, (%rdi)
shrl$16, %eax
movb%al, 2(%rdi)
```

we're loading both `B::a` and `B::b`, sticking them together, incrementing 
`B::b` and then only storing the latter. I.e. we've reduced the memory 
accesses, but we're doing more work than necessary. Without the `B::c` field, 
there's 1 byte of padding, and a regular 4-byte access can be used (and is). 
X86_64 is not unique in this behaviour.

I'm of the opinion that one cannot do these in a single pass -- concatenating 
access units fundamentally requires knowing how large both units are, and you 
cannot tell that just by looking at the first bitfield of the second access 
unit.

That's what this patch does: separate the two algorithm into separate phases. 
We first determine which bitfields /must/ be in a single access unit, and then 
determine which of those access units could be concatentated. We pay attention 
to the storage-size of the integral type -- an i24 naturally requires 4 bytes 
of storage. When generating the access units we note barriers such as `:0` 
bitfields (on ABIs that care), and the starting location of the next 
non-bitfield or, the structure tail-padding.

The concatenation only occurs if:

a) The larger access is naturally aligned, or unaligned access is cheap.

b) The larger access storage size doesn't expand into a forbidden zone

c) The larger access is not bigger than a register.

d) Neither of the two access units contain a volatile bitfield.

(Note that if an access-unit's storage-size naturally overlaps a subsequent 
access unit, we'll merge the two provided. A partial overlap can occur with 
packed structures and is handled too.)

ETA: in essence, it only merges ac

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

2023-12-10 Thread Nathan Sidwell via cfe-commits

urnathan wrote:

Rebased

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


[clang] [clang][NFC] Adjust TBAA Base Info API (PR #73263)

2023-12-10 Thread Nathan Sidwell via cfe-commits

urnathan wrote:

> I'd tend to prefer to keep the simpler name for the external interface, and 
> use a more complicated one for use within the class. So maybe introduce 
> getValidBaseTypeInfo().

This naming scheme better?

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


[llvm] [clang-tools-extra] [clang] [libcxx] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits

https://github.com/H-G-Hristov edited 
https://github.com/llvm/llvm-project/pull/74994
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [libcxx] [llvm] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Nikolas Klauser via cfe-commits

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


[clang-tools-extra] [libcxx] [clang] [llvm] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Nikolas Klauser via cfe-commits


@@ -41,7 +41,6 @@ void testRuntimeSpan(Span sp, std::size_t idx)
 assert(r1 == r2);
 }
 
-struct A{};

philnik777 wrote:

Unrelated change?

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


[llvm] [libcxx] [clang-tools-extra] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Nikolas Klauser via cfe-commits

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

Looks mostly good, but I have a few small comments.

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


[llvm] [libcxx] [clang] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Nikolas Klauser via cfe-commits


@@ -0,0 +1,136 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+constexpr void testSpanAt(auto span, int idx, int expectedValue) {
+  // non-const
+  {
+std::same_as decltype(auto) elem = 
span.at(idx);
+assert(elem == expectedValue);
+  }
+
+  // const
+  {
+std::same_as decltype(auto) elem = 
std::as_const(span).at(idx);
+assert(elem == expectedValue);
+  }
+}
+
+constexpr bool test() {
+  // With static extent
+  {
+std::array arr{0, 1, 2, 3, 4, 5, 9084};
+std::span arrSpan{arr};
+
+assert(std::dynamic_extent != arrSpan.extent);
+
+testSpanAt(arrSpan, 0, 0);
+testSpanAt(arrSpan, 1, 1);
+testSpanAt(arrSpan, 6, 9084);
+  }
+
+  // With dynamic extent
+  {
+std::vector vec{0, 1, 2, 3, 4, 5, 9084};
+std::span vecSpan{vec};
+
+assert(std::dynamic_extent == vecSpan.extent);
+
+testSpanAt(vecSpan, 0, 0);
+testSpanAt(vecSpan, 1, 1);
+testSpanAt(vecSpan, 6, 9084);
+  }
+
+  return true;
+}
+
+void test_exceptions() {

philnik777 wrote:

I'd also like to see tests with the last element in range and something like 
`numeric_limits::max()` to have something not even close covered.

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


[clang-tools-extra] [clang] [llvm] [libcxx] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Nikolas Klauser via cfe-commits


@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);

philnik777 wrote:

```suggestion
  if (__idx >= size())
__throw_out_of_range();
  return data()[__idx];
```
Maybe also rename `__idx` to `__index` for better readability. Same below

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


[clang-tools-extra] [clang] [llvm] [libcxx] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Nikolas Klauser via cfe-commits


@@ -0,0 +1,136 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+constexpr void testSpanAt(auto span, int idx, int expectedValue) {
+  // non-const
+  {
+std::same_as decltype(auto) elem = 
span.at(idx);
+assert(elem == expectedValue);
+  }
+
+  // const
+  {
+std::same_as decltype(auto) elem = 
std::as_const(span).at(idx);
+assert(elem == expectedValue);
+  }
+}
+
+constexpr bool test() {
+  // With static extent
+  {
+std::array arr{0, 1, 2, 3, 4, 5, 9084};
+std::span arrSpan{arr};
+
+assert(std::dynamic_extent != arrSpan.extent);
+
+testSpanAt(arrSpan, 0, 0);
+testSpanAt(arrSpan, 1, 1);
+testSpanAt(arrSpan, 6, 9084);
+  }
+
+  // With dynamic extent
+  {
+std::vector vec{0, 1, 2, 3, 4, 5, 9084};
+std::span vecSpan{vec};
+
+assert(std::dynamic_extent == vecSpan.extent);
+
+testSpanAt(vecSpan, 0, 0);
+testSpanAt(vecSpan, 1, 1);
+testSpanAt(vecSpan, 6, 9084);
+  }
+
+  return true;
+}
+
+void test_exceptions() {
+#ifndef TEST_HAS_NO_EXCEPTIONS
+  // With static extent
+  {
+std::array arr{1, 2, 3, 4};
+const std::span arrSpan{arr};
+
+try {
+  TEST_IGNORE_NODISCARD arrSpan.at(arr.size() + 1);

philnik777 wrote:

```suggestion
  (void) arrSpan.at(arr.size() + 1);
```
I'm pretty sure the argument should be `arr.size()`, since that's the first out 
of bounds element.

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


[clang] [Cygwin] Cygwin macro (PR #74973)

2023-12-10 Thread Yingchi Long via cfe-commits

https://github.com/inclyc commented:

Would you please add some tests about your changes?

Also maybe it will be more useful to write some detailed descriptions, so 
others can understand your code easily. Cheers!

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


[clang] [Cygwin] Reduced number of inline elements of CallArgList. (PR #74977)

2023-12-10 Thread Yingchi Long via cfe-commits

https://github.com/inclyc commented:

> This fix bootstraping on Cygwin, using GCC 13.2.0 as stage 0 compiler.
It seems that the size of CallArgList can't exceed an unknown limit.

How about paste some logs here? This change seems to be completely NFC, and I 
suppose it shall work for GCC 13?

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


[llvm] [clang-tools-extra] [libcxx] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Mark de Wever via cfe-commits

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


[clang-tools-extra] [clang] [llvm] [libcxx] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Mark de Wever via cfe-commits

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

Thanks for working in this.

I didn't start the CI jobs since I know they will fail.

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


[libcxx] [llvm] [clang-tools-extra] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Mark de Wever via cfe-commits


@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);

mordante wrote:

And `std::__throw_out_of_range()` for consistency.

I prefer not to use `data()[__idx]`. This differs from the wording in the paper.

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


[llvm] [libcxx] [clang-tools-extra] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Mark de Wever via cfe-commits


@@ -0,0 +1,136 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+constexpr void testSpanAt(auto span, int idx, int expectedValue) {
+  // non-const
+  {
+std::same_as decltype(auto) elem = 
span.at(idx);
+assert(elem == expectedValue);
+  }
+
+  // const
+  {
+std::same_as decltype(auto) elem = 
std::as_const(span).at(idx);
+assert(elem == expectedValue);
+  }
+}
+
+constexpr bool test() {
+  // With static extent
+  {
+std::array arr{0, 1, 2, 3, 4, 5, 9084};
+std::span arrSpan{arr};
+
+assert(std::dynamic_extent != arrSpan.extent);
+
+testSpanAt(arrSpan, 0, 0);
+testSpanAt(arrSpan, 1, 1);
+testSpanAt(arrSpan, 6, 9084);
+  }
+
+  // With dynamic extent
+  {
+std::vector vec{0, 1, 2, 3, 4, 5, 9084};
+std::span vecSpan{vec};
+
+assert(std::dynamic_extent == vecSpan.extent);
+
+testSpanAt(vecSpan, 0, 0);
+testSpanAt(vecSpan, 1, 1);
+testSpanAt(vecSpan, 6, 9084);
+  }
+
+  return true;
+}
+
+void test_exceptions() {
+#ifndef TEST_HAS_NO_EXCEPTIONS
+  // With static extent
+  {
+std::array arr{1, 2, 3, 4};
+const std::span arrSpan{arr};
+
+try {
+  TEST_IGNORE_NODISCARD arrSpan.at(arr.size() + 1);
+  assert(false);
+} catch (std::out_of_range const&) {
+  // pass

mordante wrote:

For libc++ you can test for the expected message.

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


[libcxx] [clang] [llvm] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Mark de Wever via cfe-commits


@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {

mordante wrote:

You need to export this declaration from the `modules/span.inc` too.

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


[llvm] [libcxx] [clang] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Mark de Wever via cfe-commits


@@ -146,6 +147,9 @@ template
 #include <__utility/forward.h>
 #include // for array
 #include   // for byte
+#if _LIBCPP_STD_VER >= 26
+#  include 

mordante wrote:

Typically we unconditionally include headers.

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


[clang-tools-extra] [libcxx] [llvm] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Mark de Wever via cfe-commits


@@ -0,0 +1,136 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+constexpr void testSpanAt(auto span, int idx, int expectedValue) {
+  // non-const
+  {
+std::same_as decltype(auto) elem = 
span.at(idx);
+assert(elem == expectedValue);
+  }
+
+  // const
+  {
+std::same_as decltype(auto) elem = 
std::as_const(span).at(idx);
+assert(elem == expectedValue);
+  }
+}
+
+constexpr bool test() {
+  // With static extent
+  {
+std::array arr{0, 1, 2, 3, 4, 5, 9084};
+std::span arrSpan{arr};
+
+assert(std::dynamic_extent != arrSpan.extent);
+
+testSpanAt(arrSpan, 0, 0);
+testSpanAt(arrSpan, 1, 1);
+testSpanAt(arrSpan, 6, 9084);
+  }
+
+  // With dynamic extent
+  {
+std::vector vec{0, 1, 2, 3, 4, 5, 9084};
+std::span vecSpan{vec};
+
+assert(std::dynamic_extent == vecSpan.extent);
+
+testSpanAt(vecSpan, 0, 0);
+testSpanAt(vecSpan, 1, 1);
+testSpanAt(vecSpan, 6, 9084);
+  }
+
+  return true;
+}
+
+void test_exceptions() {
+#ifndef TEST_HAS_NO_EXCEPTIONS
+  // With static extent
+  {
+std::array arr{1, 2, 3, 4};
+const std::span arrSpan{arr};
+
+try {
+  TEST_IGNORE_NODISCARD arrSpan.at(arr.size() + 1);

mordante wrote:

Why do you sugggest `TEST_IGNORE_NODISCARD` -> (void)? That macro has been 
added for a reason. 

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


[libcxx] [llvm] [clang] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Mark de Wever via cfe-commits


@@ -552,6 +578,10 @@ public:
 private:
 pointer   __data_;
 size_type __size_;
+
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_NORETURN _LIBCPP_HIDE_FROM_ABI void __throw_out_of_range() const { 
std::__throw_out_of_range("span"); }

mordante wrote:

Either remove the helper function and call `std::__throw_out_of_range("span");` 
directly or move it in the `std` namespace. We now add functions that are 
called once and use indirection for it.

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


[llvm] [clang] [clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-12-10 Thread via cfe-commits

https://github.com/Da-Viper updated 
https://github.com/llvm/llvm-project/pull/69102

>From 21156656433fb8d2dc5a805d97cbd20fa916fff9 Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Sun, 15 Oct 2023 11:39:42 +0100
Subject: [PATCH 1/9] Fix #35272: Don't replace typedefs in extern c scope

---
 .../clang-tidy/modernize/UseUsingCheck.cpp   | 16 
 .../clang-tidy/checkers/modernize/use-using.cpp  | 14 ++
 2 files changed, 26 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
index e6293ed48bfddb..841ffb4c9bfe66 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -11,6 +11,12 @@
 #include "clang/Lex/Lexer.h"
 
 using namespace clang::ast_matchers;
+namespace {
+
+AST_MATCHER(clang::LinkageSpecDecl, isExternCLinkage) {
+  return Node.getLanguage() == clang::LinkageSpecDecl::lang_c;
+}
+} // namespace
 
 namespace clang::tidy::modernize {
 
@@ -27,10 +33,12 @@ void 
UseUsingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(typedefDecl(unless(isInstantiated()),
- hasParent(decl().bind(ParentDeclName)))
- .bind(TypedefName),
- this);
+  Finder->addMatcher(
+  typedefDecl(unless(anyOf(isInstantiated(), hasAncestor(linkageSpecDecl(
+ isExternCLinkage(),
+  hasParent(decl().bind(ParentDeclName)))
+  .bind(TypedefName),
+  this);
 
   // This matcher is used to find tag declarations in source code within
   // typedefs. They appear in the AST just *prior* to the typedefs.
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
index 422abee11a7196..0f8f14502d5ca3 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
@@ -325,3 +325,17 @@ typedef bool (*ISSUE_65055_2)(int);
 typedef class ISSUE_67529_1 *ISSUE_67529;
 // CHECK-MESSAGES: :[[@LINE-1]]:1: warning: use 'using' instead of 'typedef'
 // CHECK-FIXES: using ISSUE_67529 = class ISSUE_67529_1 *;
+
+// Some Header
+extern "C" {
+
+typedef int InExternC;
+}
+
+extern "C++" {
+
+typedef int InExternCPP;
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: use 'using' instead of 'typedef' 
[modernize-use-using]
+// CHECK-FIXES: using InExternCPP = int;
+
+}

>From 521dec9325285d1e1819a8bee1bd20eadb7c4158 Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Mon, 16 Oct 2023 23:26:25 +0100
Subject: [PATCH 2/9] Add: Update docs with the new changes. Update
 ReleaseNotes.rst with the changes made

---
 clang-tools-extra/docs/ReleaseNotes.rst  | 5 +
 .../docs/clang-tidy/checks/modernize/use-using.rst   | 9 +
 2 files changed, 14 insertions(+)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index c1b926b296b055..af6b20369c9dcf 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -285,6 +285,10 @@ Changes in existing checks
   ` check to fix function pointer and
   forward declared ``typedef`` correctly.
 
+- Improved :doc:`modernize-use-using
+  ` by ignoring ``typedef`` declaration 
in
+  ``extern "C"`` scope.
+
 - Improved :doc:`performance-faster-string-find
   ` check to properly escape
   single quotes.
@@ -325,6 +329,7 @@ Changes in existing checks
   identify calls to static member functions with out-of-class inline 
definitions.
 
 
+
 Removed checks
 ^^
 
diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst 
b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst
index eeddaf8d8d65ab..048fc26617b7b7 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-using.rst
@@ -28,6 +28,15 @@ After:
   using R_t = struct { int a; };
   using R_p = R_t*;
 
+The checker ignores `typedef` within `extern "C" { ... }` blocks.
+
+.. code-block:: c++
+
+  extern "C" {
+
+typedef int InExternC; // Left intact.
+  }
+
 This check requires using C++11 or higher to run.
 
 Options

>From 3426e0a36606a7e3eeb38c0f436c25aa2fde2b36 Mon Sep 17 00:00:00 2001
From: Ezike Ebuka 
Date: Sun, 22 Oct 2023 20:02:20 +0100
Subject: [PATCH 3/9] Update: commit with review requested changes

---
 clang-tools-extra/docs/ReleaseNotes.rst | 6 +-
 .../docs/clang-tidy/checks/modernize/use-using.rst  | 2 --
 2 files changed, 1 insertion(+), 7 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index af6b203

[libcxx] [llvm] [clang] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Mark de Wever via cfe-commits

https://github.com/mordante commented:

I pressed submit too soon ;-)

You need to update the FTM as implemented too and update the generated files.

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread Björn Schäpers via cfe-commits


@@ -583,20 +583,31 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   return true;
   }
 
-  // If the return type spans multiple lines, wrap before the function name.
-  if (((Current.is(TT_FunctionDeclarationName) &&
-!State.Line->ReturnTypeWrapped &&
-// Don't break before a C# function when no break after return type.
-(!Style.isCSharp() ||
- Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
-// Don't always break between a JavaScript `function` and the function
-// name.
-!Style.isJavaScript()) ||
-   (Current.is(tok::kw_operator) && Previous.isNot(tok::coloncolon))) &&
-  Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter) {
+  const auto WrapBeforeName = [&]() {

HazardyKnusperkeks wrote:

Okay as far as I can see the conditions are transformed correctly, thanks for 
that.

But there is no addition from you, or am I missing something? Is the problem 
already fixed?

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread Björn Schäpers via cfe-commits


@@ -26465,6 +26451,21 @@ TEST_F(FormatTest, BreakAfterAttributes) {
"{\n"
"}",
CtorDtorCode, Style);
+
+  Style.BreakBeforeBraces = FormatStyle::BS_Attach;
+  Style.ReferenceAlignment = FormatStyle::ReferenceAlignmentStyle::RAS_Left;
+  verifyFormat("struct Foo {\n"
+ "  [[maybe_unused]]\n"
+ "  void operator+();\n"
+ "};\n"
+ "[[nodiscard]]\n"
+ "Foo& operator-(Foo&);",
+

HazardyKnusperkeks wrote:

Remove the blank line.

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread Björn Schäpers via cfe-commits


@@ -583,20 +583,31 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   return true;
   }
 
-  // If the return type spans multiple lines, wrap before the function name.
-  if (((Current.is(TT_FunctionDeclarationName) &&
-!State.Line->ReturnTypeWrapped &&
-// Don't break before a C# function when no break after return type.
-(!Style.isCSharp() ||
- Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
-// Don't always break between a JavaScript `function` and the function
-// name.
-!Style.isJavaScript()) ||
-   (Current.is(tok::kw_operator) && Previous.isNot(tok::coloncolon))) &&
-  Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter) {
+  const auto WrapBeforeName = [&]() {

HazardyKnusperkeks wrote:

```suggestion
  const auto WrapBeforeName = [&] {
```
I think LLVM style is to omit the empty parenthesis.

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread Björn Schäpers via cfe-commits


@@ -583,21 +583,31 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   return true;
   }
 
-  // If the return type spans multiple lines, wrap before the function name.
-  if (((Current.is(TT_FunctionDeclarationName) &&
-!State.Line->ReturnTypeWrapped &&
-// Don't break before a C# function when no break after return type.
-(!Style.isCSharp() ||
- Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
-// Don't always break between a JavaScript `function` and the function
-// name.
-!Style.isJavaScript()) ||
-   (Current.is(tok::kw_operator) && Previous.isNot(tok::coloncolon))) &&
-  Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter &&
-  (Style.isCpp() && Current.Tok.isNot(tok::kw_operator))) {
+  const auto WrapBeforeName = [&]() {
+// If the return type spans multiple lines, wrap before the function name.
+if (Current.isNot(TT_FunctionDeclarationName) ||
+State.Line->ReturnTypeWrapped) {
+  return false;
+}
+if (Previous.is(tok::kw_template) || Current.is(tok::kw_operator))
+  return false;
+if (!CurrentState.BreakBeforeParameter)
+  return false;
+return true;

HazardyKnusperkeks wrote:

```suggestion
// Don't break before a C# function when no break after return type.
return (!Style.isCSharp() ||
 Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
// Don't always break between a JavaScript `function` and the function
// name.
!Style.isJavaScript();
```

Don't call the lambda twice.

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


[clang] 65a1841 - [DirectoryWatcher] Include limits.h instead of MathExtras.h (NFC)

2023-12-10 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2023-12-10T12:12:54-08:00
New Revision: 65a18412ab26f92df133ca1ef3ff7ff7dbf3c5f8

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

LOG: [DirectoryWatcher] Include limits.h instead of MathExtras.h (NFC)

Added: 


Modified: 
clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp

Removed: 




diff  --git a/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp 
b/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
index 9b3d2571f29f6..beca9586988b5 100644
--- a/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
+++ b/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
@@ -14,7 +14,6 @@
 #include "llvm/Support/AlignOf.h"
 #include "llvm/Support/Errno.h"
 #include "llvm/Support/Error.h"
-#include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Path.h"
 #include 
 #include 
@@ -25,6 +24,7 @@
 #include 
 
 #include 
+#include 
 #include 
 #include 
 #include 



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


[llvm] [clang-tools-extra] [libcxx] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Nikolas Klauser via cfe-commits


@@ -0,0 +1,136 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+constexpr void testSpanAt(auto span, int idx, int expectedValue) {
+  // non-const
+  {
+std::same_as decltype(auto) elem = 
span.at(idx);
+assert(elem == expectedValue);
+  }
+
+  // const
+  {
+std::same_as decltype(auto) elem = 
std::as_const(span).at(idx);
+assert(elem == expectedValue);
+  }
+}
+
+constexpr bool test() {
+  // With static extent
+  {
+std::array arr{0, 1, 2, 3, 4, 5, 9084};
+std::span arrSpan{arr};
+
+assert(std::dynamic_extent != arrSpan.extent);
+
+testSpanAt(arrSpan, 0, 0);
+testSpanAt(arrSpan, 1, 1);
+testSpanAt(arrSpan, 6, 9084);
+  }
+
+  // With dynamic extent
+  {
+std::vector vec{0, 1, 2, 3, 4, 5, 9084};
+std::span vecSpan{vec};
+
+assert(std::dynamic_extent == vecSpan.extent);
+
+testSpanAt(vecSpan, 0, 0);
+testSpanAt(vecSpan, 1, 1);
+testSpanAt(vecSpan, 6, 9084);
+  }
+
+  return true;
+}
+
+void test_exceptions() {
+#ifndef TEST_HAS_NO_EXCEPTIONS
+  // With static extent
+  {
+std::array arr{1, 2, 3, 4};
+const std::span arrSpan{arr};
+
+try {
+  TEST_IGNORE_NODISCARD arrSpan.at(arr.size() + 1);

philnik777 wrote:

For what reason though? In which case is `TEST_IGNORE_NODISCARD` better to 
understand than `(void)`? I'm pretty sure I've pushed back against uses of this 
macro in the past and haven't gotten any good response for why one would ever 
use it. IMO this makes things just more confusing.

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


[libcxx] [clang] [llvm] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Nikolas Klauser via cfe-commits


@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);

philnik777 wrote:

Honestly, that seems really weird to me. Why would you write in in such a 
convoluted way? This seems like a case where the wording should simply be 
adjusted to something simpler, or I'm missing something and there is a test 
missing.

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


[llvm] [clang] [libcxx] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits


@@ -41,7 +41,6 @@ void testRuntimeSpan(Span sp, std::size_t idx)
 assert(r1 == r2);
 }
 
-struct A{};

H-G-Hristov wrote:

Yes, I can restore that change. Initially I was looking into reusing op_idx 
tests and I noticed that this declaration is unused.

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


[llvm] [clang] [libcxx] [clang-tools-extra] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits


@@ -343,6 +347,15 @@ public:
 return __data_[__idx];
 }
 
+#  if _LIBCPP_STD_VER >= 26
+_LIBCPP_HIDE_FROM_ABI constexpr reference at(size_type __idx) const {
+  if (__idx >= size()) {
+__throw_out_of_range();
+  }
+  return *(data() + __idx);

H-G-Hristov wrote:

I already renamed the arg as you suggested but in the synopsis both methods 
would be using `idx`
```c++
constexpr reference operator[](size_type idx) const;
constexpr reference at(size_type idx) const;
```
Would it make sense to also rename the arg of `operator[]` for consistency?

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


[clang] [clang-tools-extra] [llvm] [libcxx] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Hristo Hristov via cfe-commits


@@ -0,0 +1,136 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+constexpr void testSpanAt(auto span, int idx, int expectedValue) {
+  // non-const
+  {
+std::same_as decltype(auto) elem = 
span.at(idx);
+assert(elem == expectedValue);
+  }
+
+  // const
+  {
+std::same_as decltype(auto) elem = 
std::as_const(span).at(idx);
+assert(elem == expectedValue);
+  }
+}
+
+constexpr bool test() {
+  // With static extent
+  {
+std::array arr{0, 1, 2, 3, 4, 5, 9084};
+std::span arrSpan{arr};
+
+assert(std::dynamic_extent != arrSpan.extent);
+
+testSpanAt(arrSpan, 0, 0);
+testSpanAt(arrSpan, 1, 1);
+testSpanAt(arrSpan, 6, 9084);
+  }
+
+  // With dynamic extent
+  {
+std::vector vec{0, 1, 2, 3, 4, 5, 9084};
+std::span vecSpan{vec};
+
+assert(std::dynamic_extent == vecSpan.extent);
+
+testSpanAt(vecSpan, 0, 0);
+testSpanAt(vecSpan, 1, 1);
+testSpanAt(vecSpan, 6, 9084);
+  }
+
+  return true;
+}
+
+void test_exceptions() {
+#ifndef TEST_HAS_NO_EXCEPTIONS
+  // With static extent
+  {
+std::array arr{1, 2, 3, 4};
+const std::span arrSpan{arr};
+
+try {
+  TEST_IGNORE_NODISCARD arrSpan.at(arr.size() + 1);

H-G-Hristov wrote:

C++ Core Guidelines: [ES.48: Avoid 
casts](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es48-avoid-casts)

> Never cast to (void) to ignore a [[nodiscard]]return value. If you 
> deliberately want to discard such a result, first think hard about whether 
> that is really a good idea (there is usually a good reason the author of the 
> function or of the return type used [[nodiscard]] in the first place). If you 
> still think it's appropriate and your code reviewer agrees, use std::ignore = 
> to turn off the warning which is simple, portable, and easy to grep.
Alternatives
...
>- Use std::ignore = to ignore [[nodiscard]] values.

Maybe use `std::ignore` instead?

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


[llvm] [clang-tools-extra] [libcxx] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

2023-12-10 Thread Nikolas Klauser via cfe-commits


@@ -0,0 +1,136 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// 
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+constexpr void testSpanAt(auto span, int idx, int expectedValue) {
+  // non-const
+  {
+std::same_as decltype(auto) elem = 
span.at(idx);
+assert(elem == expectedValue);
+  }
+
+  // const
+  {
+std::same_as decltype(auto) elem = 
std::as_const(span).at(idx);
+assert(elem == expectedValue);
+  }
+}
+
+constexpr bool test() {
+  // With static extent
+  {
+std::array arr{0, 1, 2, 3, 4, 5, 9084};
+std::span arrSpan{arr};
+
+assert(std::dynamic_extent != arrSpan.extent);
+
+testSpanAt(arrSpan, 0, 0);
+testSpanAt(arrSpan, 1, 1);
+testSpanAt(arrSpan, 6, 9084);
+  }
+
+  // With dynamic extent
+  {
+std::vector vec{0, 1, 2, 3, 4, 5, 9084};
+std::span vecSpan{vec};
+
+assert(std::dynamic_extent == vecSpan.extent);
+
+testSpanAt(vecSpan, 0, 0);
+testSpanAt(vecSpan, 1, 1);
+testSpanAt(vecSpan, 6, 9084);
+  }
+
+  return true;
+}
+
+void test_exceptions() {
+#ifndef TEST_HAS_NO_EXCEPTIONS
+  // With static extent
+  {
+std::array arr{1, 2, 3, 4};
+const std::span arrSpan{arr};
+
+try {
+  TEST_IGNORE_NODISCARD arrSpan.at(arr.size() + 1);

philnik777 wrote:

Sure, why not.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits


@@ -0,0 +1,143 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wmissing-format-attribute %s
+
+#include 
+#include 
+#include 
+#include 
+
+__attribute__((__format__ (__scanf__, 1, 4)))
+void f1(char *out, const size_t len, const char *format, ... /* args */)
+{
+va_list args;
+vsnprintf(out, len, format, args); // expected-warning {{diagnostic 
behavior may be improved by adding the 'printf' format attribute to the 
declaration of 'f1'}}
+   // CHECK-FIXES: 
__attribute__((format(printf, 1, 4)))

aaronpuchert wrote:

Shouldn't it be `__attribute__((format(printf, 3, 4)))`, since the format 
string is the third argument? The first argument is just the target buffer.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits


@@ -6849,6 +6849,73 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
 }
 
+// Warn if parent function misses format attribute. Parent function misses
+// format attribute if there is an argument format string forwarded to calling
+// function with format attribute, parent function has a parameter which type
+// is either string or pointer to char and parent function format attribute
+// type does not match with calling function format attribute type.
+void Sema::DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc) {
+  assert(FDecl);
+
+  // Check if function has format attribute with forwarded format string.
+  IdentifierInfo *AttrType;
+  if (!llvm::any_of(
+  FDecl->specific_attrs(), [&](const FormatAttr *Attr) {
+if (!Args[Attr->getFirstArg()]->getReferencedDeclOfCallee())
+  return false;
+
+AttrType = Attr->getType();
+return true;
+  }))
+return;
+
+  const FunctionDecl *ParentFuncDecl = getCurFunctionDecl();
+  if (!ParentFuncDecl)
+return;
+
+  // Check if parent function has string or pointer to char parameter.
+  unsigned int StringIndex = 0;
+  if (!llvm::any_of(
+  ParentFuncDecl->parameters(), [&](const ParmVarDecl *Param) {
+StringIndex = Param->getFunctionScopeIndex() + 1;
+QualType Ty = Param->getType();
+if (isNSStringType(Ty, Context, true))
+  return true;
+if (isCFStringType(Ty, Context))
+  return true;
+if (Ty->isPointerType() &&
+Ty->castAs()
+->getPointeeType()
+->isSpecificBuiltinType(BuiltinType::Char_S))
+  return true;
+return false;
+  }))
+return;
+
+  // Check if there is parent function format attribute which type matches
+  // calling function format attribute type.
+  if (llvm::any_of(
+  ParentFuncDecl->specific_attrs(),
+  [&](const FormatAttr *Attr) { return Attr->getType() == AttrType; }))
+return;

aaronpuchert wrote:

The index arguments could still be off, should we warn about that?

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits

https://github.com/aaronpuchert commented:

Two additional checks that might be interesting:
* Look at the `FormatIdx` argument. Is it a `DeclRefExpr` referring to a 
`ParmVarDecl`, perhaps with some conversions? (There is probably going to be an 
`LValueToRValue` conversion at least. There are special `Ignore*` functions on 
`Expr` to unwrap that.) If it is, we should propagate the attribute, if not 
then not.
* For `FirstArg` it seems that GCC only warns when we call a `v*` function, or 
the called function has `FirstArg == 0`, probably because forwarding to a 
variadic function isn't really possible in C. It doesn't seem to check whether 
we're actually forwarding. What you've implemented here (deciding based on 
`ParentFuncDecl->isVariadic()`) seems like a reasonable heuristic. But it 
probably makes sense to additionally restrict based on the archetype or 
`FirstArg`. Or is that what you're doing with `Args[Attr->getFirstArg()]`?

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits


@@ -6849,6 +6849,73 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
 }
 
+// Warn if parent function misses format attribute. Parent function misses
+// format attribute if there is an argument format string forwarded to calling
+// function with format attribute, parent function has a parameter which type
+// is either string or pointer to char and parent function format attribute
+// type does not match with calling function format attribute type.
+void Sema::DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc) {
+  assert(FDecl);
+
+  // Check if function has format attribute with forwarded format string.
+  IdentifierInfo *AttrType;
+  if (!llvm::any_of(
+  FDecl->specific_attrs(), [&](const FormatAttr *Attr) {
+if (!Args[Attr->getFirstArg()]->getReferencedDeclOfCallee())

aaronpuchert wrote:

Do we need to do a bounds check before we access into the array or has this 
already been checked?

Also, the attribute arguments start counting at 1, but array access starts at 
0, so I would assume we're off by one here?

And shouldn't we look up `Attr->getFormatIdx()` instead? The "first argument" 
can be 0, if the caller takes a `va_list` for example.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits


@@ -0,0 +1,132 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wmissing-format-attribute %s
+
+#include 
+#include 
+
+void f1(const std::string &str, ... /* args */)
+{
+va_list args;
+vscanf(str.c_str(), args); // no warning
+vprintf(str.c_str(), args); // no warning
+}
+
+__attribute__((format(printf, 1, 2))) // expected-error: {{format argument not 
a string type}}
+void f2(const std::string &str, ... /* args */);
+
+void f3(std::string_view str, ... /* args */)
+{
+va_list args;
+vscanf(std::string(str).c_str(), args); // no warning
+vprintf(std::string(str).c_str(), args); // no warning
+}
+
+__attribute__((format(printf, 1, 2))) // expected-error {{format argument not 
a string type}}
+void f4(std::string_view str, ... /* args */);
+
+void f5(const std::wstring &str, ... /* args */)
+{
+va_list args;
+vscanf((const char *)str.c_str(), args); // no warning
+vprintf((const char *)str.c_str(), args); // no warning
+}
+
+__attribute__((format(printf, 1, 2))) // expected-error {{format argument not 
a string type}}
+void f6(const std::wstring &str, ... /* args */);
+
+void f7(std::wstring_view str, ... /* args */)
+{
+va_list args;
+vscanf((const char *) std::wstring(str).c_str(), args); // no warning
+vprintf((const char *) std::wstring(str).c_str(), args); // no warning
+}
+
+__attribute__((format(printf, 1, 2))) // expected-error {{format argument not 
a string type}}
+void f8(std::wstring_view str, ... /* args */);
+
+void f9(const wchar_t *out, ... /* args */)
+{
+va_list args;
+vprintf(out, args); // expected-error {{no matching function for call to 
'vprintf'}}
+vscanf((const char *) out, args); // no warning
+vscanf((char *) out, args); // no warning
+}
+
+__attribute__((format(printf, 1, 2))) // expected-error {{format argument not 
a string type}}
+void f10(const wchar_t *out, ... /* args */);
+
+void f11(const char16_t *out, ... /* args */)
+{
+va_list args;
+vscanf(out, args); // expected-error {{no matching function for call to 
'vscanf'}}
+}
+
+__attribute__((format(printf, 1, 2))) // expected-error {{format argument not 
a string type}}
+void f12(const char16_t *out, ... /* args */);
+
+void f13(const char32_t *out, ... /* args */)
+{
+va_list args;
+vscanf(out, args); // expected-error {{no matching function for call to 
'vscanf'}}
+}
+
+__attribute__((format(scanf, 1, 2))) // expected-error {{format argument not a 
string type}}
+void f14(const char32_t *out, ... /* args */);
+
+void f15(const char *out, ... /* args */)
+{
+va_list args;
+vscanf(out, args); // expected-warning {{diagnostic behavior may be 
improved by adding the 'scanf' format attribute to the declaration of 'f15'}}
+}
+
+__attribute__((format(scanf, 1, 2)))
+void f16(const char *out, ... /* args */)
+{
+va_list args;
+vscanf(out, args); // no warning
+}
+
+void f17(const unsigned char *out, ... /* args */)
+{
+va_list args;
+vscanf(out, args); // expected-error {{no matching function for call to 
'vscanf'}}
+}
+
+__attribute__((format(scanf, 1, 2)))
+void f18(const unsigned char *out, ... /* args */)
+{
+va_list args;
+vscanf(out, args); // expected-error {{no matching function for call to 
'vscanf'}}
+}
+
+void f19(const signed char *out, ... /* args */)
+{
+va_list args;
+vscanf(out, args); // expected-error {{no matching function for call to 
'vscanf'}}
+}
+
+__attribute__((format(scanf, 1, 2)))
+void f20(const signed char *out, ... /* args */)
+{
+va_list args;
+vscanf(out, args); // expected-error {{no matching function for call to 
'vscanf'}}
+}
+
+void f21(const char out[], ... /* args */)
+{
+va_list args;
+vscanf(out, args); // expected-warning {{diagnostic behavior may be 
improved by adding the 'scanf' format attribute to the declaration of 'f21'}}
+}
+
+__attribute__((format(scanf, 1, 2)))
+void f22(const char out[], ... /* args */)
+{
+va_list args;
+vscanf(out, args); // no warning
+}
+
+template 
+void func(char (&str)[N], ...)
+{
+va_list args;
+vprintf(str, args); // no warning
+}

aaronpuchert wrote:

What makes C++ interesting is the implicit `this` parameter in non-static 
member functions, maybe you can add tests for that? The existing tests here 
seem to be mostly about cases where the attribute does not apply due to some 
technicality.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits


@@ -0,0 +1,143 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wmissing-format-attribute %s
+
+#include 
+#include 
+#include 
+#include 
+
+__attribute__((__format__ (__scanf__, 1, 4)))
+void f1(char *out, const size_t len, const char *format, ... /* args */)
+{
+va_list args;
+vsnprintf(out, len, format, args); // expected-warning {{diagnostic 
behavior may be improved by adding the 'printf' format attribute to the 
declaration of 'f1'}}
+   // CHECK-FIXES: 
__attribute__((format(printf, 1, 4)))
+}
+
+void f2(char *out, va_list args)
+{
+vprintf(out, args); // expected-warning {{diagnostic behavior may be 
improved by adding the 'printf' format attribute to the declaration of 'f2'}}
+// CHECK-FIXES: __attribute__((format(printf, 1, 0)))
+vscanf(out, args); // expected-warning {{diagnostic behavior may be 
improved by adding the 'scanf' format attribute to the declaration of 'f2'}}
+   // CHECK-FIXES: __attribute__((format(scanf, 1, 0)))
+}
+
+void f3(char* out, ... /* args */)
+{
+va_list args;
+vprintf("test", args); // no warning
+}
+
+void f4(char *out, ... /* args */)
+{
+const char *ch;
+va_list args;
+vscanf(ch, args); // expected-warning {{diagnostic behavior may be 
improved by adding the 'scanf' format attribute to the declaration of 'f4'}}
+  // CHECK-FIXES: __attribute__((format(scanf, 1, 2)))

aaronpuchert wrote:

I don't think we can propagate the attribute here, since the format string is a 
local variable. It doesn't come from the caller.

The `out` parameter seems unused here, and has no relation to the format string 
`ch`.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits


@@ -6849,6 +6849,73 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
 }
 
+// Warn if parent function misses format attribute. Parent function misses
+// format attribute if there is an argument format string forwarded to calling
+// function with format attribute, parent function has a parameter which type
+// is either string or pointer to char and parent function format attribute
+// type does not match with calling function format attribute type.
+void Sema::DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc) {
+  assert(FDecl);
+
+  // Check if function has format attribute with forwarded format string.
+  IdentifierInfo *AttrType;
+  if (!llvm::any_of(
+  FDecl->specific_attrs(), [&](const FormatAttr *Attr) {
+if (!Args[Attr->getFirstArg()]->getReferencedDeclOfCallee())
+  return false;
+
+AttrType = Attr->getType();
+return true;
+  }))
+return;
+
+  const FunctionDecl *ParentFuncDecl = getCurFunctionDecl();
+  if (!ParentFuncDecl)
+return;
+
+  // Check if parent function has string or pointer to char parameter.
+  unsigned int StringIndex = 0;
+  if (!llvm::any_of(
+  ParentFuncDecl->parameters(), [&](const ParmVarDecl *Param) {
+StringIndex = Param->getFunctionScopeIndex() + 1;
+QualType Ty = Param->getType();
+if (isNSStringType(Ty, Context, true))
+  return true;
+if (isCFStringType(Ty, Context))
+  return true;
+if (Ty->isPointerType() &&
+Ty->castAs()
+->getPointeeType()
+->isSpecificBuiltinType(BuiltinType::Char_S))
+  return true;
+return false;
+  }))
+return;

aaronpuchert wrote:

I don't think we can decide this based on the type. We should look at the 
argument and check if it's a `DeclRefExpr` referring to a parameter of the 
parent function. There can be other (unrelated) string arguments. (See also my 
comments in the tests.)

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits


@@ -6849,6 +6849,73 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
 }
 
+// Warn if parent function misses format attribute. Parent function misses
+// format attribute if there is an argument format string forwarded to calling
+// function with format attribute, parent function has a parameter which type
+// is either string or pointer to char and parent function format attribute
+// type does not match with calling function format attribute type.
+void Sema::DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc) {
+  assert(FDecl);
+
+  // Check if function has format attribute with forwarded format string.
+  IdentifierInfo *AttrType;
+  if (!llvm::any_of(
+  FDecl->specific_attrs(), [&](const FormatAttr *Attr) {
+if (!Args[Attr->getFirstArg()]->getReferencedDeclOfCallee())
+  return false;
+
+AttrType = Attr->getType();
+return true;
+  }))
+return;
+
+  const FunctionDecl *ParentFuncDecl = getCurFunctionDecl();
+  if (!ParentFuncDecl)
+return;
+
+  // Check if parent function has string or pointer to char parameter.
+  unsigned int StringIndex = 0;
+  if (!llvm::any_of(
+  ParentFuncDecl->parameters(), [&](const ParmVarDecl *Param) {
+StringIndex = Param->getFunctionScopeIndex() + 1;
+QualType Ty = Param->getType();
+if (isNSStringType(Ty, Context, true))
+  return true;
+if (isCFStringType(Ty, Context))
+  return true;
+if (Ty->isPointerType() &&
+Ty->castAs()
+->getPointeeType()
+->isSpecificBuiltinType(BuiltinType::Char_S))
+  return true;
+return false;
+  }))
+return;
+
+  // Check if there is parent function format attribute which type matches
+  // calling function format attribute type.
+  if (llvm::any_of(
+  ParentFuncDecl->specific_attrs(),
+  [&](const FormatAttr *Attr) { return Attr->getType() == AttrType; }))
+return;
+
+  unsigned int FirstToCheck =
+  ParentFuncDecl->isVariadic() ? (ParentFuncDecl->getNumParams() + 1) : 0;
+
+  // Diagnose missing format attributes
+  std::string InsertionText;
+  llvm::raw_string_ostream OS(InsertionText);
+  OS << "__attribute__((format(" << AttrType->getName() << ", "
+ << std::to_string(StringIndex) << ", " << std::to_string(FirstToCheck)

aaronpuchert wrote:

I'm surprised that we need `std::to_string` here, can 
`llvm::raw_string_ostream` not print integers directly?

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits


@@ -583,20 +583,31 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   return true;
   }
 
-  // If the return type spans multiple lines, wrap before the function name.
-  if (((Current.is(TT_FunctionDeclarationName) &&
-!State.Line->ReturnTypeWrapped &&
-// Don't break before a C# function when no break after return type.
-(!Style.isCSharp() ||
- Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
-// Don't always break between a JavaScript `function` and the function
-// name.
-!Style.isJavaScript()) ||
-   (Current.is(tok::kw_operator) && Previous.isNot(tok::coloncolon))) &&
-  Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter) {
+  const auto WrapBeforeName = [&]() {

XDeme wrote:

The original condition could be rewritten like this:
```cpp
  const auto WrapBeforeName = [&] {
if(Previous.is(tok::kw_template) || !CurrentState.BreakBeforeParameter)
  return false;
if((Current.isNot(tok::kw_operator) || Previous.is(tok::coloncolon)) && 
(Current.isNot(TT_FunctionDeclarationName) || State.Line->ReturnTypeWrapped))
  return false;
// Don't break before a C# function when no break after return type.
return (!Style.isCSharp() ||
Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
   // Don't always break between a JavaScript `function` and the
   // function name.
   !Style.isJavaScript();
  };
```

The problem is that `Current.isNot(tok::kw_operator)` is returning false and 
then the last check will return true, forcing the return type of a operator 
overload to wrap.
We could fix this by adding a `Curret.is(tok::kw_operator) return false` before 
that line like this:
```cpp
  const auto WrapBeforeName = [&] {
if(Previous.is(tok::kw_template) || !CurrentState.BreakBeforeParameter)
  return false;
if(Current.is(tok::kw_operator))
  return false;
if((Current.isNot(tok::kw_operator) || Previous.is(tok::coloncolon)) && 
(Current.isNot(TT_FunctionDeclarationName) || State.Line->ReturnTypeWrapped))
  return false;
return (!Style.isCSharp() ||
Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
   // Don't always break between a JavaScript `function` and the
   // function name.
   !Style.isJavaScript();
  };
```

I am not sure what the original conditional was exactly checking for, but my 
change didn't break any test.

And for the `ReferenceAlignment: Left` with `BreakAfterAttributes: Always` not 
working on non-member operator overload, it fixed by just changing this 
condition.

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

https://github.com/XDeme updated https://github.com/llvm/llvm-project/pull/74943

>From b80f8579dbc745ddfaa3d60770dd0d3e79e6c641 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Sat, 9 Dec 2023 14:31:12 -0300
Subject: [PATCH 1/7] Fixes overload operator in BreakAfterAttributes

---
 clang/lib/Format/ContinuationIndenter.cpp |  3 ++-
 clang/unittests/Format/FormatTest.cpp | 14 ++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 9e4e939503dfe4..de3768d475e7b2 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -593,7 +593,8 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
 // name.
 !Style.isJavaScript()) ||
(Current.is(tok::kw_operator) && Previous.isNot(tok::coloncolon))) &&
-  Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter) {
+  Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter &&
+  (Style.isCpp() && Current.Tok.isNot(tok::kw_operator))) {
 return true;
   }
 
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 24b2fd599dc397..a1f3beed475ff3 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26417,6 +26417,20 @@ TEST_F(FormatTest, BreakAfterAttributes) {
"void g() {}",
CtorDtorCode, Style);
 
+  Style.ReferenceAlignment = FormatStyle::ReferenceAlignmentStyle::RAS_Left;
+  constexpr StringRef OperatorOverloadCode(
+  "struct Foo {\n"
+  "[[maybe_unused]] void operator+();\n"
+  "};\n"
+  "[[nodiscard]] Foo& operator-(Foo&);");
+  verifyFormat("struct Foo {\n"
+   "  [[maybe_unused]]\n"
+   "  void operator+();\n"
+   "};\n"
+   "[[nodiscard]]\n"
+   "Foo& operator-(Foo&);",
+   OperatorOverloadCode, Style);
+
   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
   verifyFormat("struct Foo {\n"
"  [[deprecated]]\n"

>From 67a018f8c27f547fdea3443100ec7255e7aa4f2e Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Sat, 9 Dec 2023 16:05:12 -0300
Subject: [PATCH 2/7] Addresses 1, 2 and 4 comments

---
 clang/lib/Format/ContinuationIndenter.cpp |  2 +-
 clang/unittests/Format/FormatTest.cpp | 20 
 2 files changed, 9 insertions(+), 13 deletions(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index de3768d475e7b2..d05a16f87038ce 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -594,7 +594,7 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
 !Style.isJavaScript()) ||
(Current.is(tok::kw_operator) && Previous.isNot(tok::coloncolon))) &&
   Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter &&
-  (Style.isCpp() && Current.Tok.isNot(tok::kw_operator))) {
+  Current.Tok.isNot(tok::kw_operator)) {
 return true;
   }
 
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index a1f3beed475ff3..bccc3162c34367 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26418,18 +26418,14 @@ TEST_F(FormatTest, BreakAfterAttributes) {
CtorDtorCode, Style);
 
   Style.ReferenceAlignment = FormatStyle::ReferenceAlignmentStyle::RAS_Left;
-  constexpr StringRef OperatorOverloadCode(
-  "struct Foo {\n"
-  "[[maybe_unused]] void operator+();\n"
-  "};\n"
-  "[[nodiscard]] Foo& operator-(Foo&);");
-  verifyFormat("struct Foo {\n"
-   "  [[maybe_unused]]\n"
-   "  void operator+();\n"
-   "};\n"
-   "[[nodiscard]]\n"
-   "Foo& operator-(Foo&);",
-   OperatorOverloadCode, Style);
+  verifyNoChange("struct Foo {\n"
+ "  [[maybe_unused]]\n"
+ "  void operator+();\n"
+ "};\n"
+ "[[nodiscard]]\n"
+ "Foo& operator-(Foo&);",
+ Style);
+  Style.ReferenceAlignment = getLLVMStyle().ReferenceAlignment;
 
   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
   verifyFormat("struct Foo {\n"

>From f9b8d8cee9cf1fd313497c72e7829114a5d4b083 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Sat, 9 Dec 2023 18:46:15 -0300
Subject: [PATCH 3/7] Addresses comment 3

---
 clang/lib/Format/ContinuationIndenter.cpp | 25 +--
 1 file changed, 14 insertions(+), 11 deletions(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index d05a16f87038ce..a9ce3d20142984 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -584,20 +584,23 @@ bool ContinuationIndenter::mustBreak(const LineSta

[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits


@@ -583,21 +583,31 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   return true;
   }
 
-  // If the return type spans multiple lines, wrap before the function name.
-  if (((Current.is(TT_FunctionDeclarationName) &&
-!State.Line->ReturnTypeWrapped &&
-// Don't break before a C# function when no break after return type.
-(!Style.isCSharp() ||
- Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
-// Don't always break between a JavaScript `function` and the function
-// name.
-!Style.isJavaScript()) ||
-   (Current.is(tok::kw_operator) && Previous.isNot(tok::coloncolon))) &&
-  Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter &&
-  (Style.isCpp() && Current.Tok.isNot(tok::kw_operator))) {
+  const auto WrapBeforeName = [&]() {
+// If the return type spans multiple lines, wrap before the function name.
+if (Current.isNot(TT_FunctionDeclarationName) ||
+State.Line->ReturnTypeWrapped) {
+  return false;
+}
+if (Previous.is(tok::kw_template) || Current.is(tok::kw_operator))
+  return false;
+if (!CurrentState.BreakBeforeParameter)
+  return false;
+return true;

XDeme wrote:

Fixed

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits


@@ -26465,6 +26451,21 @@ TEST_F(FormatTest, BreakAfterAttributes) {
"{\n"
"}",
CtorDtorCode, Style);
+
+  Style.BreakBeforeBraces = FormatStyle::BS_Attach;
+  Style.ReferenceAlignment = FormatStyle::ReferenceAlignmentStyle::RAS_Left;
+  verifyFormat("struct Foo {\n"
+ "  [[maybe_unused]]\n"
+ "  void operator+();\n"
+ "};\n"
+ "[[nodiscard]]\n"
+ "Foo& operator-(Foo&);",
+

XDeme wrote:

Fixed

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits


@@ -583,20 +583,31 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   return true;
   }
 
-  // If the return type spans multiple lines, wrap before the function name.
-  if (((Current.is(TT_FunctionDeclarationName) &&
-!State.Line->ReturnTypeWrapped &&
-// Don't break before a C# function when no break after return type.
-(!Style.isCSharp() ||
- Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
-// Don't always break between a JavaScript `function` and the function
-// name.
-!Style.isJavaScript()) ||
-   (Current.is(tok::kw_operator) && Previous.isNot(tok::coloncolon))) &&
-  Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter) {
+  const auto WrapBeforeName = [&]() {

XDeme wrote:

Fixed

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

XDeme wrote:

One thing that I checked only now, is that with clang-format 16.0.6 and 17.0.6, 
it formats correctly.
But with `clang-format version 18.0.0 (https://github.com/llvm/llvm-project.git 
a6c02edd6eac476523b5c73f29619a7a9e054872)` is doens't anymore, so this is a 
regression introduced recently.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2023-12-10 Thread Aaron Puchert via cfe-commits


@@ -6849,6 +6849,73 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
 }
 
+// Warn if parent function misses format attribute. Parent function misses
+// format attribute if there is an argument format string forwarded to calling
+// function with format attribute, parent function has a parameter which type
+// is either string or pointer to char and parent function format attribute
+// type does not match with calling function format attribute type.
+void Sema::DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc) {
+  assert(FDecl);
+
+  // Check if function has format attribute with forwarded format string.
+  IdentifierInfo *AttrType;
+  if (!llvm::any_of(
+  FDecl->specific_attrs(), [&](const FormatAttr *Attr) {
+if (!Args[Attr->getFirstArg()]->getReferencedDeclOfCallee())
+  return false;
+
+AttrType = Attr->getType();
+return true;
+  }))
+return;
+
+  const FunctionDecl *ParentFuncDecl = getCurFunctionDecl();
+  if (!ParentFuncDecl)
+return;
+
+  // Check if parent function has string or pointer to char parameter.
+  unsigned int StringIndex = 0;
+  if (!llvm::any_of(
+  ParentFuncDecl->parameters(), [&](const ParmVarDecl *Param) {
+StringIndex = Param->getFunctionScopeIndex() + 1;
+QualType Ty = Param->getType();
+if (isNSStringType(Ty, Context, true))
+  return true;
+if (isCFStringType(Ty, Context))
+  return true;
+if (Ty->isPointerType() &&
+Ty->castAs()
+->getPointeeType()
+->isSpecificBuiltinType(BuiltinType::Char_S))
+  return true;
+return false;
+  }))
+return;

aaronpuchert wrote:

Hmm, it seems that GCC is also warning in cases where we're not forwarding the 
format string, for example here:
```c
void forward_tgt(char* tgt) {
va_list va;
const char* fmt;
vsprintf(tgt, fmt, va);
}
```
produces "warning: function 'void forward_tgt(char*)' might be a candidate for 
'gnu_printf' format attribute [-Wsuggest-attribute=format]". But I think that's 
a false positive, and we can easily check for proper forwarding instead.

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

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


[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

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


[clang] [llvm] [NFC][InstrProf] Refactor InstrProfiling lowering pass (PR #74970)

2023-12-10 Thread Mircea Trofin via cfe-commits


@@ -31,31 +31,45 @@ using LoadStorePair = std::pair;
 /// Instrumentation based profiling lowering pass. This pass lowers
 /// the profile instrumented code generated by FE or the IR based
 /// instrumentation pass.
-class InstrProfiling : public PassInfoMixin {
+class InstrProfilingLoweringPass
+: public PassInfoMixin {
+  const InstrProfOptions Options;
+  // Is this lowering for the context-sensitive instrumentation.
+  const bool IsCS;
+
 public:
-  InstrProfiling() : IsCS(false) {}
-  InstrProfiling(const InstrProfOptions &Options, bool IsCS = false)
+  InstrProfilingLoweringPass() : IsCS(false) {}
+  InstrProfilingLoweringPass(const InstrProfOptions &Options, bool IsCS = 
false)
   : Options(Options), IsCS(IsCS) {}
 
   PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
-  bool run(Module &M,
-   std::function GetTLI);
+};
+class InstrProfiling final {

mtrofin wrote:

Done, will move it to the cpp next.

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


[clang] [Clang][LoongArch] Comply with the lp64d ABI to pass vector arguments (PR #74990)

2023-12-10 Thread Lu Weining via cfe-commits

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


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


[clang] [llvm] [NFC][InstrProf] Refactor InstrProfiling lowering pass (PR #74970)

2023-12-10 Thread Mircea Trofin via cfe-commits

https://github.com/mtrofin updated 
https://github.com/llvm/llvm-project/pull/74970

>From 90893a3b3f71524947cb041b2a25d0a02a8956d7 Mon Sep 17 00:00:00 2001
From: Mircea Trofin 
Date: Sat, 9 Dec 2023 21:24:35 -0800
Subject: [PATCH 1/2] [NFC][InstrProf] Refactor InstrProfiling lowering pass

Akin other passes - refactored the name to `InstrProfilingLoweringPass`
to better communicate what it does, and split the pass part and the
transformation part to avoid needing to initialize object state during
`::run`.
---
 clang/lib/CodeGen/BackendUtil.cpp |   2 +-
 .../include/llvm/Transforms/Instrumentation.h |   3 +-
 .../Instrumentation/InstrProfiling.h  |  45 ---
 llvm/lib/Passes/PassBuilderPipelines.cpp  |   4 +-
 llvm/lib/Passes/PassRegistry.def  |   2 +-
 .../Instrumentation/InstrProfiling.cpp| 126 --
 .../Instrumentation/Instrumentation.cpp   |   2 +-
 7 files changed, 94 insertions(+), 90 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 8c666e2cb463c6..77455c075cab0d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -982,7 +982,7 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 getInstrProfOptions(CodeGenOpts, LangOpts))
   PB.registerPipelineStartEPCallback(
   [Options](ModulePassManager &MPM, OptimizationLevel Level) {
-MPM.addPass(InstrProfiling(*Options, false));
+MPM.addPass(InstrProfilingLoweringPass(*Options, false));
   });
 
 // TODO: Consider passing the MemoryProfileOutput to the pass builder via
diff --git a/llvm/include/llvm/Transforms/Instrumentation.h 
b/llvm/include/llvm/Transforms/Instrumentation.h
index bb1a0d446aa2ab..ea97ab2562a5b0 100644
--- a/llvm/include/llvm/Transforms/Instrumentation.h
+++ b/llvm/include/llvm/Transforms/Instrumentation.h
@@ -52,7 +52,8 @@ Comdat *getOrCreateFunctionComdat(Function &F, Triple &T);
 // Place global in a large section for x86-64 ELF binaries to mitigate
 // relocation overflow pressure. This can be be used for metadata globals that
 // aren't directly accessed by code, which has no performance impact.
-void setGlobalVariableLargeSection(Triple &TargetTriple, GlobalVariable &GV);
+void setGlobalVariableLargeSection(const Triple &TargetTriple,
+   GlobalVariable &GV);
 
 // Insert GCOV profiling instrumentation
 struct GCOVOptions {
diff --git a/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h 
b/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h
index c106e1651e8045..0d778288d78455 100644
--- a/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h
+++ b/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h
@@ -31,31 +31,45 @@ using LoadStorePair = std::pair;
 /// Instrumentation based profiling lowering pass. This pass lowers
 /// the profile instrumented code generated by FE or the IR based
 /// instrumentation pass.
-class InstrProfiling : public PassInfoMixin {
+class InstrProfilingLoweringPass
+: public PassInfoMixin {
+  const InstrProfOptions Options;
+  // Is this lowering for the context-sensitive instrumentation.
+  const bool IsCS;
+
 public:
-  InstrProfiling() : IsCS(false) {}
-  InstrProfiling(const InstrProfOptions &Options, bool IsCS = false)
+  InstrProfilingLoweringPass() : IsCS(false) {}
+  InstrProfilingLoweringPass(const InstrProfOptions &Options, bool IsCS = 
false)
   : Options(Options), IsCS(IsCS) {}
 
   PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
-  bool run(Module &M,
-   std::function GetTLI);
+};
+class InstrProfiling final {
+public:
+  InstrProfiling(Module &M, const InstrProfOptions &Options,
+ std::function GetTLI,
+ bool IsCS)
+  : M(M), Options(Options), TT(Triple(M.getTargetTriple())), IsCS(IsCS),
+GetTLI(GetTLI) {}
+
+  bool lower();
 
 private:
-  InstrProfOptions Options;
-  Module *M;
-  Triple TT;
+  Module &M;
+  const InstrProfOptions Options;
+  const Triple TT;
+  // Is this lowering for the context-sensitive instrumentation.
+  const bool IsCS;
+
   std::function GetTLI;
   struct PerFunctionProfileData {
-uint32_t NumValueSites[IPVK_Last + 1];
+uint32_t NumValueSites[IPVK_Last + 1] = {};
 GlobalVariable *RegionCounters = nullptr;
 GlobalVariable *DataVar = nullptr;
 GlobalVariable *RegionBitmaps = nullptr;
 uint32_t NumBitmapBytes = 0;
 
-PerFunctionProfileData() {
-  memset(NumValueSites, 0, sizeof(uint32_t) * (IPVK_Last + 1));
-}
+PerFunctionProfileData() = default;
   };
   DenseMap ProfileDataMap;
   /// If runtime relocation is enabled, this maps functions to the load
@@ -64,11 +78,8 @@ class InstrProfiling : public PassInfoMixin {
   std::vector CompilerUsedVars;
   std::vector UsedVars;
   std::vector ReferencedNames;
-  GlobalVariable *NamesVar;
-  size_t NamesSize;
-
-  // Is this lowering

[clang] [Clang][Sema] Check the number of lambda non-concept tempate parameters (PR #74885)

2023-12-10 Thread via cfe-commits

knightXun wrote:

> This needs at least one test and a Release note.
> 
> I expect the code form the issue to be well-formed: 
> https://godbolt.org/z/bhdfG34xc
> 
> So I am curious why you are adding the diagnostic for?

thanks for the hit! 

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2023-12-10 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

@sam-mccall ping!

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


[clang] 1d608fc - [NFC][InstrProf] Refactor InstrProfiling lowering pass (#74970)

2023-12-10 Thread via cfe-commits

Author: Mircea Trofin
Date: 2023-12-10T18:03:08-08:00
New Revision: 1d608fc755a3e15d0020f61c9535c9b730ab9dec

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

LOG: [NFC][InstrProf] Refactor InstrProfiling lowering pass (#74970)

Akin other passes - refactored the name to `InstrProfilingLoweringPass` to 
better communicate what it does, and split the pass part and the transformation 
part to avoid needing to initialize object state during `::run`.

A subsequent PR will move `InstrLowering` to the .cpp file and rename it to 
`InstrLowerer`.

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/pgo-instrumentation.c
llvm/include/llvm/Transforms/Instrumentation.h
llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h
llvm/lib/Passes/PassBuilderPipelines.cpp
llvm/lib/Passes/PassRegistry.def
llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
llvm/lib/Transforms/Instrumentation/Instrumentation.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 8c666e2cb463c6..77455c075cab0d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -982,7 +982,7 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 getInstrProfOptions(CodeGenOpts, LangOpts))
   PB.registerPipelineStartEPCallback(
   [Options](ModulePassManager &MPM, OptimizationLevel Level) {
-MPM.addPass(InstrProfiling(*Options, false));
+MPM.addPass(InstrProfilingLoweringPass(*Options, false));
   });
 
 // TODO: Consider passing the MemoryProfileOutput to the pass builder via

diff  --git a/clang/test/CodeGen/pgo-instrumentation.c 
b/clang/test/CodeGen/pgo-instrumentation.c
index a65c6712291bd2..c01658065497e3 100644
--- a/clang/test/CodeGen/pgo-instrumentation.c
+++ b/clang/test/CodeGen/pgo-instrumentation.c
@@ -3,7 +3,7 @@
 // Ensure Pass PGOInstrumentationGenPass is invoked.
 // RUN: %clang_cc1 -O2 -fprofile-instrument=llvm %s  -fdebug-pass-manager 
-emit-llvm -o - 2>&1 | FileCheck %s 
-check-prefix=CHECK-PGOGENPASS-INVOKED-INSTR-GEN --check-prefix=CHECK-INSTRPROF
 // CHECK-PGOGENPASS-INVOKED-INSTR-GEN: Running pass: PGOInstrumentationGen on
-// CHECK-INSTRPROF: Running pass: InstrProfiling on
+// CHECK-INSTRPROF: Running pass: InstrProfilingLoweringPass on
 //
 // Ensure Pass PGOInstrumentationGenPass is not invoked.
 // RUN: %clang_cc1 -O2 -fprofile-instrument=clang %s -fdebug-pass-manager 
-emit-llvm -o - 2>&1 | FileCheck %s 
-check-prefix=CHECK-PGOGENPASS-INVOKED-INSTR-GEN-CLANG
@@ -11,7 +11,7 @@
 
 // RUN: %clang_cc1 -O2 -fprofile-instrument=clang %s -fdebug-pass-manager 
-emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-CLANG-INSTRPROF
 // RUN: %clang_cc1 -O0 -fprofile-instrument=clang %s -fdebug-pass-manager 
-emit-llvm -o - 2>&1 | FileCheck %s --check-prefix=CHECK-CLANG-INSTRPROF
-// CHECK-CLANG-INSTRPROF: Running pass: InstrProfiling on
+// CHECK-CLANG-INSTRPROF: Running pass: InstrProfilingLoweringPass on
 
 // Ensure Pass PGOInstrumentationUsePass is invoked.
 // RUN: llvm-profdata merge -o %t.profdata %S/Inputs/pgotestir.profraw

diff  --git a/llvm/include/llvm/Transforms/Instrumentation.h 
b/llvm/include/llvm/Transforms/Instrumentation.h
index bb1a0d446aa2ab..ea97ab2562a5b0 100644
--- a/llvm/include/llvm/Transforms/Instrumentation.h
+++ b/llvm/include/llvm/Transforms/Instrumentation.h
@@ -52,7 +52,8 @@ Comdat *getOrCreateFunctionComdat(Function &F, Triple &T);
 // Place global in a large section for x86-64 ELF binaries to mitigate
 // relocation overflow pressure. This can be be used for metadata globals that
 // aren't directly accessed by code, which has no performance impact.
-void setGlobalVariableLargeSection(Triple &TargetTriple, GlobalVariable &GV);
+void setGlobalVariableLargeSection(const Triple &TargetTriple,
+   GlobalVariable &GV);
 
 // Insert GCOV profiling instrumentation
 struct GCOVOptions {

diff  --git a/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h 
b/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h
index c106e1651e8045..89fa08685692b7 100644
--- a/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h
+++ b/llvm/include/llvm/Transforms/Instrumentation/InstrProfiling.h
@@ -31,31 +31,46 @@ using LoadStorePair = std::pair;
 /// Instrumentation based profiling lowering pass. This pass lowers
 /// the profile instrumented code generated by FE or the IR based
 /// instrumentation pass.
-class InstrProfiling : public PassInfoMixin {
+class InstrProfilingLoweringPass
+: public PassInfoMixin {
+  const InstrProfOptions Options;
+  // Is this lowering for the context-sensitive instrumentation.
+  const bool IsCS = false;

[llvm] [clang] [NFC][InstrProf] Refactor InstrProfiling lowering pass (PR #74970)

2023-12-10 Thread Mircea Trofin via cfe-commits

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


[clang] 9406ea3 - [NFC] [Serialization] Packing more bits

2023-12-10 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2023-12-11T10:18:12+08:00
New Revision: 9406ea3fe32e59a7d28de0dcbd0317b4cdfa4c62

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

LOG: [NFC] [Serialization] Packing more bits

This patch tries to reduce the size of the BMIs by packing more bits
into an unsigned integer.

Added: 


Modified: 
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterDecl.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/test/Modules/decl-params-determinisim.m

Removed: 




diff  --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index bc16cfc67a24f9..7140a14aefbf9b 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -583,6 +583,9 @@ void ASTDeclReader::Visit(Decl *D) {
 }
 
 void ASTDeclReader::VisitDecl(Decl *D) {
+  BitsUnpacker DeclBits(Record.readInt());
+  bool HasStandaloneLexicalDC = DeclBits.getNextBit();
+
   if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
   isa(D)) {
 // We don't want to deserialize the DeclContext of a template
@@ -592,7 +595,8 @@ void ASTDeclReader::VisitDecl(Decl *D) {
 // return type of the function).  Use the translation unit DeclContext as a
 // placeholder.
 GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();
-GlobalDeclID LexicalDCIDForTemplateParmDecl = readDeclID();
+GlobalDeclID LexicalDCIDForTemplateParmDecl =
+HasStandaloneLexicalDC ? readDeclID() : 0;
 if (!LexicalDCIDForTemplateParmDecl)
   LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
 Reader.addPendingDeclContextInfo(D,
@@ -601,7 +605,8 @@ void ASTDeclReader::VisitDecl(Decl *D) {
 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
   } else {
 auto *SemaDC = readDeclAs();
-auto *LexicalDC = readDeclAs();
+auto *LexicalDC =
+HasStandaloneLexicalDC ? readDeclAs() : nullptr;
 if (!LexicalDC)
   LexicalDC = SemaDC;
 // If the context is a class, we might not have actually merged it yet, in
@@ -618,7 +623,6 @@ void ASTDeclReader::VisitDecl(Decl *D) {
   }
   D->setLocation(ThisDeclLoc);
 
-  BitsUnpacker DeclBits(Record.readInt());
   D->InvalidDecl = DeclBits.getNextBit();
   bool HasAttrs = DeclBits.getNextBit();
   D->setImplicit(DeclBits.getNextBit());
@@ -765,7 +769,7 @@ ASTDeclReader::RedeclarableResult 
ASTDeclReader::VisitTagDecl(TagDecl *TD) {
   TD->setCompleteDefinitionRequired(TagDeclBits.getNextBit());
   TD->setBraceRange(readSourceRange());
 
-  switch (Record.readInt()) {
+  switch (TagDeclBits.getNextBits(/*Width=*/2)) {
   case 0:
 break;
   case 1: { // ExtInfo
@@ -1089,7 +1093,8 @@ void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
   FD->setCachedLinkage((Linkage)FunctionDeclBits.getNextBits(/*Width=*/3));
 
   FD->EndRangeLoc = readSourceLocation();
-  FD->setDefaultLoc(readSourceLocation());
+  if (FD->isExplicitlyDefaulted())
+FD->setDefaultLoc(readSourceLocation());
 
   FD->ODRHash = Record.readInt();
   FD->setHasODRHash(true);
@@ -1703,7 +1708,7 @@ void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
   unsigned isObjCMethodParam = ParmVarDeclBits.getNextBit();
   unsigned scopeDepth = ParmVarDeclBits.getNextBits(/*Width=*/7);
   unsigned scopeIndex = ParmVarDeclBits.getNextBits(/*Width=*/8);
-  unsigned declQualifier = Record.readInt();
+  unsigned declQualifier = ParmVarDeclBits.getNextBits(/*Width=*/7);
   if (isObjCMethodParam) {
 assert(scopeDepth == 0);
 PD->setObjCMethodScopeInfo(scopeIndex);
@@ -1716,7 +1721,9 @@ void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
   PD->ParmVarDeclBits.HasInheritedDefaultArg = ParmVarDeclBits.getNextBit();
   if (ParmVarDeclBits.getNextBit()) // hasUninstantiatedDefaultArg.
 PD->setUninstantiatedDefaultArg(Record.readExpr());
-  PD->ExplicitObjectParameterIntroducerLoc = Record.readSourceLocation();
+
+  if (ParmVarDeclBits.getNextBit()) // Valid explicit object parameter
+PD->ExplicitObjectParameterIntroducerLoc = Record.readSourceLocation();
 
   // FIXME: If this is a redeclaration of a function from another module, 
handle
   // inheritance of default arguments.

diff  --git a/clang/lib/Serialization/ASTReaderStmt.cpp 
b/clang/lib/Serialization/ASTReaderStmt.cpp
index d7d0c0e5bb21b4..865322ec0782cd 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -108,7 +108,7 @@ namespace clang {
 
 /// The number of record fields required for the Expr class
 /// itself.
-static const unsigned NumExprFields = NumStmtFields + 4;
+static const unsigned NumExprFields = NumStmtFields + 2;
 
 /// Read and init

[clang] 1095105 - [clang] Remove unused variable 'ExprDependenceBits' in ASTWriterDecl.cpp (NFC)

2023-12-10 Thread Jie Fu via cfe-commits

Author: Jie Fu
Date: 2023-12-11T10:45:56+08:00
New Revision: 10951050b5f371eb3e7cacce1691c4eb2fe2eab5

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

LOG: [clang] Remove unused variable 'ExprDependenceBits' in ASTWriterDecl.cpp 
(NFC)

llvm-project/clang/lib/Serialization/ASTWriterDecl.cpp:2342:12:
 error: unused variable 'ExprDependenceBits' [-Werror,-Wunused-variable]
 2342 |   unsigned ExprDependenceBits = llvm::BitWidth;
  |^~
1 error generated.

Added: 


Modified: 
clang/lib/Serialization/ASTWriterDecl.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTWriterDecl.cpp 
b/clang/lib/Serialization/ASTWriterDecl.cpp
index a5035d5002818..43169b2befc68 100644
--- a/clang/lib/Serialization/ASTWriterDecl.cpp
+++ b/clang/lib/Serialization/ASTWriterDecl.cpp
@@ -2339,7 +2339,6 @@ void ASTWriter::WriteDeclAbbrevs() {
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
   DeclCXXMethodAbbrev = Stream.EmitAbbrev(std::move(Abv));
 
-  unsigned ExprDependenceBits = llvm::BitWidth;
   // Abbreviation for EXPR_DECL_REF
   Abv = std::make_shared();
   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_DECL_REF));



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


[clang-tools-extra] [clang] [mlir] [llvm] Generalize depthwise conv (PR #75017)

2023-12-10 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 10951050b5f371eb3e7cacce1691c4eb2fe2eab5 
1ccaf0d034d73145ddfa9e3265f856950628a7f7 -- 
mlir/include/mlir/Dialect/Linalg/IR/LinalgInterfaces.h 
mlir/lib/Dialect/Linalg/IR/LinalgInterfaces.cpp 
mlir/lib/Dialect/Linalg/IR/LinalgOps.cpp
``





View the diff from clang-format here.


``diff
diff --git a/mlir/include/mlir/Dialect/Linalg/IR/LinalgInterfaces.h 
b/mlir/include/mlir/Dialect/Linalg/IR/LinalgInterfaces.h
index 2b73bd80d2..3104d0670c 100644
--- a/mlir/include/mlir/Dialect/Linalg/IR/LinalgInterfaces.h
+++ b/mlir/include/mlir/Dialect/Linalg/IR/LinalgInterfaces.h
@@ -130,12 +130,13 @@ ArrayAttr 
getIteratorTypes(DepthwiseConvolutionOpInterface op);
 void regionBuilder(ImplicitLocOpBuilder &b, Block &block,
ArrayRef attrs);
 void quantizedRegionBuilder(ImplicitLocOpBuilder &b, Block &block,
-   ArrayRef attrs);
+ArrayRef attrs);
 void getEffects(
 DepthwiseConvolutionOpInterface op,
 SmallVectorImpl>
 &effects);
-ParseResult parse(OpAsmParser &parser, OperationState &result, bool 
isQuantized = false);
+ParseResult parse(OpAsmParser &parser, OperationState &result,
+  bool isQuantized = false);
 void print(DepthwiseConvolutionOpInterface op, OpAsmPrinter &p);
 } // namespace depthwise_convolution_impl
 

``




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


[clang-tools-extra] [clangd] Initialize HighlightingsBuilder::Resolver (PR #74971)

2023-12-10 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 updated 
https://github.com/llvm/llvm-project/pull/74971

>From 86d99f7b29a131b949b32f18ff15eb1d1f5e4d3a Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 10 Dec 2023 00:50:54 -0500
Subject: [PATCH] [clangd] Initialize HighlightingsBuilder::Resolver

---
 clang-tools-extra/clangd/SemanticHighlighting.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 49e479abf45621..37939d36425a97 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -418,7 +418,8 @@ class HighlightingsBuilder {
 public:
   HighlightingsBuilder(const ParsedAST &AST, const HighlightingFilter &Filter)
   : TB(AST.getTokens()), SourceMgr(AST.getSourceManager()),
-LangOpts(AST.getLangOpts()), Filter(Filter) {}
+LangOpts(AST.getLangOpts()), Filter(Filter),
+Resolver(AST.getHeuristicResolver()) {}
 
   HighlightingToken &addToken(SourceLocation Loc, HighlightingKind Kind) {
 auto Range = getRangeForSourceLocation(Loc);
@@ -589,7 +590,7 @@ class HighlightingsBuilder {
   HighlightingFilter Filter;
   std::vector Tokens;
   std::map> ExtraModifiers;
-  const HeuristicResolver *Resolver = nullptr;
+  const HeuristicResolver *Resolver;
   // returned from addToken(InvalidLoc)
   HighlightingToken InvalidHighlightingToken;
 };

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


[clang-tools-extra] [clangd] Initialize HighlightingsBuilder::Resolver (PR #74971)

2023-12-10 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] 9d3ea5a - [clangd] Initialize HighlightingsBuilder::Resolver (#74971)

2023-12-10 Thread via cfe-commits

Author: Nathan Ridge
Date: 2023-12-10T22:05:51-05:00
New Revision: 9d3ea5a06abe08fa37053b825b3a1510d96bb7fb

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

LOG: [clangd] Initialize HighlightingsBuilder::Resolver (#74971)

Added: 


Modified: 
clang-tools-extra/clangd/SemanticHighlighting.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 49e479abf45621..37939d36425a97 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -418,7 +418,8 @@ class HighlightingsBuilder {
 public:
   HighlightingsBuilder(const ParsedAST &AST, const HighlightingFilter &Filter)
   : TB(AST.getTokens()), SourceMgr(AST.getSourceManager()),
-LangOpts(AST.getLangOpts()), Filter(Filter) {}
+LangOpts(AST.getLangOpts()), Filter(Filter),
+Resolver(AST.getHeuristicResolver()) {}
 
   HighlightingToken &addToken(SourceLocation Loc, HighlightingKind Kind) {
 auto Range = getRangeForSourceLocation(Loc);
@@ -589,7 +590,7 @@ class HighlightingsBuilder {
   HighlightingFilter Filter;
   std::vector Tokens;
   std::map> ExtraModifiers;
-  const HeuristicResolver *Resolver = nullptr;
+  const HeuristicResolver *Resolver;
   // returned from addToken(InvalidLoc)
   HighlightingToken InvalidHighlightingToken;
 };



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


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

2023-12-10 Thread Elvis Wang via cfe-commits

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

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

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

- If option `-fdiagnostics-show-profile-count` is set we will append the 
`MD_prof_count` metadata at the branch instruction at the header of loops.
- Show the profile count like hotness with remark. For example:
```
  remark: the cost-model indicates that interleaving is not beneficial
  (ProfileCount: 20) [-Rpass-analysis=loop-vectorize]
  38 |   for(int i = 0;  i < argc % 20; i++){
 |   ^
```

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

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

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

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

diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index f1b344ef5109b..59e2bdbd02500 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -425,6 +425,33 @@ output format of the diagnostics that it generates.
If this option is not used, all the passes are included in the optimization
record.
 
+.. option:: -fdiagnostics-show-profile-count
+
+   Enable profile loop count information in diagnostic line.
+
+   This option controls whether Clang prints the profile loop count associated
+   with diagnostics in the presence of profile-guided optimization information.
+   This is currently supported with optimization remarks (see
+   :ref:`Options to Emit Optimization Reports `). The profile count 
information
+   allows users to focus on the hot optimization remarks that are likely to be
+   more relevant for run-time performance. The main difference between profile 
count
+   the hotness is the profile count is the real profile count from the runtime
+   profile 

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

2023-12-10 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-llvm-ir

Author: Elvis Wang (ElvisWang123)


Changes

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

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

- If option `-fdiagnostics-show-profile-count` is set we will append the 
`MD_prof_count` metadata at the branch instruction at the header of loops.
- Show the profile count like hotness with remark. For example:
```
  remark: the cost-model indicates that interleaving is not beneficial
  (ProfileCount: 20) [-Rpass-analysis=loop-vectorize]
  38 |   for(int i = 0;  i < argc % 20; i++){
 |   ^
```

---

Patch is 25.56 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/75021.diff


24 Files Affected:

- (modified) clang/docs/UsersManual.rst (+27) 
- (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+3) 
- (modified) clang/include/clang/Driver/Options.td (+3) 
- (modified) clang/lib/CodeGen/CGStmt.cpp (+23-4) 
- (modified) clang/lib/CodeGen/CodeGenAction.cpp (+4) 
- (modified) clang/lib/CodeGen/CodeGenFunction.h (+1) 
- (modified) clang/lib/CodeGen/CodeGenPGO.cpp (+12) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+5) 
- (modified) clang/lib/Frontend/CompilerInvocation.cpp (+6) 
- (added) 
clang/test/Frontend/Inputs/optimization-remark-with-profile-count.proftext (+9) 
- (added) clang/test/Frontend/optimization-remark-with-profile-count-new-pm.c 
(+41) 
- (added) clang/test/Profile/Inputs/c-profile-count-metadata.proftext (+32) 
- (added) clang/test/Profile/c-profile-count-metadata.c (+73) 
- (modified) llvm/docs/LangRef.rst (+22) 
- (modified) llvm/include/llvm/Analysis/OptimizationRemarkEmitter.h (+7) 
- (modified) llvm/include/llvm/IR/DiagnosticInfo.h (+6) 
- (modified) llvm/include/llvm/IR/FixedMetadataKinds.def (+1) 
- (modified) llvm/include/llvm/IR/MDBuilder.h (+3) 
- (modified) llvm/include/llvm/Remarks/Remark.h (+4) 
- (modified) llvm/lib/Analysis/OptimizationRemarkEmitter.cpp (+22) 
- (modified) llvm/lib/IR/LLVMRemarkStreamer.cpp (+1) 
- (modified) llvm/lib/IR/MDBuilder.cpp (+10) 
- (modified) llvm/lib/Remarks/Remark.cpp (+2) 
- (modified) llvm/lib/Remarks/YAMLRemarkSerializer.cpp (+5-2) 


``diff
diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index f1b344ef5109b5..59e2bdbd025000 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -425,6 +425,33 @@ output format of the diagnostics that it generates.
If this option is not used, all the passes are included in the optimization
record.
 
+.. option:: -fdiagnostics-show-profile-count
+
+   Enable profile loop count information in diagnostic line.
+
+   This option controls whether Clang prints the profile loop count associated
+   with diagnostics in the presence of profile-guided optimization information.
+   This is currently supported with optimization remarks (see
+   :ref:`Options to Emit Optimization Reports `). The profile count 
information
+   allows users to focus on the hot optimization remarks that are likely to be
+   more relevant for run-time performance. The main difference between profile 
count
+   the hotness is the profile count is the real profile count from the runtime
+   profile and hotness is a relative number calculated by function entry count 
and
+   weight.
+
+   For example, in this output, the block containing the callsite of `foo` was
+   executed 3000 times according to the profile data:
+
+   ::
+
+ s.c:7:10: remark: foo inlined into bar (ProfileCount: 3000) 
[-Rpass-analysis=inline]
+   sum += foo(x, x - 2);
+  ^
+
+   This option is implied when
+   :ref:`-fsave-optimization-record ` is used.
+   Otherwise, it defaults to off.
+
 .. _opt_fdiagnostics-show-hotness:
 
 .. option:: -f[no-]diagnostics-show-hotness
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 676f1a62b49dd0..47ad1e058a1d82 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -420,6 +420,9 @@ def warn_drv_empty_joined_argument : Warning<
 def warn_drv_diagnostics_hotness_requires_pgo : Warning<
   "argument '%0' requires profile-guided optimization information">,
   InGroup;
+def warn_drv_diagnostics_profile_count_requires_pgo : Warning<
+  "argument '%0' requires profile-guided optimization information">,
+  InGroup;
 def warn_drv_diagnostics_misexpect_requires_pgo : Warning<
   "argument '%0' r

[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

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


[clang] [Clang][Sema] Check the number of lambda non-concept tempate parameters (PR #74885)

2023-12-10 Thread via cfe-commits

https://github.com/knightXun updated 
https://github.com/llvm/llvm-project/pull/74885

>From 12cc1fe332fbab94c1368ea95374d5a1289a22f8 Mon Sep 17 00:00:00 2001
From: knightXun 
Date: Sat, 9 Dec 2023 04:57:15 +0800
Subject: [PATCH 01/15] [Clang][Sema] Check the number of lambda non-concept
 tempate parameters Check that the number of non-concept template parameters
 is greater than zero during lambda template instantiation to aviod panic Fix
 issue: https://github.com/llvm/llvm-project/issues/70601

---
 .../include/clang/Basic/DiagnosticParseKinds.td  |  2 ++
 clang/lib/Sema/TreeTransform.h   | 16 
 2 files changed, 18 insertions(+)

diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 6150fc36430ab1..e46fa69d013b61 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -851,6 +851,8 @@ def err_friend_explicit_instantiation : Error<
 def err_explicit_instantiation_enum : Error<
   "enumerations cannot be explicitly instantiated">;
 def err_expected_template_parameter : Error<"expected template parameter">;
+def err_expected_non_concept_template_parameter : Error<
+  "expected non-concept template parameter">;
 def err_empty_requires_expr : Error<
   "a requires expression must contain at least one requirement">;
 def err_requires_expr_parameter_list_ellipsis : Error<
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 1ad843d0bf4e0c..a140bbbc0c43d5 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -13662,6 +13662,22 @@ TreeTransform::TransformLambdaExpr(LambdaExpr 
*E) {
 return ExprError();
   }
 
+  // Check the number of the Concept template parameters
+  size_t conceptParams = 0;
+  for (auto P : *E->getTemplateParameterList()) {
+const TemplateTypeParmDecl *CD = dyn_cast(P);
+if (CD && CD->hasTypeConstraint()) {
+  conceptParams++;
+}
+  }
+
+  if (conceptParams > 0 &&
+  conceptParams == E->getTemplateParameterList()->size()) {
+getSema().Diag(E->getTemplateParameterList()->getLAngleLoc(),
+   diag::err_expected_non_concept_template_parameter);
+return ExprError();
+  }
+
   // Copy the LSI before ActOnFinishFunctionBody removes it.
   // FIXME: This is dumb. Store the lambda information somewhere that outlives
   // the call operator.

>From e53ed4531d6918384be40de2b76bea558eac06ea Mon Sep 17 00:00:00 2001
From: knightXun 
Date: Sat, 9 Dec 2023 08:38:23 +0800
Subject: [PATCH 02/15] fix ut

---
 clang/lib/Sema/TreeTransform.h | 34 ++
 1 file changed, 18 insertions(+), 16 deletions(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index a140bbbc0c43d5..9fb426c1a044b9 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -13594,6 +13594,24 @@ TreeTransform::TransformLambdaExpr(LambdaExpr 
*E) {
 getSema().AddTemplateParametersToLambdaCallOperator(NewCallOperator, Class,
 TPL);
 
+  if (E->getTemplateParameterList()) {
+// Check the number of the Concept template parameters
+size_t conceptParams = 0;
+for (auto P : *E->getTemplateParameterList()) {
+  const TemplateTypeParmDecl *CD = dyn_cast(P);
+  if (CD && CD->hasTypeConstraint()) {
+conceptParams++;
+  }
+}
+
+if (conceptParams > 0 &&
+conceptParams == E->getTemplateParameterList()->size()) {
+  getSema().Diag(E->getTemplateParameterList()->getLAngleLoc(),
+ diag::err_expected_non_concept_template_parameter);
+  return ExprError();
+}
+  }
+
   // Transform the type of the original lambda's call operator.
   // The transformation MUST be done in the CurrentInstantiationScope since
   // it introduces a mapping of the original to the newly created
@@ -13662,22 +13680,6 @@ TreeTransform::TransformLambdaExpr(LambdaExpr 
*E) {
 return ExprError();
   }
 
-  // Check the number of the Concept template parameters
-  size_t conceptParams = 0;
-  for (auto P : *E->getTemplateParameterList()) {
-const TemplateTypeParmDecl *CD = dyn_cast(P);
-if (CD && CD->hasTypeConstraint()) {
-  conceptParams++;
-}
-  }
-
-  if (conceptParams > 0 &&
-  conceptParams == E->getTemplateParameterList()->size()) {
-getSema().Diag(E->getTemplateParameterList()->getLAngleLoc(),
-   diag::err_expected_non_concept_template_parameter);
-return ExprError();
-  }
-
   // Copy the LSI before ActOnFinishFunctionBody removes it.
   // FIXME: This is dumb. Store the lambda information somewhere that outlives
   // the call operator.

>From 7d2c8743d1e28342e3e6ac44424d789bba4e698b Mon Sep 17 00:00:00 2001
From: knightXun 
Date: Sat, 9 Dec 2023 21:40:36 +0800
Subject: [PATCH 03/15] fx

---
 clang/include/clang/Basic/DiagnosticParseKinds.td

[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-10 Thread via cfe-commits

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


  1   2   >