[clang] [AArch64] Add getHostCPUFeatures to query for enabled features in cpu… (PR #97749)

2024-07-05 Thread David Green via cfe-commits

davemgreen wrote:

Hi this sounds like a good idea to me. Note that the implementation of 
getHostCPUFeatures isn't amazing for AArch64 at the moment, there was an 
attempt to fix it up in #95694 (but thaat has gone a bit quiet). One point we 
noticed is that it could end up turning "aes+sha2" into "crypto" and "crypto" 
back into "sha2+aes+sha3+sm4", as it uses the old meaning of "crypto"

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


[clang] [compiler-rt] [llvm] [CMake] Use Clang to infer the target triple (PR #89425)

2024-07-05 Thread YunQiang Su via cfe-commits


@@ -368,14 +368,22 @@ macro(construct_compiler_rt_default_triple)
   "Default triple for which compiler-rt runtimes will be built.")
   endif()
 
-  if ("${CMAKE_C_COMPILER_ID}" MATCHES "Clang")
+  if(CMAKE_C_COMPILER_ID MATCHES "Clang")
 set(option_prefix "")
 if (CMAKE_C_SIMULATE_ID MATCHES "MSVC")
   set(option_prefix "/clang:")
 endif()
-execute_process(COMMAND ${CMAKE_C_COMPILER} 
${option_prefix}--target=${COMPILER_RT_DEFAULT_TARGET_TRIPLE} 
${option_prefix}-print-target-triple
-OUTPUT_VARIABLE COMPILER_RT_DEFAULT_TARGET_TRIPLE
-OUTPUT_STRIP_TRAILING_WHITESPACE)
+set(print_target_triple ${CMAKE_C_COMPILER} 
${option_prefix}--target=${COMPILER_RT_DEFAULT_TARGET_TRIPLE} 
${option_prefix}-print-target-triple)
+execute_process(COMMAND ${print_target_triple}
+  RESULT_VARIABLE result
+  OUTPUT_VARIABLE output
+  OUTPUT_STRIP_TRAILING_WHITESPACE)
+if(result EQUAL 0)
+  set(COMPILER_RT_DEFAULT_TARGET_TRIPLE ${output})
+else()
+  string(REPLACE ";" " " print_target_triple "${print_target_triple}")
+  message(WARNING "Failed to execute `${print_target_triple}` to normalize 
target triple.")

wzssyqa wrote:

Maybe you are right.  I tested with some quite bad --target values, it will 
output the original values.
So, I think that it will be safe.  Anyway, a warning is OK for me as I think 
that it won't be used at all. 

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


[clang] [compiler-rt] [llvm] [CMake] Use Clang to infer the target triple (PR #89425)

2024-07-05 Thread YunQiang Su via cfe-commits


@@ -183,6 +183,24 @@ message(STATUS "LLVM default target triple: 
${LLVM_DEFAULT_TARGET_TRIPLE}")
 
 set(LLVM_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}")
 
+if(CMAKE_C_COMPILER_ID MATCHES "Clang")
+  set(option_prefix "")
+  if (CMAKE_C_SIMULATE_ID MATCHES "MSVC")
+set(option_prefix "/clang:")
+  endif()
+  set(print_target_triple ${CMAKE_C_COMPILER} 
${option_prefix}--target=${LLVM_DEFAULT_TARGET_TRIPLE} 
${option_prefix}-print-target-triple)
+  execute_process(COMMAND ${print_target_triple}
+RESULT_VARIABLE result
+OUTPUT_VARIABLE output
+OUTPUT_STRIP_TRAILING_WHITESPACE)
+  if(result EQUAL 0)
+set(LLVM_DEFAULT_TARGET_TRIPLE ${output})
+  else()
+string(REPLACE ";" " " print_target_triple "${print_target_triple}")

wzssyqa wrote:

Since most of the CIs monitor the commit only. I have no idea how to trigger 
them before commit.

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


[clang] [flang] [Flang-new][OpenMP] Add bitcode files for AMD GPU OpenMP (PR #96742)

2024-07-05 Thread Andrzej Warzyński via cfe-commits

banach-space wrote:

> Would it be possible for you to investigate that? It really shouldn't be 
> required if we can't help it.

+1

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


[clang] [compiler-rt] [llvm] [CMake] Use Clang to infer the target triple (PR #89425)

2024-07-05 Thread YunQiang Su via cfe-commits

wzssyqa wrote:

> @wzssyqa Is it OK with you if I go ahead and merge this PR? I plan to follow 
> up with further improvements but this is necessary to fix the build of LLVM 
> runtime libraries in the bootstrapping build.

It is OK for me, while I have no permission to approve such a patch.

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


[clang] [flang] [Flang-new][OpenMP] Add bitcode files for AMD GPU OpenMP (PR #96742)

2024-07-05 Thread Andrzej Warzyński via cfe-commits


@@ -8024,7 +8024,7 @@ def source_date_epoch : Separate<["-"], 
"source-date-epoch">,
 // CUDA Options
 
//===--===//
 
-let Visibility = [CC1Option] in {
+let Visibility = [CC1Option, FC1Option] in {

banach-space wrote:

This enables 4 CUDA flags in `flang-new -fc1` - this really shouldn't be needed 
in this PR. I would expect that AMD GPU and CUDA logic to be orthogonal. If 
that's not the case, then lets try to either fix or at document that.

I appreciate that some sub-optimal behaviour might be inherited from Clang. In 
such cases, lets try to:
1.  Understand what's going on.
2. If a path towards a fix is clear, lets just fix it.
3. If there's no easy fix, lets document this with a GitHub issue and add a 
link in the commit/code.

Thanks!

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


[clang] [flang] [Flang-new][OpenMP] Add bitcode files for AMD GPU OpenMP (PR #96742)

2024-07-05 Thread Andrzej Warzyński via cfe-commits


@@ -333,6 +333,9 @@ void Flang::AddAMDGPUTargetArgs(const ArgList &Args,
 StringRef Val = A->getValue();
 CmdArgs.push_back(Args.MakeArgString("-mcode-object-version=" + Val));
   }
+
+  const ToolChain &TC = getToolChain();
+  TC.addClangTargetOptions(Args, CmdArgs, Action::OffloadKind::OFK_OpenMP);

banach-space wrote:

> Shall I extend https://github.com/llvm/llvm-project/pull/94763 ?

Yes, please.

> Who could be the right person to ask?
> > I don't know. Open-source LLVM Flang meetings can be good place to ask this 
> > question.

Did you ask? What feedback did you get?

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


[clang] [AArch64] Add getHostCPUFeatures to query for enabled features in cpu… (PR #97749)

2024-07-05 Thread via cfe-commits

neildhickey wrote:

Thanks for the review comments @madhur13490 and @davemgreen I plan to improve 
getHostCPUFeatures for AArach64 as well, this is just the first phase to add 
the function call.

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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

https://github.com/PiotrZSL commented:

Few nits. Mainly documentation require some love.

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,253 @@
+//===--- UseRangesCheck.cpp - clang-tidy 
--===//
+//
+// 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 "UseRangesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallBitVector.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+static constexpr const char BoundCall[] = "CallExpr";
+static constexpr const char FuncDecl[] = "FuncDecl";
+static constexpr const char ArgName[] = "ArgName";
+
+namespace clang::tidy::utils {
+
+static bool operator==(const UseRangesCheck::Replacer::Indexes &L,
+   const UseRangesCheck::Replacer::Indexes &R) {
+  return std::tie(L.BeginArg, L.EndArg, L.ReplaceArg) ==
+ std::tie(R.BeginArg, R.EndArg, R.ReplaceArg);
+}
+
+std::string
+getFullPrefix(ArrayRef Signature) {
+  std::string Output;
+  llvm::raw_string_ostream OS(Output);
+  for (auto Item : Signature) {
+OS << Item.BeginArg << ":" << Item.EndArg << ":"
+   << (Item.ReplaceArg == Item.First ? '0' : '1');
+  }
+  return Output;
+}
+
+static llvm::hash_code hash_value(const UseRangesCheck::Replacer::Indexes &L) {
+  return llvm::hash_combine(L.BeginArg, L.EndArg, L.ReplaceArg);
+}
+
+namespace {
+
+AST_MATCHER(Expr, hasSideEffects) {
+  return Node.HasSideEffects(Finder->getASTContext());
+}
+
+AST_MATCHER_P(Expr, isEquivalentToBound, std::string, Other) {

PiotrZSL wrote:

there is already something similar: 
clang::tidy::matchers::isStatementIdenticalToBoundNode, but that one by default 
pass false as Canonical

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,24 @@
+.. title:: clang-tidy - boost-use-ranges
+
+boost-use-ranges
+
+
+Detects calls to standard library iterator algorithms that could be replaced
+with a ranges version instead

PiotrZSL wrote:

Nit: '.' after instead

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,171 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t
+
+// CHECK-FIXES: #include 
+
+namespace std {
+
+template  class vector {
+public:
+  using iterator = T *;
+  using const_iterator = const T *;
+  constexpr const_iterator begin() const;
+  constexpr const_iterator end() const;
+  constexpr const_iterator cbegin() const;
+  constexpr const_iterator cend() const;
+  constexpr iterator begin();
+  constexpr iterator end();
+};
+
+template  constexpr auto begin(const Container &Cont) {
+  return Cont.begin();
+}
+
+template  constexpr auto begin(Container &Cont) {
+  return Cont.begin();
+}
+
+template  constexpr auto end(const Container &Cont) {
+  return Cont.end();
+}
+
+template  constexpr auto end(Container &Cont) {
+  return Cont.end();
+}
+
+template  constexpr auto cbegin(const Container &Cont) {
+  return Cont.cbegin();
+}
+
+template  constexpr auto cend(const Container &Cont) {
+  return Cont.cend();
+}
+// Find
+template< class InputIt, class T >
+InputIt find( InputIt first, InputIt last, const T& value );
+
+// Reverse
+template  void reverse(Iter begin, Iter end);
+
+template 
+void reverse(int policy, Iter begin, Iter end);
+
+// Includes
+template 
+bool includes(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 
last2);
+template 
+bool includes(int policy, ForwardIt1 first1, ForwardIt1 last1,
+  ForwardIt2 first2, ForwardIt2 last2);
+
+// IsPermutation
+template 
+bool is_permutation(ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2);
+template 
+bool is_permutation(ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2,
+ForwardIt2 last2);
+
+// Equal
+template 
+bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2);
+
+template 
+bool equal(int policy, ForwardIt1 first1, ForwardIt1 last1,
+   ForwardIt2 first2);
+
+template 
+bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2);
+
+template 
+bool equal(int policy, ForwardIt1 first1, ForwardIt1 last1,
+   ForwardIt2 first2, ForwardIt2 last2);
+} // namespace std
+
+void Positives() {
+  std::vector I, J;
+  std::find(I.begin(), I.end(), 0);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::find(I, 0);
+
+  std::find(I.cbegin(), I.cend(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::find(I, 1);
+
+  std::find(std::begin(I), std::end(I), 2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::find(I, 2);
+
+  std::find(std::cbegin(I), std::cend(I), 3);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::find(I, 3);
+
+  std::find(std::cbegin(I), I.cend(), 4);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::find(I, 4);
+
+  std::reverse(I.begin(), I.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::reverse(I);
+
+  std::reverse(0, I.begin(), I.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::reverse(0, I);
+
+  std::includes(I.begin(), I.end(), I.begin(), I.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::includes(I, I);
+
+  std::includes(I.begin(), I.end(), J.begin(), J.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::includes(I, J);
+
+
+  std::includes(0, I.begin(), I.end(), I.begin(), I.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::includes(0, I, I);
+
+  std::includes(0, I.begin(), I.end(), J.begin(), J.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::includes(0, I, J);
+
+  std::is_permutation(I.begin(), I.end(), J.begin());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::is_permutation(I, J.begin());
+
+  std::is_permutation(I.begin(), I.end(), J.begin(), J.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::is_permutation(I, J);
+
+  std::equal(I.begin(), I.end(), J.begin());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::equal(I, J.begin());
+
+  std::equal(I.begin(), I.end(), J.begin(), J.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use a ranges version of this 
algorithm
+  // CHECK-FIXES: std::ranges::equal(I, J);
+
+  std::equal(0, I.begin(), I.end(), J.b

[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,253 @@
+//===--- UseRangesCheck.cpp - clang-tidy 
--===//
+//
+// 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 "UseRangesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallBitVector.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+static constexpr const char BoundCall[] = "CallExpr";
+static constexpr const char FuncDecl[] = "FuncDecl";
+static constexpr const char ArgName[] = "ArgName";
+
+namespace clang::tidy::utils {
+
+static bool operator==(const UseRangesCheck::Replacer::Indexes &L,
+   const UseRangesCheck::Replacer::Indexes &R) {
+  return std::tie(L.BeginArg, L.EndArg, L.ReplaceArg) ==
+ std::tie(R.BeginArg, R.EndArg, R.ReplaceArg);
+}
+
+std::string
+getFullPrefix(ArrayRef Signature) {
+  std::string Output;
+  llvm::raw_string_ostream OS(Output);
+  for (auto Item : Signature) {
+OS << Item.BeginArg << ":" << Item.EndArg << ":"
+   << (Item.ReplaceArg == Item.First ? '0' : '1');
+  }
+  return Output;
+}
+
+static llvm::hash_code hash_value(const UseRangesCheck::Replacer::Indexes &L) {
+  return llvm::hash_combine(L.BeginArg, L.EndArg, L.ReplaceArg);
+}
+
+namespace {
+
+AST_MATCHER(Expr, hasSideEffects) {
+  return Node.HasSideEffects(Finder->getASTContext());
+}
+
+AST_MATCHER_P(Expr, isEquivalentToBound, std::string, Other) {
+  llvm::FoldingSetNodeID NodeRepr;
+  Node.Profile(NodeRepr, Finder->getASTContext(), true);
+  return Builder->removeBindings(
+  [this, &Finder,
+   &NodeRepr](const ast_matchers::internal::BoundNodesMap &Nodes) {
+auto BoundNode = Nodes.getNodeAs(Other);
+if (!BoundNode)
+  return true;
+llvm::FoldingSetNodeID BoundRepr;
+BoundNode->Profile(BoundRepr, Finder->getASTContext(), true);
+return BoundRepr != NodeRepr;
+  });
+}
+} // namespace
+
+static auto makeMatcher(bool IsBegin, StringRef Prefix) {
+  auto Member =
+  IsBegin ? expr(unless(hasSideEffects())).bind((ArgName + Prefix).str())
+  : expr(isEquivalentToBound((ArgName + Prefix).str()));
+  return expr(
+  anyOf(cxxMemberCallExpr(
+callee(cxxMethodDecl(IsBegin ? hasAnyName("begin", "cbegin")
+ : hasAnyName("end", "cend"))),
+on(Member)),
+callExpr(argumentCountIs(1), hasArgument(0, Member),
+ hasDeclaration(functionDecl(
+ IsBegin ? hasAnyName("::std::begin", "::std::cbegin")
+ : hasAnyName("::std::end", 
"::std::cend"));
+}
+static ast_matchers::internal::Matcher
+makeMatcherPair(StringRef State,
+const UseRangesCheck::Replacer::Indexes &Indexes) {
+  auto ArgPostfix = std::to_string(Indexes.BeginArg);
+  SmallString<64> ID = {BoundCall, State};
+  return callExpr(argumentCountAtLeast(
+  std::max(Indexes.BeginArg, Indexes.EndArg) + 1),
+  hasArgument(Indexes.BeginArg, makeMatcher(true, ArgPostfix)),
+  hasArgument(Indexes.EndArg, makeMatcher(false, ArgPostfix)))
+  .bind(ID);
+}
+
+void UseRangesCheck::registerMatchers(MatchFinder *Finder) {
+  Replaces = GetReplacerMap();
+  llvm::DenseSet>> Seen;
+  for (auto I = Replaces.begin(), E = Replaces.end(); I != E; ++I) {
+const auto &Replacer = I->getValue();
+const auto &Signatures = Replacer->getReplacementSignatures();
+if (Seen.contains(Signatures))
+  continue;
+assert(!Signatures.empty() &&
+   llvm::all_of(Signatures, [](auto index) { return !index.empty(); 
}));
+std::vector Names(1, I->getKey());
+for (auto J = std::next(I); J != E; ++J) {
+  if (J->getValue()->getReplacementSignatures() == Signatures) {
+Names.push_back(J->getKey());
+  }
+}
+std::vector TotalMatchers;
+// As we match on the first matched signature, we need to ensure that any
+SmallVector> SigVec(Signatures);
+llvm::sort(SigVec, [](auto &L, auto &R) { return R.size() < L.size(); });
+for (const auto &Signature : SigVec) {
+  std::vector Matche

[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,253 @@
+//===--- UseRangesCheck.cpp - clang-tidy 
--===//
+//
+// 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 "UseRangesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallBitVector.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+static constexpr const char BoundCall[] = "CallExpr";
+static constexpr const char FuncDecl[] = "FuncDecl";
+static constexpr const char ArgName[] = "ArgName";
+
+namespace clang::tidy::utils {
+
+static bool operator==(const UseRangesCheck::Replacer::Indexes &L,
+   const UseRangesCheck::Replacer::Indexes &R) {
+  return std::tie(L.BeginArg, L.EndArg, L.ReplaceArg) ==
+ std::tie(R.BeginArg, R.EndArg, R.ReplaceArg);
+}
+
+std::string
+getFullPrefix(ArrayRef Signature) {

PiotrZSL wrote:

Nit: static, keep this private

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,253 @@
+//===--- UseRangesCheck.cpp - clang-tidy 
--===//
+//
+// 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 "UseRangesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallBitVector.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+static constexpr const char BoundCall[] = "CallExpr";
+static constexpr const char FuncDecl[] = "FuncDecl";
+static constexpr const char ArgName[] = "ArgName";
+
+namespace clang::tidy::utils {
+
+static bool operator==(const UseRangesCheck::Replacer::Indexes &L,
+   const UseRangesCheck::Replacer::Indexes &R) {
+  return std::tie(L.BeginArg, L.EndArg, L.ReplaceArg) ==
+ std::tie(R.BeginArg, R.EndArg, R.ReplaceArg);
+}
+
+std::string
+getFullPrefix(ArrayRef Signature) {
+  std::string Output;
+  llvm::raw_string_ostream OS(Output);
+  for (auto Item : Signature) {
+OS << Item.BeginArg << ":" << Item.EndArg << ":"
+   << (Item.ReplaceArg == Item.First ? '0' : '1');
+  }
+  return Output;
+}
+
+static llvm::hash_code hash_value(const UseRangesCheck::Replacer::Indexes &L) {
+  return llvm::hash_combine(L.BeginArg, L.EndArg, L.ReplaceArg);
+}
+
+namespace {
+
+AST_MATCHER(Expr, hasSideEffects) {
+  return Node.HasSideEffects(Finder->getASTContext());
+}
+
+AST_MATCHER_P(Expr, isEquivalentToBound, std::string, Other) {
+  llvm::FoldingSetNodeID NodeRepr;
+  Node.Profile(NodeRepr, Finder->getASTContext(), true);
+  return Builder->removeBindings(
+  [this, &Finder,
+   &NodeRepr](const ast_matchers::internal::BoundNodesMap &Nodes) {
+auto BoundNode = Nodes.getNodeAs(Other);
+if (!BoundNode)
+  return true;
+llvm::FoldingSetNodeID BoundRepr;
+BoundNode->Profile(BoundRepr, Finder->getASTContext(), true);
+return BoundRepr != NodeRepr;
+  });
+}
+} // namespace
+
+static auto makeMatcher(bool IsBegin, StringRef Prefix) {
+  auto Member =
+  IsBegin ? expr(unless(hasSideEffects())).bind((ArgName + Prefix).str())
+  : expr(isEquivalentToBound((ArgName + Prefix).str()));
+  return expr(
+  anyOf(cxxMemberCallExpr(
+callee(cxxMethodDecl(IsBegin ? hasAnyName("begin", "cbegin")
+ : hasAnyName("end", "cend"))),
+on(Member)),
+callExpr(argumentCountIs(1), hasArgument(0, Member),
+ hasDeclaration(functionDecl(
+ IsBegin ? hasAnyName("::std::begin", "::std::cbegin")
+ : hasAnyName("::std::end", 
"::std::cend"));
+}
+static ast_matchers::internal::Matcher
+makeMatcherPair(StringRef State,
+const UseRangesCheck::Replacer::Indexes &Indexes) {
+  auto ArgPostfix = std::to_string(Indexes.BeginArg);
+  SmallString<64> ID = {BoundCall, State};
+  return callExpr(argumentCountAtLeast(
+  std::max(Indexes.BeginArg, Indexes.EndArg) + 1),
+  hasArgument(Indexes.BeginArg, makeMatcher(true, ArgPostfix)),
+  hasArgument(Indexes.EndArg, makeMatcher(false, ArgPostfix)))
+  .bind(ID);
+}
+
+void UseRangesCheck::registerMatchers(MatchFinder *Finder) {
+  Replaces = GetReplacerMap();
+  llvm::DenseSet>> Seen;
+  for (auto I = Replaces.begin(), E = Replaces.end(); I != E; ++I) {
+const auto &Replacer = I->getValue();
+const auto &Signatures = Replacer->getReplacementSignatures();
+if (Seen.contains(Signatures))
+  continue;
+assert(!Signatures.empty() &&
+   llvm::all_of(Signatures, [](auto index) { return !index.empty(); 
}));
+std::vector Names(1, I->getKey());
+for (auto J = std::next(I); J != E; ++J) {
+  if (J->getValue()->getReplacementSignatures() == Signatures) {
+Names.push_back(J->getKey());
+  }
+}
+std::vector TotalMatchers;
+// As we match on the first matched signature, we need to ensure that any
+SmallVector> SigVec(Signatures);
+llvm::sort(SigVec, [](auto &L, auto &R) { return R.size() < L.size(); });
+for (const auto &Signature : SigVec) {
+  std::vector Matche

[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,58 @@
+//===--- UseRangesCheck.h - clang-tidy --*- C++ 
-*-===//
+//
+// 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
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_USERANGESCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_USERANGESCHECK_H
+
+#include "../ClangTidyCheck.h"
+#include "IncludeInserter.h"
+#include "clang/AST/Decl.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang::tidy::utils {
+
+/// FIXME: Base class for handling converting std iterator algorithms to a 
range

PiotrZSL wrote:

Nit: Maybe just drop "FIXME"

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,58 @@
+//===--- UseRangesCheck.h - clang-tidy --*- C++ 
-*-===//
+//
+// 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
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_USERANGESCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_USERANGESCHECK_H
+
+#include "../ClangTidyCheck.h"
+#include "IncludeInserter.h"
+#include "clang/AST/Decl.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang::tidy::utils {
+
+/// FIXME: Base class for handling converting std iterator algorithms to a 
range
+/// equivalent
+class UseRangesCheck : public ClangTidyCheck {
+public:
+  class Replacer : public llvm::RefCountedBase {
+  public:
+struct Indexes {
+  enum Replace { First, Second };
+  unsigned BeginArg;

PiotrZSL wrote:

Nit: `BeginArg = 0U`,

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,24 @@
+.. title:: clang-tidy - boost-use-ranges
+

PiotrZSL wrote:

add options that check has (like include style).

Add table with info what is converted to what.

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,24 @@
+.. title:: clang-tidy - modernize-use-ranges
+
+modernize-use-ranges
+
+
+Detects calls to standard library iterator algorithms that could be replaced
+with a ranges version instead
+

PiotrZSL wrote:

Same:
- table with list of what is converted to what
- check options

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,253 @@
+//===--- UseRangesCheck.cpp - clang-tidy 
--===//
+//
+// 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 "UseRangesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallBitVector.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+static constexpr const char BoundCall[] = "CallExpr";
+static constexpr const char FuncDecl[] = "FuncDecl";
+static constexpr const char ArgName[] = "ArgName";
+
+namespace clang::tidy::utils {
+
+static bool operator==(const UseRangesCheck::Replacer::Indexes &L,
+   const UseRangesCheck::Replacer::Indexes &R) {
+  return std::tie(L.BeginArg, L.EndArg, L.ReplaceArg) ==
+ std::tie(R.BeginArg, R.EndArg, R.ReplaceArg);
+}
+
+std::string
+getFullPrefix(ArrayRef Signature) {
+  std::string Output;
+  llvm::raw_string_ostream OS(Output);
+  for (auto Item : Signature) {
+OS << Item.BeginArg << ":" << Item.EndArg << ":"
+   << (Item.ReplaceArg == Item.First ? '0' : '1');
+  }
+  return Output;
+}
+
+static llvm::hash_code hash_value(const UseRangesCheck::Replacer::Indexes &L) {
+  return llvm::hash_combine(L.BeginArg, L.EndArg, L.ReplaceArg);
+}
+
+namespace {
+
+AST_MATCHER(Expr, hasSideEffects) {
+  return Node.HasSideEffects(Finder->getASTContext());
+}
+
+AST_MATCHER_P(Expr, isEquivalentToBound, std::string, Other) {
+  llvm::FoldingSetNodeID NodeRepr;
+  Node.Profile(NodeRepr, Finder->getASTContext(), true);
+  return Builder->removeBindings(
+  [this, &Finder,
+   &NodeRepr](const ast_matchers::internal::BoundNodesMap &Nodes) {
+auto BoundNode = Nodes.getNodeAs(Other);
+if (!BoundNode)
+  return true;
+llvm::FoldingSetNodeID BoundRepr;
+BoundNode->Profile(BoundRepr, Finder->getASTContext(), true);
+return BoundRepr != NodeRepr;
+  });
+}
+} // namespace
+
+static auto makeMatcher(bool IsBegin, StringRef Prefix) {
+  auto Member =
+  IsBegin ? expr(unless(hasSideEffects())).bind((ArgName + Prefix).str())
+  : expr(isEquivalentToBound((ArgName + Prefix).str()));
+  return expr(
+  anyOf(cxxMemberCallExpr(
+callee(cxxMethodDecl(IsBegin ? hasAnyName("begin", "cbegin")
+ : hasAnyName("end", "cend"))),
+on(Member)),
+callExpr(argumentCountIs(1), hasArgument(0, Member),
+ hasDeclaration(functionDecl(
+ IsBegin ? hasAnyName("::std::begin", "::std::cbegin")
+ : hasAnyName("::std::end", 
"::std::cend"));
+}
+static ast_matchers::internal::Matcher
+makeMatcherPair(StringRef State,
+const UseRangesCheck::Replacer::Indexes &Indexes) {
+  auto ArgPostfix = std::to_string(Indexes.BeginArg);
+  SmallString<64> ID = {BoundCall, State};
+  return callExpr(argumentCountAtLeast(
+  std::max(Indexes.BeginArg, Indexes.EndArg) + 1),
+  hasArgument(Indexes.BeginArg, makeMatcher(true, ArgPostfix)),
+  hasArgument(Indexes.EndArg, makeMatcher(false, ArgPostfix)))
+  .bind(ID);
+}
+
+void UseRangesCheck::registerMatchers(MatchFinder *Finder) {
+  Replaces = GetReplacerMap();
+  llvm::DenseSet>> Seen;
+  for (auto I = Replaces.begin(), E = Replaces.end(); I != E; ++I) {
+const auto &Replacer = I->getValue();
+const auto &Signatures = Replacer->getReplacementSignatures();
+if (Seen.contains(Signatures))
+  continue;
+assert(!Signatures.empty() &&
+   llvm::all_of(Signatures, [](auto index) { return !index.empty(); 
}));
+std::vector Names(1, I->getKey());
+for (auto J = std::next(I); J != E; ++J) {
+  if (J->getValue()->getReplacementSignatures() == Signatures) {
+Names.push_back(J->getKey());
+  }
+}
+std::vector TotalMatchers;
+// As we match on the first matched signature, we need to ensure that any
+SmallVector> SigVec(Signatures);
+llvm::sort(SigVec, [](auto &L, auto &R) { return R.size() < L.size(); });
+for (const auto &Signature : SigVec) {
+  std::vector Matche

[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,24 @@
+.. title:: clang-tidy - modernize-use-ranges
+
+modernize-use-ranges
+
+
+Detects calls to standard library iterator algorithms that could be replaced
+with a ranges version instead
+
+Example
+---
+
+.. code-block:: c++
+
+  auto Iter1 = std::find(Items.begin(), Items.end(), 0);
+  auto AreSame = std::equal(std::execution::par, Items1.cbegin(), 
Items1.cend(),
+std::begin(Items2), std::end(Items2));
+
+
+transforms to:
+
+.. code-block:: c++
+
+  auto Iter1 = std::ranges::find(Items, 0);
+  auto AreSame = std::equal(std::execution::par, Items1, Items2);

PiotrZSL wrote:

should be "std::ranges::equal"

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

2024-07-05 Thread Nathan James via cfe-commits

https://github.com/njames93 updated 
https://github.com/llvm/llvm-project/pull/97764

>From ef9042357628f4c2e83d6be322f2d177a6170ebd Mon Sep 17 00:00:00 2001
From: Nathan James 
Date: Tue, 2 Jul 2024 14:25:44 +0100
Subject: [PATCH 1/2] Add a modernize-use-ranges check

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/ModernizeTidyModule.cpp |   2 +
 .../clang-tidy/modernize/UseRangesCheck.cpp   | 151 ++
 .../clang-tidy/modernize/UseRangesCheck.h |  31 +++
 .../clang-tidy/utils/CMakeLists.txt   |   1 +
 .../clang-tidy/utils/UseRangesCheck.cpp   | 258 ++
 .../clang-tidy/utils/UseRangesCheck.h |  60 
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../checks/modernize/use-ranges.rst   |  24 ++
 .../checkers/modernize/use-ranges.cpp | 171 
 11 files changed, 706 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseRangesCheck.h
 create mode 100644 clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/utils/UseRangesCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-ranges.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 576805c4c7f181..4f68c487cac9d4 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -40,6 +40,7 @@ add_clang_library(clangTidyModernizeModule
   UseNoexceptCheck.cpp
   UseNullptrCheck.cpp
   UseOverrideCheck.cpp
+  UseRangesCheck.cpp
   UseStartsEndsWithCheck.cpp
   UseStdFormatCheck.cpp
   UseStdNumbersCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index b9c7a2dc383e88..18607593320635 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -41,6 +41,7 @@
 #include "UseNoexceptCheck.h"
 #include "UseNullptrCheck.h"
 #include "UseOverrideCheck.h"
+#include "UseRangesCheck.h"
 #include "UseStartsEndsWithCheck.h"
 #include "UseStdFormatCheck.h"
 #include "UseStdNumbersCheck.h"
@@ -75,6 +76,7 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck("modernize-pass-by-value");
 CheckFactories.registerCheck(
 "modernize-use-designated-initializers");
+CheckFactories.registerCheck("modernize-use-ranges");
 CheckFactories.registerCheck(
 "modernize-use-starts-ends-with");
 
CheckFactories.registerCheck("modernize-use-std-format");
diff --git a/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
new file mode 100644
index 00..ae6c88c89d04b5
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
@@ -0,0 +1,151 @@
+//===--- UseRangesCheck.cpp - clang-tidy 
--===//
+//
+// 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 "UseRangesCheck.h"
+#include "clang/AST/Decl.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace clang::tidy::modernize {
+
+utils::UseRangesCheck::ReplacerMap UseRangesCheck::GetReplacerMap() const {
+  class StdReplacer : public utils::UseRangesCheck::Replacer {
+  public:
+explicit StdReplacer(SmallVector Indexes)
+: Indexes(std::move(Indexes)) {}
+std::string getReplaceName(const NamedDecl &OriginalName) const override {
+  return ("std::ranges::" + OriginalName.getName()).str();
+}
+ArrayRef getReplacementSignatures() const 
override {
+  return Indexes;
+}
+std::optional
+getHeaderInclusion(const NamedDecl & /*OriginalName*/) const override {
+  return "";
+}
+
+  private:
+SmallVector Indexes;
+  };
+
+  utils::UseRangesCheck::ReplacerMap Result;
+  
+  // template Func(Iter first, Iter last,...).
+  static const Signature SingleRangeArgs = {{0}};
+  // template
+  // Func(Policy policy, Iter first, // Iter last,...).
+  static const Signature SingleRangeExecPolicy = {{1}};
+  // template
+  // Func(Iter1 first1, Iter1 last1, Iter2 first2, Iter2 last2,...).
+  static const Signature TwoRangeArgs = {{0}, {2}};
+  // template
+  // Func(Policy policy, Iter1 first1, Iter1 last1, Iter2 first2, Ite

[clang] [AArch64] Add getHostCPUFeatures to query for enabled features in cpu info (PR #97749)

2024-07-05 Thread David Spickett via cfe-commits

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


[clang] [AArch64] Add getHostCPUFeatures to query for enabled features in cpu info (PR #97749)

2024-07-05 Thread David Spickett via cfe-commits

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


[clang] [clang][AArch64] Add getHostCPUFeatures to query for enabled features in cpu info (PR #97749)

2024-07-05 Thread David Spickett via cfe-commits

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

2024-07-05 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 f1903431558b93f0fc48f195282f61194cb024fe 
9f9895da9657543724ccce2b8bbabbfa8df4ea1d -- 
clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp 
clang-tools-extra/clang-tidy/boost/UseRangesCheck.h 
clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp 
clang-tools-extra/clang-tidy/modernize/UseRangesCheck.h 
clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp 
clang-tools-extra/clang-tidy/utils/UseRangesCheck.h 
clang-tools-extra/test/clang-tidy/checkers/boost/use-ranges.cpp 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp 
clang-tools-extra/clang-tidy/boost/BoostTidyModule.cpp 
clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
index ae6c88c89d..b6cbba97f4 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
@@ -23,7 +23,8 @@ utils::UseRangesCheck::ReplacerMap 
UseRangesCheck::GetReplacerMap() const {
 std::string getReplaceName(const NamedDecl &OriginalName) const override {
   return ("std::ranges::" + OriginalName.getName()).str();
 }
-ArrayRef getReplacementSignatures() const 
override {
+ArrayRef
+getReplacementSignatures() const override {
   return Indexes;
 }
 std::optional
@@ -36,7 +37,7 @@ utils::UseRangesCheck::ReplacerMap 
UseRangesCheck::GetReplacerMap() const {
   };
 
   utils::UseRangesCheck::ReplacerMap Result;
-  
+
   // template Func(Iter first, Iter last,...).
   static const Signature SingleRangeArgs = {{0}};
   // template
@@ -52,85 +53,83 @@ utils::UseRangesCheck::ReplacerMap 
UseRangesCheck::GetReplacerMap() const {
 
   static const Signature SingleRangeFunc[] = {SingleRangeArgs};
 
-  static const Signature SingleRangeExecFunc[] = {
-  SingleRangeArgs, SingleRangeExecPolicy};
+  static const Signature SingleRangeExecFunc[] = {SingleRangeArgs,
+  SingleRangeExecPolicy};
   static const Signature TwoRangeExecFunc[] = {TwoRangeArgs,
-   TwoRangeExecPolicy};
-  static const Signature OneOrTwoFunc[] = {SingleRangeArgs,
-   TwoRangeArgs};
+   TwoRangeExecPolicy};
+  static const Signature OneOrTwoFunc[] = {SingleRangeArgs, TwoRangeArgs};
   static const Signature OneOrTwoExecFunc[] = {
   SingleRangeArgs, SingleRangeExecPolicy, TwoRangeArgs, 
TwoRangeExecPolicy};
 
-  static const std::pair, ArrayRef>
-  Names[] = {
-  {SingleRangeFunc,
-   {"all_of",
-"any_of",
-"none_of",
-"for_each",
-"find",
-"find_if",
-"find_if_not",
-"adjacent_find",
-"copy",
-"copy_if",
-"copy_backward",
-"move",
-"move_backward",
-"fill",
-"transform",
-"replace",
-"replace_if",
-"generate",
-"remove",
-"remove_if",
-"remove_copy",
-"remove_copy_if",
-"unique",
-"unique_copy",
-"sample",
-"partition_point",
-"lower_bound",
-"upper_bound",
-"equal_range",
-"binary_search",
-"push_heap",
-"pop_heap",
-"make_heap",
-"sort_heap",
-"next_permutation",
-"prev_permutation",
-"iota"}},
-  {SingleRangeExecFunc,
-   {"reverse",
-"reverse_copy",
-"shift_left",
-"shift_right",
-"is_partitioned",
-"partition",
-"partition_copy",
-"stable_partition",
-"sort",
-"stable_sort",
-"is_sorted",
-"is_sorted_until",
-"is_heap",
-"is_heap_until",
-"max_element",
-"min_element",
-"minmax_element",
-"uninitialized_copy",
-"uninitialized_fill",
-"uninitialized_move",
-"uninitialized_default_construct",
-"uninitialized_value_construct",
-"destroy"}},
-  {TwoRangeExecFunc,
-   {"partial_sort_copy", "includes", "set_union", "set_intersection",
-"set_difference", "set_symmetric_difference", "merge",
-"lexicographical_compare", "find_end", "search"}},
-  {OneOrTwoFunc, {"is_permutation"}},
-  {OneOrTwoExecFunc, {

[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

2024-07-05 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/97585

>From 8af656659b79d76c971b01f1f4c14dc7315565b8 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Fri, 21 Jun 2024 18:55:38 +0100
Subject: [PATCH 1/6] [Clang] Warn on backslash-newline-EOF

---
 clang/docs/ReleaseNotes.rst   |  2 +
 .../include/clang/Basic/DiagnosticLexKinds.td |  1 +
 clang/lib/Lex/Lexer.cpp   | 39 +--
 clang/test/CXX/drs/cwg16xx.cpp|  9 +
 clang/test/CXX/drs/cwg2747.cpp| 11 ++
 clang/test/CXX/drs/cwg27xx.cpp|  2 +
 .../test/Preprocessor/backslash_newline_eof.c | 12 ++
 .../Preprocessor/backslash_without_newline.c  |  8 
 .../Preprocessor/backslash_without_newline.h  |  4 ++
 clang/www/cxx_dr_status.html  |  4 +-
 10 files changed, 87 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CXX/drs/cwg2747.cpp
 create mode 100644 clang/test/Preprocessor/backslash_newline_eof.c
 create mode 100644 clang/test/Preprocessor/backslash_without_newline.c
 create mode 100644 clang/test/Preprocessor/backslash_without_newline.h

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f40fd1cd145bb0..7c0ac3a504f982 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -647,6 +647,8 @@ Improvements to Clang's diagnostics
 
 - Clang now shows implicit deduction guides when diagnosing overload 
resolution failure. #GH92393.
 
+- Clang now emits ``-Wnewline-eof`` when the last newline is deleted by a 
preceding backslash.
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 12d7b8c0205ee9..e6b2c1385944c7 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -56,6 +56,7 @@ def ext_no_newline_eof : Extension<"no newline at end of 
file">,
   InGroup;
 def warn_no_newline_eof : Warning<"no newline at end of file">,
   InGroup, DefaultIgnore;
+def note_backslash_newline_eof : Note<"last newline deleted by splice here">;
 
 def warn_cxx98_compat_no_newline_eof : Warning<
   "C++98 requires newline at end of file">,
diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp
index e59c7805b38623..0e540834b473ba 100644
--- a/clang/lib/Lex/Lexer.cpp
+++ b/clang/lib/Lex/Lexer.cpp
@@ -3165,7 +3165,17 @@ bool Lexer::LexEndOfFile(Token &Result, const char 
*CurPtr) {
 
   // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
   // a pedwarn.
-  if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
+  if (CurPtr != BufferStart) {
+StringRef LastNewline;
+if (CurPtr[-1] == '\r' || CurPtr[-1] == '\n') {
+  LastNewline = StringRef(CurPtr - 1, 1);
+  if (CurPtr - 1 != BufferStart && CurPtr[-2] != CurPtr[-1] &&
+  (CurPtr[-2] == '\r' || CurPtr[-2] == '\n')) {
+// \r\n or \n\r is one newline
+LastNewline = StringRef(CurPtr - 2, 2);
+  }
+}
+
 DiagnosticsEngine &Diags = PP->getDiagnostics();
 SourceLocation EndLoc = getSourceLocation(BufferEnd);
 unsigned DiagID;
@@ -3183,8 +3193,31 @@ bool Lexer::LexEndOfFile(Token &Result, const char 
*CurPtr) {
   DiagID = diag::ext_no_newline_eof;
 }
 
-Diag(BufferEnd, DiagID)
-  << FixItHint::CreateInsertion(EndLoc, "\n");
+if (LastNewline.empty()) {
+  Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n");
+} else {
+  // While the file physically ends in a newline, the previous
+  // line might have ended in a splice, so it would be deleted
+  const char *LastSpliceLocation = LastNewline.data();
+  while (LastSpliceLocation != BufferStart &&
+ isHorizontalWhitespace(*--LastSpliceLocation))
+;
+
+  bool LastIsSplice = *LastSpliceLocation == '\\';
+  if (*LastSpliceLocation == '/' && LangOpts.Trigraphs)
+// Check for "??/" trigraph for "\"
+LastIsSplice =
+LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?' 
&&
+LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?';
+
+  if (LastIsSplice) {
+PP->Diag(getSourceLocation(LastNewline.data(), LastNewline.size()),
+ DiagID);
+Diag(LastSpliceLocation, diag::note_backslash_newline_eof)
+<< FixItHint::CreateRemoval(getSourceLocation(
+   LastSpliceLocation, *LastSpliceLocation == '\\' ? 1 : 3));
+  }
+}
   }
 
   BufferPtr = CurPtr;
diff --git a/clang/test/CXX/drs/cwg16xx.cpp b/clang/test/CXX/drs/cwg16xx.cpp
index cf6b45ceabf2cc..dca941fa30624f 100644
--- a/clang/test/CXX/drs/cwg16xx.cpp
+++ b/clang/test/CXX/drs/cwg16xx.cpp
@@ -536,3 +536,12 @@ namespace cwg1696 { // cwg1696: 7
   };
 #endif
 }
+
+// cwg1698: yes
+// This file intentionally does not end

[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

2024-07-05 Thread Mital Ashok via cfe-commits


@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -std=c++11 -pedantic-errors -verify=expected %s -E | 
FileCheck %s --strict-whitespace --allow-empty

MitalAshok wrote:

Fixed now, thanks

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


[clang] [Clang] [C23] Fix typeof_unqual for qualified array types (PR #92767)

2024-07-05 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/92767

>From f87cb4c754a477515746e2ac2f8906b93ccd1fe3 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Mon, 20 May 2024 15:58:58 +0100
Subject: [PATCH 1/5] [Clang] [C23] Fix typeof_unqual for qualified array types

Properly remove qualifiers for both the element type and the array type

Fixes #92667
---
 clang/include/clang/AST/ASTContext.h |  6 -
 clang/include/clang/AST/Type.h   | 37 +--
 clang/lib/AST/ASTContext.cpp | 14 +-
 clang/lib/AST/Type.cpp   | 38 ++--
 clang/test/Sema/c2x-typeof.c | 25 ++
 5 files changed, 84 insertions(+), 36 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index e03b112194786..ff7bdb7e7e1a6 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2611,7 +2611,11 @@ class ASTContext : public RefCountedBase {
   ///
   /// \returns if this is an array type, the completely unqualified array type
   /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
-  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
+  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const;
+  QualType getUnqualifiedArrayType(QualType T) const {
+Qualifiers Quals;
+return getUnqualifiedArrayType(T, Quals);
+  }
 
   /// Determine whether the given types are equivalent after
   /// cvr-qualifiers have been removed.
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index da3834f19ca04..df7f396bae095 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -1605,6 +1605,10 @@ class QualType {
   QualType stripObjCKindOfType(const ASTContext &ctx) const;
 
   /// Remove all qualifiers including _Atomic.
+  ///
+  /// Like getUnqualifiedType(), the type may still be qualified if it is a
+  /// sugared array type.  To strip qualifiers even from within a sugared array
+  /// type, use ASTContext::getUnqualifiedArrayType.
   QualType getAtomicUnqualifiedType() const;
 
 private:
@@ -2092,8 +2096,8 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 
 LLVM_PREFERRED_TYPE(TypeBitfields)
 unsigned : NumTypeBits;
-LLVM_PREFERRED_TYPE(bool)
-unsigned IsUnqual : 1; // If true: typeof_unqual, else: typeof
+LLVM_PREFERRED_TYPE(TypeOfKind)
+unsigned Kind : 1;
   };
 
   class UsingBitfields {
@@ -5273,19 +5277,20 @@ class MacroQualifiedType : public Type {
 /// extension) or a `typeof_unqual` expression (a C23 feature).
 class TypeOfExprType : public Type {
   Expr *TOExpr;
+  const ASTContext &Context;
 
 protected:
   friend class ASTContext; // ASTContext creates these.
 
-  TypeOfExprType(Expr *E, TypeOfKind Kind, QualType Can = QualType());
+  TypeOfExprType(const ASTContext &Context, Expr *E, TypeOfKind Kind,
+ QualType Can = QualType());
 
 public:
   Expr *getUnderlyingExpr() const { return TOExpr; }
 
   /// Returns the kind of 'typeof' type this is.
   TypeOfKind getKind() const {
-return TypeOfBits.IsUnqual ? TypeOfKind::Unqualified
-   : TypeOfKind::Qualified;
+return static_cast(TypeOfBits.Kind);
   }
 
   /// Remove a single level of sugar.
@@ -5306,7 +5311,8 @@ class TypeOfExprType : public Type {
 class DependentTypeOfExprType : public TypeOfExprType,
 public llvm::FoldingSetNode {
 public:
-  DependentTypeOfExprType(Expr *E, TypeOfKind Kind) : TypeOfExprType(E, Kind) 
{}
+  DependentTypeOfExprType(const ASTContext &Context, Expr *E, TypeOfKind Kind)
+  : TypeOfExprType(Context, E, Kind) {}
 
   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
 Profile(ID, Context, getUnderlyingExpr(),
@@ -5323,32 +5329,23 @@ class TypeOfType : public Type {
   friend class ASTContext; // ASTContext creates these.
 
   QualType TOType;
+  const ASTContext &Context;
 
-  TypeOfType(QualType T, QualType Can, TypeOfKind Kind)
-  : Type(TypeOf,
- Kind == TypeOfKind::Unqualified ? Can.getAtomicUnqualifiedType()
- : Can,
- T->getDependence()),
-TOType(T) {
-TypeOfBits.IsUnqual = Kind == TypeOfKind::Unqualified;
-  }
+  TypeOfType(const ASTContext &Context, QualType T, QualType Can,
+ TypeOfKind Kind);
 
 public:
   QualType getUnmodifiedType() const { return TOType; }
 
   /// Remove a single level of sugar.
-  QualType desugar() const {
-QualType QT = getUnmodifiedType();
-return TypeOfBits.IsUnqual ? QT.getAtomicUnqualifiedType() : QT;
-  }
+  QualType desugar() const;
 
   /// Returns whether this type directly provides sugar.
   bool isSugared() const { return true; }
 
   /// Returns the kind of 'typeof' type this is.
   TypeOfKind getKind() const {
-return TypeOfBits.IsUnqual ? 

[clang] [clang][AArch64] Add getHostCPUFeatures to query for enabled features in cpu info (PR #97749)

2024-07-05 Thread David Spickett via cfe-commits

DavidSpickett wrote:

Looks ok to me, X86 and ARM already do this.

> One point we noticed is that it could end up turning "aes+sha2" into "crypto" 
> and "crypto" back into "sha2+aes+sha3+sm4", as it uses the old meaning of 
> "crypto"

Then this needs to be fixed before this PR can go in, we don't want to be 
making binaries folks can't run. @davemgreen do we have a way that @neildhickey 
can reproduce that easily?


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


[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

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

https://github.com/Endilll commented:

DR tests look good now.

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


[clang] [llvm] [PAC][Driver] Implement `-mbranch-protection=pauthabi` option (PR #97237)

2024-07-05 Thread Daniel Kiss via cfe-commits


@@ -1537,11 +1570,16 @@ static void CollectARMPACBTIOptions(const ToolChain 
&TC, const ArgList &Args,
 if (!isAArch64 && PBP.Key == "b_key")
   D.Diag(diag::warn_unsupported_branch_protection)
   << "b-key" << A->getAsString(Args);
+if (!isAArch64 && PBP.HasPauthABI)
+  D.Diag(diag::warn_unsupported_branch_protection)
+  << "pauthabi" << A->getAsString(Args);
 Scope = PBP.Scope;
 Key = PBP.Key;
 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
 IndirectBranches = PBP.BranchTargetEnforcement;
 GuardedControlStack = PBP.GuardedControlStack;
+if (isAArch64 && PBP.HasPauthABI)

DanielKristofKiss wrote:

FYI - I'm going to change the `sign-return-address` and variants to be a 
function flag. (#82819) 

`bti` - All `BRA*` and `BLRA*` instructions set the `PSTATE.BTYPE`.  I prefer 
to check the [pseudo 
code](https://developer.arm.com/documentation/ddi0602/2022-06/Base-Instructions/BLRAA--BLRAAZ--BLRAB--BLRABZ--Branch-with-Link-to-Register--with-pointer-authentication-
 )for this things (see BTypeNext)

IMHO `pauthabi+bti` makes sense as they are complementary while other option 
are overlapping. We can introduce this combination later. 

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


[clang] [Clang] Access tls_guard via llvm.threadlocal.address (PR #96633)

2024-07-05 Thread John McCall via cfe-commits


@@ -1070,13 +1084,20 @@ 
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
   // Mark as initialized before initializing anything else. If the
   // initializers use previously-initialized thread_local vars, that's
   // probably supposed to be OK, but the standard doesn't say.
-  Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), 
Guard);
-
-  // The guard variable can't ever change again.
+  // Get the thread-local address via intrinsic.
+  if (IsTLS)
+GuardAddr = GuardAddr.withPointer(
+Builder.CreateThreadLocalAddress(Guard.getPointer()),
+NotKnownNonNull);
+  Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(), 1),
+  GuardAddr);
+
+  // Emit invariant start for TLS guard address.
   EmitInvariantStart(
   Guard.getPointer(),
   CharUnits::fromQuantity(
-  CGM.getDataLayout().getTypeAllocSize(GuardVal->getType(;
+  CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())),
+  IsTLS);

rjmccall wrote:

Yes, and in fact, sometimes that's required.  The way I think about it is that 
`threadlocal.address` is a real dynamic operation that resolves the address of 
the thread-local variable for a specific thread: namely, the current thread at 
the execution point where `threadlocal.address` appears. When we're doing a 
complicated operation on a specific thread-local variable, it's important to 
call `threadlocal.address` at the right point and then use that result 
throughout the operation.  Otherwise, a suspension in the middle of the 
operation will leave us working on a different thread-local variable at 
different points in the operation, which is not semantically allowed.

In this case, we initialize a thread-local variable and then enter an invariant 
region for it.  We need this to:
1. resolve the address of the TLV for the current thread, prior to performing 
any initialization;
2. initialize the TLV, which may include suspensions that change the current 
thread; and
3. enter an invariant region for the TLV we initialized, *not* the TLV for the 
new thread.  The new thread's TLV may not yet be in an invariant region.

Now, this may actually be moot, because I'm not sure it's actually allowed (or 
at least I'm not sure it *should* be allowed) to have a coroutine suspension in 
the middle of the initialization of a thread-local variable.  The interaction 
of thread-locals with coroutines that actually switch threads is deeply 
problematic; notably, the TLV for the new thread can actually be uninitialized 
when you go to use it.  I haven't checked what the standard says here, but 
honestly this might have to have undefined behavior, in which case we just need 
to make sure we generate reasonable code as long as the thread *doesn't* change.

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


[clang] D41416: [modules] [pch] Do not deserialize all lazy template specializations when looking for one. (PR #83108)

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

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/83108

>From 270cdac974482a9852fa8c1bff517d444a5f51f2 Mon Sep 17 00:00:00 2001
From: Vassil Vassilev 
Date: Sun, 7 Jan 2018 15:16:11 +0200
Subject: [PATCH 1/2] D41416: [modules] [pch] Do not deserialize all lazy
 template specializations when looking for one.

---
 clang/include/clang/AST/DeclTemplate.h|  36 +++-
 clang/lib/AST/DeclTemplate.cpp| 100 +-
 clang/lib/AST/ODRHash.cpp |  15 
 clang/lib/Serialization/ASTReader.cpp |  25 --
 clang/lib/Serialization/ASTReaderDecl.cpp |  46 ++
 clang/lib/Serialization/ASTWriter.cpp |  21 -
 clang/lib/Serialization/ASTWriterDecl.cpp |  76 +---
 clang/test/Modules/cxx-templates.cpp  |   8 +-
 clang/test/Modules/odr_hash.cpp   |   4 +-
 9 files changed, 255 insertions(+), 76 deletions(-)

diff --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 5b6a6b40b28ef8..d76c2937063696 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -256,6 +256,9 @@ class TemplateArgumentList final
   TemplateArgumentList(const TemplateArgumentList &) = delete;
   TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
 
+  /// Create hash for the given arguments.
+  static unsigned ComputeODRHash(ArrayRef Args);
+
   /// Create a new template argument list that copies the given set of
   /// template arguments.
   static TemplateArgumentList *CreateCopy(ASTContext &Context,
@@ -729,6 +732,26 @@ class RedeclarableTemplateDecl : public TemplateDecl,
   }
 
   void anchor() override;
+  struct LazySpecializationInfo {
+GlobalDeclID DeclID = GlobalDeclID();
+unsigned ODRHash = ~0U;
+bool IsPartial = false;
+LazySpecializationInfo(GlobalDeclID ID, unsigned Hash = ~0U,
+   bool Partial = false)
+  : DeclID(ID), ODRHash(Hash), IsPartial(Partial) { }
+LazySpecializationInfo() { }
+bool operator<(const LazySpecializationInfo &Other) const {
+  return DeclID < Other.DeclID;
+}
+bool operator==(const LazySpecializationInfo &Other) const {
+  assert((DeclID != Other.DeclID || ODRHash == Other.ODRHash) &&
+ "Hashes differ!");
+  assert((DeclID != Other.DeclID || IsPartial == Other.IsPartial) &&
+ "Both must be the same kinds!");
+  return DeclID == Other.DeclID;
+}
+  };
+
 protected:
   template  struct SpecEntryTraits {
 using DeclType = EntryType;
@@ -769,7 +792,12 @@ class RedeclarableTemplateDecl : public TemplateDecl,
 return SpecIterator(isEnd ? Specs.end() : Specs.begin());
   }
 
-  void loadLazySpecializationsImpl() const;
+  void loadLazySpecializationsImpl(bool OnlyPartial = false) const;
+
+  void loadLazySpecializationsImpl(llvm::ArrayRef Args,
+   TemplateParameterList *TPL = nullptr) const;
+
+  Decl *loadLazySpecializationImpl(LazySpecializationInfo &LazySpecInfo) const;
 
   template 
   typename SpecEntryTraits::DeclType*
@@ -796,7 +824,7 @@ class RedeclarableTemplateDecl : public TemplateDecl,
 ///
 /// The first value in the array is the number of specializations/partial
 /// specializations that follow.
-GlobalDeclID *LazySpecializations = nullptr;
+LazySpecializationInfo *LazySpecializations = nullptr;
 
 /// The set of "injected" template arguments used within this
 /// template.
@@ -2279,7 +2307,7 @@ class ClassTemplateDecl : public RedeclarableTemplateDecl 
{
   friend class TemplateDeclInstantiator;
 
   /// Load any lazily-loaded specializations from the external source.
-  void LoadLazySpecializations() const;
+  void LoadLazySpecializations(bool OnlyPartial = false) const;
 
   /// Get the underlying class declarations of the template.
   CXXRecordDecl *getTemplatedDecl() const {
@@ -3023,7 +3051,7 @@ class VarTemplateDecl : public RedeclarableTemplateDecl {
   friend class ASTDeclWriter;
 
   /// Load any lazily-loaded specializations from the external source.
-  void LoadLazySpecializations() const;
+  void LoadLazySpecializations(bool OnlyPartial = false) const;
 
   /// Get the underlying variable declarations of the template.
   VarDecl *getTemplatedDecl() const {
diff --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp
index 722c7fcf0b0df7..021454c7707413 100644
--- a/clang/lib/AST/DeclTemplate.cpp
+++ b/clang/lib/AST/DeclTemplate.cpp
@@ -20,6 +20,8 @@
 #include "clang/AST/TemplateBase.h"
 #include "clang/AST/TemplateName.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/ODRHash.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/LLVM.h"
@@ -331,17 +333,46 @@ RedeclarableTemplateDecl::CommonBase 
*RedeclarableTemplateDecl::getCommonPtr() c
   return Common;
 }
 
-void RedeclarableTemplateDecl::loadLazySpecializatio

[clang] [clang][AArch64] Add getHostCPUFeatures to query for enabled features in cpu info (PR #97749)

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


@@ -445,4 +445,21 @@ void aarch64::getAArch64TargetFeatures(const Driver &D,
 
   if (Args.getLastArg(options::OPT_mno_bti_at_return_twice))
 Features.push_back("+no-bti-at-return-twice");
+
+  // Parse AArch64 CPU Features
+  const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);

tmatheson-arm wrote:

Feels like this should be done in 
`getAArch64ArchFeaturesFromMcpu`/`DecodeAArch64Mcpu`

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


[clang] [clang][AArch64] Add getHostCPUFeatures to query for enabled features in cpu info (PR #97749)

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


@@ -445,4 +445,21 @@ void aarch64::getAArch64TargetFeatures(const Driver &D,
 
   if (Args.getLastArg(options::OPT_mno_bti_at_return_twice))
 Features.push_back("+no-bti-at-return-twice");
+
+  // Parse AArch64 CPU Features
+  const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
+  StringRef CPUName;
+
+  if (CPUArg) {
+CPUName = CPUArg->getValue();
+if (CPUName == "native") {
+  llvm::StringMap HostFeatures;
+  if (llvm::sys::getHostCPUFeatures(HostFeatures)) {
+for (auto &F : HostFeatures) {
+  Features.push_back(
+Args.MakeArgString((F.second ? "+" : "-") + F.first()));
+}

tmatheson-arm wrote:

```suggestion
for (auto &[Name, Enabled] : HostFeatures) {
  Features.push_back(
Args.MakeArgString((Enabled ? "+" : "-") + Name));
}
```


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


[clang] [clang][AArch64] Add getHostCPUFeatures to query for enabled features in cpu info (PR #97749)

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

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


[clang] [clang-format] Skip block commented out includes when sorting them (PR #97787)

2024-07-05 Thread Björn Schäpers via cfe-commits

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


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


[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)

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

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/97733

>From f009148063ba41d39fc844f4432ceb51377f381c Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Thu, 4 Jul 2024 17:05:11 +0300
Subject: [PATCH 1/2] [clang] Implement P3144R2 "Deleting a Pointer to an
 Incomplete Type Should be Ill-formed"

---
 .../clang/Basic/DiagnosticSemaKinds.td|  2 ++
 clang/lib/Sema/SemaExprCXX.cpp| 12 ++---
 clang/test/CXX/drs/cwg5xx.cpp | 22 +---
 clang/test/SemaCXX/new-delete.cpp | 26 ---
 4 files changed, 41 insertions(+), 21 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 3df64b2ecef1b..5c3e311ac6382 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7991,6 +7991,8 @@ def err_ambiguous_delete_operand : Error<
 def warn_delete_incomplete : Warning<
   "deleting pointer to incomplete type %0 may cause undefined behavior">,
   InGroup;
+def err_delete_incomplete : Error<
+  "cannot delete pointer to incomplete type %0">;
 def err_delete_incomplete_class_type : Error<
   "deleting incomplete class type %0; no conversions to pointer type">;
 def err_delete_explicit_conversion : Error<
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 69074f92a0286..fcf2189a308a8 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -3719,8 +3719,11 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool 
UseGlobal,
   // The C++ standard bans deleting a pointer to a non-object type, which
   // effectively bans deletion of "void*". However, most compilers support
   // this, so we treat it as a warning unless we're in a SFINAE context.
-  Diag(StartLoc, diag::ext_delete_void_ptr_operand)
-<< Type << Ex.get()->getSourceRange();
+  // But we still prohibit this since C++26.
+  Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
+  : diag::ext_delete_void_ptr_operand)
+  << (LangOpts.CPlusPlus26 ? Pointee : Type)
+  << Ex.get()->getSourceRange();
 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
Pointee->isSizelessType()) {
   return ExprError(Diag(StartLoc, diag::err_delete_operand)
@@ -3729,7 +3732,10 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool 
UseGlobal,
   // FIXME: This can result in errors if the definition was imported from a
   // module but is hidden.
   if (!RequireCompleteType(StartLoc, Pointee,
-   diag::warn_delete_incomplete, Ex.get())) {
+   LangOpts.CPlusPlus26
+   ? diag::err_delete_incomplete
+   : diag::warn_delete_incomplete,
+   Ex.get())) {
 if (const RecordType *RT = PointeeElem->getAs())
   PointeeRD = cast(RT->getDecl());
   }
diff --git a/clang/test/CXX/drs/cwg5xx.cpp b/clang/test/CXX/drs/cwg5xx.cpp
index 9d890f981348a..6a0bb7a196669 100644
--- a/clang/test/CXX/drs/cwg5xx.cpp
+++ b/clang/test/CXX/drs/cwg5xx.cpp
@@ -1,9 +1,10 @@
-// RUN: %clang_cc1 -std=c++98 %s 
-verify=expected,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions -fcxx-exceptions 
-pedantic-errors
-// RUN: %clang_cc1 -std=c++11 %s 
-verify=expected,cxx98-11,cxx98-14,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
-// RUN: %clang_cc1 -std=c++14 %s 
-verify=expected,cxx98-14,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions 
-pedantic-errors
-// RUN: %clang_cc1 -std=c++17 %s 
-verify=expected,since-cxx17,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions 
-pedantic-errors
-// RUN: %clang_cc1 -std=c++20 %s 
-verify=expected,since-cxx20,since-cxx17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
-// RUN: %clang_cc1 -std=c++23 %s 
-verify=expected,since-cxx23,since-cxx20,since-cxx17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++98 %s 
-verify=expected,cxx98-23,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 %s 
-verify=expected,cxx98-23,cxx98-11,cxx98-14,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++14 %s 
-verify=expected,cxx98-23,cxx98-14,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++17 %s 
-verify=expected,cxx98-23,since-cxx17,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++20 %s 
-verify=expected,cxx98-23,since-cxx20,since-cxx17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++23 %s 
-verify=expected,cxx98-23,since-cxx23,since-cxx20,since-cxx17,since-cxx11 
-fexceptions -fcxx-exce

[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)

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

Endilll wrote:

> LGTM, generally speaking, but do we maybe want change the old diagnostic to 
> mention that it’s ‘incompatible w/ C++26’ or however we usually phrase that?
 
Done.

> Oh also, this still needs a release note and an entry in the C++ support 
> docs, doesn’t it?

Done.

I also added `-Wc++2c-compat` flag and corresponding diagnostic group.

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


[clang] [llvm] [AIX] Add -msave-reg-params to save arguments to stack (PR #97524)

2024-07-05 Thread Qiu Chaofan via cfe-commits

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


[clang] [llvm] [Clang][LLVM][AArch64] Add intrinsic for LUTI4 SME2 instruction (PR #97755)

2024-07-05 Thread via cfe-commits

https://github.com/CarolineConcatto updated 
https://github.com/llvm/llvm-project/pull/97755

>From 22f5bb7cab1673632f1fa5438a35f861c16d63b2 Mon Sep 17 00:00:00 2001
From: Caroline Concatto 
Date: Thu, 4 Jul 2024 17:10:36 +
Subject: [PATCH 1/2] [Clang][LLVM][AArch64] Add intrinsic for LUTI4 SME2
 instruction

This patch adds these intrinsics:

// Variants are also available for: _s8
  svuint8x4_t svluti4_zt_u8_x4(uint64_t zt0, svuint8x2_t zn) __arm_streaming 
__arm_in("zt0");

according to PR#324[1]
[1]ARM-software/acle#324
---
 clang/include/clang/Basic/arm_sme.td  |  5 ++
 .../acle_sme2_luti4_zt.c  | 82 +++
 .../aarch64-sme2-intrinsics/acle_sme2_imm.cpp |  5 ++
 llvm/include/llvm/IR/IntrinsicsAArch64.td |  6 ++
 .../Target/AArch64/AArch64ISelDAGToDAG.cpp| 19 -
 .../lib/Target/AArch64/AArch64SMEInstrInfo.td |  2 +-
 .../AArch64/sme2-intrinsics-write-zt.ll   | 17 
 7 files changed, 132 insertions(+), 4 deletions(-)
 create mode 100644 
clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c
 create mode 100644 llvm/test/CodeGen/AArch64/sme2-intrinsics-write-zt.ll

diff --git a/clang/include/clang/Basic/arm_sme.td 
b/clang/include/clang/Basic/arm_sme.td
index ce8908f566f2fd..e4a61caae733ec 100644
--- a/clang/include/clang/Basic/arm_sme.td
+++ b/clang/include/clang/Basic/arm_sme.td
@@ -817,4 +817,9 @@ multiclass ZAReadzArray{
 
 defm SVREADZ_VG2 :  ZAReadzArray<"2">;
 defm SVREADZ_VG4 :  ZAReadzArray<"4">;
+
+let SMETargetGuard = "sme2,sme-lutv2" in {
+  def SVLUTI4_ZT_X4 : SInst<"svluti4_zt_{d}_x4", "4i2", "cUc", MergeNone, 
"aarch64_sme_luti4_zt_x4", [IsStreaming, IsInOutZT0], [ImmCheck<0, 
ImmCheck0_0>]>;
+}
+
 } // let SVETargetGuard = InvalidMode
diff --git a/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c 
b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c
new file mode 100644
index 00..2e7cd0939f516b
--- /dev/null
+++ b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c
@@ -0,0 +1,82 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang_cc1  -triple aarch64-none-linux-gnu -target-feature +bf16 
-target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 
-Werror -Wall -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -x c++  -triple aarch64-none-linux-gnu -target-feature 
+bf16 -target-feature +sme -target-feature +sme2 -target-feature  +sme-lutv2  
-O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s -check-prefix CHECK-CXX
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS   -triple aarch64-none-linux-gnu 
-target-feature +bf16 -target-feature +sme -target-feature +sme2 
-target-feature  +sme-lutv2  -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -x c++  -triple 
aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme 
-target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm 
-o - %s | FileCheck %s -check-prefix CHECK-CXX
+
+// RUN: %clang_cc1  -triple aarch64-none-linux-gnu -target-feature +bf16 
-target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -S 
-Werror -Wall -o /dev/null %s
+// REQUIRES: aarch64-registered-target
+
+#include 
+
+// CHECK-LABEL: define dso_local  @test_luti4_zt_u8_x4(
+// CHECK-SAME:  [[OP:%.*]]) local_unnamed_addr 
#[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 0)
+// CHECK-NEXT:[[TMP1:%.*]] = tail call  
@llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 16)
+// CHECK-NEXT:[[TMP2:%.*]] = tail call { , , ,  } 
@llvm.aarch64.sme.luti4.zt.x4.nxv16i8(i32 0,  [[TMP0]], 
 [[TMP1]])
+// CHECK-NEXT:[[TMP3:%.*]] = extractvalue { , , ,  } [[TMP2]], 0
+// CHECK-NEXT:[[TMP4:%.*]] = tail call  
@llvm.vector.insert.nxv64i8.nxv16i8( poison,  [[TMP3]], i64 0)
+// CHECK-NEXT:[[TMP5:%.*]] = extractvalue { , , ,  } [[TMP2]], 1
+// CHECK-NEXT:[[TMP6:%.*]] = tail call  
@llvm.vector.insert.nxv64i8.nxv16i8( [[TMP4]],  [[TMP5]], i64 16)
+// CHECK-NEXT:[[TMP7:%.*]] = extractvalue { , , ,  } [[TMP2]], 2
+// CHECK-NEXT:[[TMP8:%.*]] = tail call  
@llvm.vector.insert.nxv64i8.nxv16i8( [[TMP6]],  [[TMP7]], i64 32)
+// CHECK-NEXT:[[TMP9:%.*]] = extractvalue { , , ,  } [[TMP2]], 3
+// CHECK-NEXT:[[TMP10:%.*]] = tail call  
@llvm.vector.insert.nxv64i8.nxv16i8( [[TMP8]],  [[TMP9]], i64 48)
+// CHECK-NEXT:ret  [[TMP10]]
+//
+// CHECK-CXX-LABEL: define dso_local  
@_Z19test_luti4_zt_u8_x411svuint8x2_t(
+// CHECK-CXX-SAME:  [[OP:%.*]]) local_unnamed_addr 
#[[ATTR0:[0-9]+]] {
+// CHECK-CXX-NEXT:  [[ENTRY:.*:]]
+// CHECK-CXX-NEXT:[[TMP0:%.*]] = tail call  
@llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 0)
+// CHECK-CXX-NEXT:[[TMP1:%.*]] = tail call  
@llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 16)
+// CHECK-CXX-NEXT:[[TMP2:%.*]] = tail call { , , ,

[clang] [RFC] [clang][Toolchain] Treat "pc"/"unknown" vendor interchangeable (PR #97802)

2024-07-05 Thread Azat Khuzhin via cfe-commits

https://github.com/azat created https://github.com/llvm/llvm-project/pull/97802

Right now if you have runtime libraries under
lib/x86_64-unknown-linux-gnu you should use --target x86_64-unknown-linux-gnu, 
x86_64-pc-linux-gnu will not work.

Treat the interchangeable so that you can use any.

The initial reason for this patch is that debian packages uses 
x86_64-pc-linux-gnu, and after they enabled
LLVM_ENABLE_PER_TARGET_RUNTIME_DIR [1], clang cannot find runtime libraries for 
sanitizers.

  [1]: 
https://salsa.debian.org/pkg-llvm-team/llvm-toolchain/-/commit/9ca35f30383d89e4fdd45d15e0eb82c832df4b8c

>From dd290ddc48fd60d29e2c0eb839f9e9a08746d5f2 Mon Sep 17 00:00:00 2001
From: Azat Khuzhin 
Date: Fri, 5 Jul 2024 11:15:15 +0200
Subject: [PATCH] [clang][Toolchain] Treat "pc"/"unknown" vendor
 interchangeable

Right now if you have runtime libraries under
lib/x86_64-unknown-linux-gnu you should use --target
x86_64-unknown-linux-gnu, x86_64-pc-linux-gnu will not work.

Treat the interchangeable so that you can use any.

The initial reason for this patch is that debian packages uses
x86_64-pc-linux-gnu, and after they enabled
LLVM_ENABLE_PER_TARGET_RUNTIME_DIR [1], clang cannot find runtime
libraries for sanitizers.

  [1]: 
https://salsa.debian.org/pkg-llvm-team/llvm-toolchain/-/commit/9ca35f30383d89e4fdd45d15e0eb82c832df4b8c
---
 clang/lib/Driver/ToolChain.cpp   | 21 +
 clang/test/Driver/pc-unknown-toolchain.c |  4 
 2 files changed, 25 insertions(+)
 create mode 100644 clang/test/Driver/pc-unknown-toolchain.c

diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 977e08390800d..716cbfb43232b 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -765,6 +765,27 @@ ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
   if (auto Path = getPathForTriple(getTriple()))
 return *Path;
 
+  // Treat "pc" and "unknown" vendors interchangeable
+  switch (getTriple().getVendor())
+  {
+case Triple::UnknownVendor: {
+  llvm::Triple TripleFallback = Triple;
+  TripleFallback.setVendor(Triple::PC);
+  if (auto Path = getPathForTriple(TripleFallback))
+return *Path;
+  break;
+}
+case Triple::PC: {
+  llvm::Triple TripleFallback = Triple;
+  TripleFallback.setVendor(Triple::UnknownVendor);
+  if (auto Path = getPathForTriple(TripleFallback))
+return *Path;
+  break;
+}
+default:
+  break;
+  }
+
   // When building with per target runtime directories, various ways of naming
   // the Arm architecture may have been normalised to simply "arm".
   // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
diff --git a/clang/test/Driver/pc-unknown-toolchain.c 
b/clang/test/Driver/pc-unknown-toolchain.c
new file mode 100644
index 0..a7e9bb80b0f2d
--- /dev/null
+++ b/clang/test/Driver/pc-unknown-toolchain.c
@@ -0,0 +1,4 @@
+// RUN: %clang -### %s -fsanitize=address --target=x86_64-pc-linux-gnu 2>&1 | 
FileCheck -check-prefix=CHECK-ASAN-PC %s
+// CHECK-ASAN-PC: x86_64-unknown-linux-gnu/libclang_rt.asan_static.a
+// RUN: %clang -### %s -fsanitize=address --target=x86_64-unknown-linux-gnu 
2>&1 | FileCheck -check-prefix=CHECK-ASAN-UNKNOWN %s
+// CHECK-ASAN-UNKNOWN: x86_64-unknown-linux-gnu/libclang_rt.asan_static.a

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


[clang] [RFC] [clang][Toolchain] Treat "pc"/"unknown" vendor interchangeable (PR #97802)

2024-07-05 Thread Azat Khuzhin via cfe-commits

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


[clang] [RFC] [clang][Toolchain] Treat "pc"/"unknown" vendor interchangeable (PR #97802)

2024-07-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Azat Khuzhin (azat)


Changes

Right now if you have runtime libraries under
lib/x86_64-unknown-linux-gnu you should use --target x86_64-unknown-linux-gnu, 
x86_64-pc-linux-gnu will not work.

Treat the interchangeable so that you can use any.

The initial reason for this patch is that debian packages uses 
x86_64-pc-linux-gnu, and after they enabled
LLVM_ENABLE_PER_TARGET_RUNTIME_DIR [1], clang cannot find runtime libraries for 
sanitizers.

  [1]: 
https://salsa.debian.org/pkg-llvm-team/llvm-toolchain/-/commit/9ca35f30383d89e4fdd45d15e0eb82c832df4b8c

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

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


2 Files Affected:

- (modified) clang/lib/Driver/ToolChain.cpp (+21) 
- (added) clang/test/Driver/pc-unknown-toolchain.c (+4) 


``diff
diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 977e08390800d7..716cbfb43232b6 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -765,6 +765,27 @@ ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
   if (auto Path = getPathForTriple(getTriple()))
 return *Path;
 
+  // Treat "pc" and "unknown" vendors interchangeable
+  switch (getTriple().getVendor())
+  {
+case Triple::UnknownVendor: {
+  llvm::Triple TripleFallback = Triple;
+  TripleFallback.setVendor(Triple::PC);
+  if (auto Path = getPathForTriple(TripleFallback))
+return *Path;
+  break;
+}
+case Triple::PC: {
+  llvm::Triple TripleFallback = Triple;
+  TripleFallback.setVendor(Triple::UnknownVendor);
+  if (auto Path = getPathForTriple(TripleFallback))
+return *Path;
+  break;
+}
+default:
+  break;
+  }
+
   // When building with per target runtime directories, various ways of naming
   // the Arm architecture may have been normalised to simply "arm".
   // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
diff --git a/clang/test/Driver/pc-unknown-toolchain.c 
b/clang/test/Driver/pc-unknown-toolchain.c
new file mode 100644
index 00..a7e9bb80b0f2d6
--- /dev/null
+++ b/clang/test/Driver/pc-unknown-toolchain.c
@@ -0,0 +1,4 @@
+// RUN: %clang -### %s -fsanitize=address --target=x86_64-pc-linux-gnu 2>&1 | 
FileCheck -check-prefix=CHECK-ASAN-PC %s
+// CHECK-ASAN-PC: x86_64-unknown-linux-gnu/libclang_rt.asan_static.a
+// RUN: %clang -### %s -fsanitize=address --target=x86_64-unknown-linux-gnu 
2>&1 | FileCheck -check-prefix=CHECK-ASAN-UNKNOWN %s
+// CHECK-ASAN-UNKNOWN: x86_64-unknown-linux-gnu/libclang_rt.asan_static.a

``




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


[clang] fbd7360 - [clang][Interp] Short-cirtuit Move/Copy constructors if we can

2024-07-05 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-07-05T11:29:32+02:00
New Revision: fbd736062e043d34cddd6031b4ee93954d4bf199

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

LOG: [clang][Interp] Short-cirtuit Move/Copy constructors if we can

Added: 


Modified: 
clang/lib/AST/Interp/Compiler.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Compiler.cpp 
b/clang/lib/AST/Interp/Compiler.cpp
index 775cabf7f8c59..2fd20d8022126 100644
--- a/clang/lib/AST/Interp/Compiler.cpp
+++ b/clang/lib/AST/Interp/Compiler.cpp
@@ -2447,6 +2447,12 @@ bool Compiler::VisitCXXConstructExpr(const 
CXXConstructExpr *E) {
   if (T->isRecordType()) {
 const CXXConstructorDecl *Ctor = E->getConstructor();
 
+// Trivial copy/move constructor. Avoid copy.
+if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
+E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
+T->getAsCXXRecordDecl()))
+  return this->visitInitializer(E->getArg(0));
+
 // If we're discarding a construct expression, we still need
 // to allocate a variable and call the constructor and destructor.
 if (DiscardResult) {



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


[clang] [RFC] [clang][Toolchain] Treat "pc"/"unknown" vendor interchangeable (PR #97802)

2024-07-05 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 687531fbed080b86c31144bf66c29f4a30e10e84 
dd290ddc48fd60d29e2c0eb839f9e9a08746d5f2 -- 
clang/test/Driver/pc-unknown-toolchain.c clang/lib/Driver/ToolChain.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 716cbfb432..43ec3c234b 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -766,24 +766,23 @@ ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
 return *Path;
 
   // Treat "pc" and "unknown" vendors interchangeable
-  switch (getTriple().getVendor())
-  {
-case Triple::UnknownVendor: {
-  llvm::Triple TripleFallback = Triple;
-  TripleFallback.setVendor(Triple::PC);
-  if (auto Path = getPathForTriple(TripleFallback))
-return *Path;
-  break;
-}
-case Triple::PC: {
-  llvm::Triple TripleFallback = Triple;
-  TripleFallback.setVendor(Triple::UnknownVendor);
-  if (auto Path = getPathForTriple(TripleFallback))
-return *Path;
-  break;
-}
-default:
-  break;
+  switch (getTriple().getVendor()) {
+  case Triple::UnknownVendor: {
+llvm::Triple TripleFallback = Triple;
+TripleFallback.setVendor(Triple::PC);
+if (auto Path = getPathForTriple(TripleFallback))
+  return *Path;
+break;
+  }
+  case Triple::PC: {
+llvm::Triple TripleFallback = Triple;
+TripleFallback.setVendor(Triple::UnknownVendor);
+if (auto Path = getPathForTriple(TripleFallback))
+  return *Path;
+break;
+  }
+  default:
+break;
   }
 
   // When building with per target runtime directories, various ways of naming

``




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


[clang] [RFC] [clang][Toolchain] Treat "pc"/"unknown" vendor interchangeable (PR #97802)

2024-07-05 Thread Azat Khuzhin via cfe-commits

https://github.com/azat updated https://github.com/llvm/llvm-project/pull/97802

>From c2d4c4649004262569a7f1d17077ebd48bb35269 Mon Sep 17 00:00:00 2001
From: Azat Khuzhin 
Date: Fri, 5 Jul 2024 11:15:15 +0200
Subject: [PATCH] [clang][Toolchain] Treat "pc"/"unknown" vendor
 interchangeable

Right now if you have runtime libraries under
lib/x86_64-unknown-linux-gnu you should use --target
x86_64-unknown-linux-gnu, x86_64-pc-linux-gnu will not work.

Treat the interchangeable so that you can use any.

The initial reason for this patch is that debian packages uses
x86_64-pc-linux-gnu, and after they enabled
LLVM_ENABLE_PER_TARGET_RUNTIME_DIR [1], clang cannot find runtime
libraries for sanitizers.

  [1]: 
https://salsa.debian.org/pkg-llvm-team/llvm-toolchain/-/commit/9ca35f30383d89e4fdd45d15e0eb82c832df4b8c
---
 clang/lib/Driver/ToolChain.cpp   | 20 
 clang/test/Driver/pc-unknown-toolchain.c |  4 
 2 files changed, 24 insertions(+)
 create mode 100644 clang/test/Driver/pc-unknown-toolchain.c

diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 977e08390800d..43ec3c234ba14 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -765,6 +765,26 @@ ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
   if (auto Path = getPathForTriple(getTriple()))
 return *Path;
 
+  // Treat "pc" and "unknown" vendors interchangeable
+  switch (getTriple().getVendor()) {
+  case Triple::UnknownVendor: {
+llvm::Triple TripleFallback = Triple;
+TripleFallback.setVendor(Triple::PC);
+if (auto Path = getPathForTriple(TripleFallback))
+  return *Path;
+break;
+  }
+  case Triple::PC: {
+llvm::Triple TripleFallback = Triple;
+TripleFallback.setVendor(Triple::UnknownVendor);
+if (auto Path = getPathForTriple(TripleFallback))
+  return *Path;
+break;
+  }
+  default:
+break;
+  }
+
   // When building with per target runtime directories, various ways of naming
   // the Arm architecture may have been normalised to simply "arm".
   // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
diff --git a/clang/test/Driver/pc-unknown-toolchain.c 
b/clang/test/Driver/pc-unknown-toolchain.c
new file mode 100644
index 0..a7e9bb80b0f2d
--- /dev/null
+++ b/clang/test/Driver/pc-unknown-toolchain.c
@@ -0,0 +1,4 @@
+// RUN: %clang -### %s -fsanitize=address --target=x86_64-pc-linux-gnu 2>&1 | 
FileCheck -check-prefix=CHECK-ASAN-PC %s
+// CHECK-ASAN-PC: x86_64-unknown-linux-gnu/libclang_rt.asan_static.a
+// RUN: %clang -### %s -fsanitize=address --target=x86_64-unknown-linux-gnu 
2>&1 | FileCheck -check-prefix=CHECK-ASAN-UNKNOWN %s
+// CHECK-ASAN-UNKNOWN: x86_64-unknown-linux-gnu/libclang_rt.asan_static.a

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


[clang] [clang] Add C++26 diagnostics to compatibility diagnosic groups (PR #97806)

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

https://github.com/Endilll created 
https://github.com/llvm/llvm-project/pull/97806

This patch adds `CXXPre26Compat` and `CXXPre26CompatPedantic` groups (which are 
concerned with new features not available in older language modes) to 
`CXX98Compat`, etc. This way, if user has `-Wc++20-compat` and they use pack 
indexing, they will be warned.

Ideally this should have been done when C++26 groups were created, but we 
shipped 2 releases of Clang since then.

>From b855fe1b301a156ea45caa4b6fd6eca1c69d5cf5 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Fri, 5 Jul 2024 12:39:13 +0300
Subject: [PATCH] [clang] Add C++26 diagnostics to compatibility diagnosic
 groups

---
 clang/docs/ReleaseNotes.rst   |  4 +++
 clang/include/clang/Basic/DiagnosticGroups.td | 30 ---
 2 files changed, 24 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 36cf615a4287cc..cf1b529eb73210 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -476,6 +476,10 @@ Modified Compiler Flags
   evaluating to ``true`` and an empty body such as ``while(1);``)
   are considered infinite, even when the ``-ffinite-loop`` flag is set.
 
+- Diagnostics groups about compatibility with a particular C++ Standard version
+  now include dianostics about C++26 features that are not present in older
+  versions.
+
 Removed Compiler Flags
 -
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 9431eea1f6be22..a4496431e46e4c 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -344,7 +344,8 @@ def CXX98Compat : DiagGroup<"c++98-compat",
  CXXPre14Compat,
  CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 // Warnings for C++11 features which are Extensions in C++98 mode.
 def CXX98CompatPedantic : DiagGroup<"c++98-compat-pedantic",
 [CXX98Compat,
@@ -353,7 +354,8 @@ def CXX98CompatPedantic : DiagGroup<"c++98-compat-pedantic",
  CXXPre14CompatPedantic,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX11NarrowingConstReference : 
DiagGroup<"c++11-narrowing-const-reference">;
 def CXX11Narrowing : DiagGroup<"c++11-narrowing", 
[CXX11NarrowingConstReference]>;
@@ -384,39 +386,47 @@ def CXX11Compat : DiagGroup<"c++11-compat",
  CXXPre14Compat,
  CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def : DiagGroup<"c++0x-compat", [CXX11Compat]>;
 def CXX11CompatPedantic : DiagGroup<"c++11-compat-pedantic",
 [CXX11Compat,
  CXXPre14CompatPedantic,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX14Compat : DiagGroup<"c++14-compat", [CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX14CompatPedantic : DiagGroup<"c++14-compat-pedantic",
 [CXX14Compat,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX17Compat : DiagGroup<"c++17-compat", [DeprecatedRegister,
  DeprecatedIncrementBool,
  CXX17CompatMangling,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX17CompatPedantic : DiagGroup<"c++17

[clang] [clang] Add C++26 diagnostics to compatibility diagnosic groups (PR #97806)

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

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


[clang] [clang] Add C++26 diagnostics to compatibility diagnosic groups (PR #97806)

2024-07-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

This patch adds `CXXPre26Compat` and `CXXPre26CompatPedantic` groups (which are 
concerned with new features not available in older language modes) to 
`CXX98Compat`, etc. This way, if user has `-Wc++20-compat` and they use pack 
indexing, they will be warned.

Ideally this should have been done when C++26 groups were created, but we 
shipped two releases of Clang since then.

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


2 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+4) 
- (modified) clang/include/clang/Basic/DiagnosticGroups.td (+20-10) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 36cf615a4287c..cf1b529eb7321 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -476,6 +476,10 @@ Modified Compiler Flags
   evaluating to ``true`` and an empty body such as ``while(1);``)
   are considered infinite, even when the ``-ffinite-loop`` flag is set.
 
+- Diagnostics groups about compatibility with a particular C++ Standard version
+  now include dianostics about C++26 features that are not present in older
+  versions.
+
 Removed Compiler Flags
 -
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 9431eea1f6be2..a4496431e46e4 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -344,7 +344,8 @@ def CXX98Compat : DiagGroup<"c++98-compat",
  CXXPre14Compat,
  CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 // Warnings for C++11 features which are Extensions in C++98 mode.
 def CXX98CompatPedantic : DiagGroup<"c++98-compat-pedantic",
 [CXX98Compat,
@@ -353,7 +354,8 @@ def CXX98CompatPedantic : DiagGroup<"c++98-compat-pedantic",
  CXXPre14CompatPedantic,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX11NarrowingConstReference : 
DiagGroup<"c++11-narrowing-const-reference">;
 def CXX11Narrowing : DiagGroup<"c++11-narrowing", 
[CXX11NarrowingConstReference]>;
@@ -384,39 +386,47 @@ def CXX11Compat : DiagGroup<"c++11-compat",
  CXXPre14Compat,
  CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def : DiagGroup<"c++0x-compat", [CXX11Compat]>;
 def CXX11CompatPedantic : DiagGroup<"c++11-compat-pedantic",
 [CXX11Compat,
  CXXPre14CompatPedantic,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX14Compat : DiagGroup<"c++14-compat", [CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX14CompatPedantic : DiagGroup<"c++14-compat-pedantic",
 [CXX14Compat,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX17Compat : DiagGroup<"c++17-compat", [DeprecatedRegister,
  DeprecatedIncrementBool,
  CXX17CompatMangling,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX17CompatPedantic : DiagGroup<"c++17-compat-pedantic",
 [CXX17Compat,
  CXXPre20CompatPedantic,
- CXX

[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

2024-07-05 Thread via cfe-commits

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

LGTM. 

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


[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

2024-07-05 Thread via cfe-commits

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


[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

2024-07-05 Thread via cfe-commits


@@ -647,6 +647,8 @@ Improvements to Clang's diagnostics
 
 - Clang now shows implicit deduction guides when diagnosing overload 
resolution failure. #GH92393.
 
+- Clang now emits ``-Wnewline-eof`` when the last newline is deleted by a 
preceding backslash. #GH41571.

cor3ntin wrote:

```suggestion
- Clang now emits ``-Wnewline-eof`` when the last newline follows a splicing 
backslash . #GH41571.
```

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


[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

2024-07-05 Thread via cfe-commits


@@ -3183,8 +3193,35 @@ bool Lexer::LexEndOfFile(Token &Result, const char 
*CurPtr) {
   DiagID = diag::ext_no_newline_eof;
 }
 
-Diag(BufferEnd, DiagID)
-  << FixItHint::CreateInsertion(EndLoc, "\n");
+if (LastNewline.empty()) {
+  Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n");
+} else {
+  // While the file physically ends in a newline, the previous
+  // line might have ended in a splice, so it would be deleted
+  StringRef WithoutLastNewline =
+  StringRef(BufferStart, LastNewline.data() - BufferStart);
+  while (!WithoutLastNewline.empty()) {
+if (isHorizontalWhitespace(WithoutLastNewline.back())) {
+  WithoutLastNewline = WithoutLastNewline.drop_back();
+} else {
+  break;
+}
+  }
+
+  if (WithoutLastNewline.ends_with('\\') ||
+  (LangOpts.Trigraphs && WithoutLastNewline.ends_with("??"
+  "/"))) {

cor3ntin wrote:

Very weird formatting here (please make "??/" a single string)

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


[clang] [llvm] [Inliner] Propagate more attributes to params when inlining (PR #91101)

2024-07-05 Thread Antonio Frighetto via cfe-commits

https://github.com/antoniofrighetto commented:

I think this makes sense.

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


[clang] [clang] Add C++26 diagnostics to compatibility diagnosic groups (PR #97806)

2024-07-05 Thread via cfe-commits


@@ -384,39 +386,47 @@ def CXX11Compat : DiagGroup<"c++11-compat",
  CXXPre14Compat,
  CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def : DiagGroup<"c++0x-compat", [CXX11Compat]>;
 def CXX11CompatPedantic : DiagGroup<"c++11-compat-pedantic",
 [CXX11Compat,
  CXXPre14CompatPedantic,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX14Compat : DiagGroup<"c++14-compat", [CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX14CompatPedantic : DiagGroup<"c++14-compat-pedantic",
 [CXX14Compat,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX17Compat : DiagGroup<"c++17-compat", [DeprecatedRegister,
  DeprecatedIncrementBool,
  CXX17CompatMangling,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX17CompatPedantic : DiagGroup<"c++17-compat-pedantic",
 [CXX17Compat,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 def : DiagGroup<"c++1z-compat", [CXX17Compat]>;
 
-def CXX20Compat : DiagGroup<"c++20-compat", [CXXPre23Compat]>;
+def CXX20Compat : DiagGroup<"c++20-compat", [CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX20CompatPedantic : DiagGroup<"c++20-compat-pedantic",
 [CXX20Compat,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;

cor3ntin wrote:

We don't have a CXX23Compat group?

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


[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)

2024-07-05 Thread via cfe-commits

cor3ntin wrote:

Still missing a change to cxx_status.html

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


[clang] 6fbd26b - [clang][Interp] Add QualType parameter to Pointer::toRValue

2024-07-05 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-07-05T11:58:04+02:00
New Revision: 6fbd26b147ab93da4d0689ea2f6ff73cc9859cb8

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

LOG: [clang][Interp] Add QualType parameter to Pointer::toRValue

This fixes the crash from #97302, but exposes an underlying problem.

Added: 


Modified: 
clang/lib/AST/Interp/EvalEmitter.cpp
clang/lib/AST/Interp/EvaluationResult.cpp
clang/lib/AST/Interp/EvaluationResult.h
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/Pointer.cpp
clang/lib/AST/Interp/Pointer.h

Removed: 




diff  --git a/clang/lib/AST/Interp/EvalEmitter.cpp 
b/clang/lib/AST/Interp/EvalEmitter.cpp
index d17151416b44b..5d20a0b8182a9 100644
--- a/clang/lib/AST/Interp/EvalEmitter.cpp
+++ b/clang/lib/AST/Interp/EvalEmitter.cpp
@@ -156,7 +156,8 @@ template <> bool EvalEmitter::emitRet(const 
SourceInfo &Info) {
 if (!Ptr.isConst() && Ptr.block()->getEvalID() != Ctx.getEvalID())
   return false;
 
-if (std::optional V = Ptr.toRValue(Ctx)) {
+if (std::optional V =
+Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
   EvalResult.setValue(*V);
 } else {
   return false;
@@ -186,7 +187,8 @@ bool EvalEmitter::emitRetValue(const SourceInfo &Info) {
   if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
 return false;
 
-  if (std::optional APV = Ptr.toRValue(S.getCtx())) {
+  if (std::optional APV =
+  Ptr.toRValue(S.getCtx(), EvalResult.getSourceType())) {
 EvalResult.setValue(*APV);
 return true;
   }
@@ -257,7 +259,8 @@ void EvalEmitter::updateGlobalTemporaries() {
   if (std::optional T = Ctx.classify(E->getType())) {
 TYPE_SWITCH(*T, { *Cached = Ptr.deref().toAPValue(); });
   } else {
-if (std::optional APV = Ptr.toRValue(Ctx))
+if (std::optional APV =
+Ptr.toRValue(Ctx, Temp->getTemporaryExpr()->getType()))
   *Cached = *APV;
   }
 }

diff  --git a/clang/lib/AST/Interp/EvaluationResult.cpp 
b/clang/lib/AST/Interp/EvaluationResult.cpp
index a62f3f635e6e0..d0d68f75dd803 100644
--- a/clang/lib/AST/Interp/EvaluationResult.cpp
+++ b/clang/lib/AST/Interp/EvaluationResult.cpp
@@ -43,7 +43,7 @@ std::optional EvaluationResult::toRValue() const {
 
   // We have a pointer and want an RValue.
   if (const auto *P = std::get_if(&Value))
-return P->toRValue(*Ctx);
+return P->toRValue(*Ctx, getSourceType());
   else if (const auto *FP = std::get_if(&Value)) // Nope
 return FP->toAPValue();
   llvm_unreachable("Unhandled lvalue kind");

diff  --git a/clang/lib/AST/Interp/EvaluationResult.h 
b/clang/lib/AST/Interp/EvaluationResult.h
index ecf2250074cc9..378f1ccdb0af4 100644
--- a/clang/lib/AST/Interp/EvaluationResult.h
+++ b/clang/lib/AST/Interp/EvaluationResult.h
@@ -100,6 +100,15 @@ class EvaluationResult final {
 
   bool checkFullyInitialized(InterpState &S, const Pointer &Ptr) const;
 
+  QualType getSourceType() const {
+if (const auto *D =
+dyn_cast_if_present(Source.dyn_cast()))
+  return D->getType();
+else if (const auto *E = Source.dyn_cast())
+  return E->getType();
+return QualType();
+  }
+
   /// Dump to stderr.
   void dump() const;
 

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 5d8362b4fa881..12143fbf50808 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1309,7 +1309,8 @@ inline bool InitGlobalTempComp(InterpState &S, CodePtr 
OpPC,
   S.SeenGlobalTemporaries.push_back(
   std::make_pair(P.getDeclDesc()->asExpr(), Temp));
 
-  if (std::optional APV = P.toRValue(S.getCtx())) {
+  if (std::optional APV =
+  P.toRValue(S.getCtx(), Temp->getTemporaryExpr()->getType())) {
 *Cached = *APV;
 return true;
   }

diff  --git a/clang/lib/AST/Interp/Pointer.cpp 
b/clang/lib/AST/Interp/Pointer.cpp
index d6603f91fb127..157892ea492f6 100644
--- a/clang/lib/AST/Interp/Pointer.cpp
+++ b/clang/lib/AST/Interp/Pointer.cpp
@@ -340,7 +340,9 @@ bool Pointer::hasSameArray(const Pointer &A, const Pointer 
&B) {
  A.getFieldDesc()->IsArray;
 }
 
-std::optional Pointer::toRValue(const Context &Ctx) const {
+std::optional Pointer::toRValue(const Context &Ctx,
+ QualType ResultType) const {
+  assert(!ResultType.isNull());
   // Method to recursively traverse composites.
   std::function Composite;
   Composite = [&Composite, &Ctx](QualType Ty, const Pointer &Ptr, APValue &R) {
@@ -483,13 +485,19 @@ std::optional Pointer::toRValue(const Context 
&Ctx) const {
 llvm_unreachable("invalid value to return");
   };
 
-  if (isZero())
-return APValue(static_cast(nullptr), CharUnits::Zero(), {}, false,
-   true);
-
-  if (isDu

[clang] [clang] Add C++26 diagnostics to compatibility diagnosic groups (PR #97806)

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


@@ -384,39 +386,47 @@ def CXX11Compat : DiagGroup<"c++11-compat",
  CXXPre14Compat,
  CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def : DiagGroup<"c++0x-compat", [CXX11Compat]>;
 def CXX11CompatPedantic : DiagGroup<"c++11-compat-pedantic",
 [CXX11Compat,
  CXXPre14CompatPedantic,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX14Compat : DiagGroup<"c++14-compat", [CXXPre17Compat,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX14CompatPedantic : DiagGroup<"c++14-compat-pedantic",
 [CXX14Compat,
  CXXPre17CompatPedantic,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 
 def CXX17Compat : DiagGroup<"c++17-compat", [DeprecatedRegister,
  DeprecatedIncrementBool,
  CXX17CompatMangling,
  CXXPre20Compat,
- CXXPre23Compat]>;
+ CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX17CompatPedantic : DiagGroup<"c++17-compat-pedantic",
 [CXX17Compat,
  CXXPre20CompatPedantic,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;
 def : DiagGroup<"c++1z-compat", [CXX17Compat]>;
 
-def CXX20Compat : DiagGroup<"c++20-compat", [CXXPre23Compat]>;
+def CXX20Compat : DiagGroup<"c++20-compat", [CXXPre23Compat,
+ CXXPre26Compat]>;
 def CXX20CompatPedantic : DiagGroup<"c++20-compat-pedantic",
 [CXX20Compat,
- CXXPre23CompatPedantic]>;
+ CXXPre23CompatPedantic,
+ CXXPre26CompatPedantic]>;

Endilll wrote:

This is correct.

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


[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)

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

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/97733

>From f009148063ba41d39fc844f4432ceb51377f381c Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Thu, 4 Jul 2024 17:05:11 +0300
Subject: [PATCH 1/3] [clang] Implement P3144R2 "Deleting a Pointer to an
 Incomplete Type Should be Ill-formed"

---
 .../clang/Basic/DiagnosticSemaKinds.td|  2 ++
 clang/lib/Sema/SemaExprCXX.cpp| 12 ++---
 clang/test/CXX/drs/cwg5xx.cpp | 22 +---
 clang/test/SemaCXX/new-delete.cpp | 26 ---
 4 files changed, 41 insertions(+), 21 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 3df64b2ecef1b2..5c3e311ac63829 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7991,6 +7991,8 @@ def err_ambiguous_delete_operand : Error<
 def warn_delete_incomplete : Warning<
   "deleting pointer to incomplete type %0 may cause undefined behavior">,
   InGroup;
+def err_delete_incomplete : Error<
+  "cannot delete pointer to incomplete type %0">;
 def err_delete_incomplete_class_type : Error<
   "deleting incomplete class type %0; no conversions to pointer type">;
 def err_delete_explicit_conversion : Error<
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 69074f92a0286b..fcf2189a308a86 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -3719,8 +3719,11 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool 
UseGlobal,
   // The C++ standard bans deleting a pointer to a non-object type, which
   // effectively bans deletion of "void*". However, most compilers support
   // this, so we treat it as a warning unless we're in a SFINAE context.
-  Diag(StartLoc, diag::ext_delete_void_ptr_operand)
-<< Type << Ex.get()->getSourceRange();
+  // But we still prohibit this since C++26.
+  Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
+  : diag::ext_delete_void_ptr_operand)
+  << (LangOpts.CPlusPlus26 ? Pointee : Type)
+  << Ex.get()->getSourceRange();
 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
Pointee->isSizelessType()) {
   return ExprError(Diag(StartLoc, diag::err_delete_operand)
@@ -3729,7 +3732,10 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool 
UseGlobal,
   // FIXME: This can result in errors if the definition was imported from a
   // module but is hidden.
   if (!RequireCompleteType(StartLoc, Pointee,
-   diag::warn_delete_incomplete, Ex.get())) {
+   LangOpts.CPlusPlus26
+   ? diag::err_delete_incomplete
+   : diag::warn_delete_incomplete,
+   Ex.get())) {
 if (const RecordType *RT = PointeeElem->getAs())
   PointeeRD = cast(RT->getDecl());
   }
diff --git a/clang/test/CXX/drs/cwg5xx.cpp b/clang/test/CXX/drs/cwg5xx.cpp
index 9d890f981348a7..6a0bb7a1966693 100644
--- a/clang/test/CXX/drs/cwg5xx.cpp
+++ b/clang/test/CXX/drs/cwg5xx.cpp
@@ -1,9 +1,10 @@
-// RUN: %clang_cc1 -std=c++98 %s 
-verify=expected,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions -fcxx-exceptions 
-pedantic-errors
-// RUN: %clang_cc1 -std=c++11 %s 
-verify=expected,cxx98-11,cxx98-14,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
-// RUN: %clang_cc1 -std=c++14 %s 
-verify=expected,cxx98-14,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions 
-pedantic-errors
-// RUN: %clang_cc1 -std=c++17 %s 
-verify=expected,since-cxx17,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions 
-pedantic-errors
-// RUN: %clang_cc1 -std=c++20 %s 
-verify=expected,since-cxx20,since-cxx17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
-// RUN: %clang_cc1 -std=c++23 %s 
-verify=expected,since-cxx23,since-cxx20,since-cxx17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++98 %s 
-verify=expected,cxx98-23,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 %s 
-verify=expected,cxx98-23,cxx98-11,cxx98-14,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++14 %s 
-verify=expected,cxx98-23,cxx98-14,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++17 %s 
-verify=expected,cxx98-23,since-cxx17,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++20 %s 
-verify=expected,cxx98-23,since-cxx20,since-cxx17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++23 %s 
-verify=expected,cxx98-23,since-cxx23,since-cxx20,since-cxx17,since-cxx11 
-fexceptions -fcx

[clang] [RFC] [clang][Toolchain] Treat "pc"/"unknown" vendor interchangeable (PR #97802)

2024-07-05 Thread via cfe-commits

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


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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

2024-07-05 Thread Nathan James via cfe-commits

https://github.com/njames93 updated 
https://github.com/llvm/llvm-project/pull/97764

>From dd529ead075012e4c74ff54fb534e1f34efe0c7f Mon Sep 17 00:00:00 2001
From: Nathan James 
Date: Tue, 2 Jul 2024 14:25:44 +0100
Subject: [PATCH 1/2] Add a modernize-use-ranges check

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/ModernizeTidyModule.cpp |   2 +
 .../clang-tidy/modernize/UseRangesCheck.cpp   | 151 +++
 .../clang-tidy/modernize/UseRangesCheck.h |  31 +++
 .../clang-tidy/utils/CMakeLists.txt   |   1 +
 .../clang-tidy/utils/UseRangesCheck.cpp   | 248 ++
 .../clang-tidy/utils/UseRangesCheck.h |  68 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../checks/modernize/use-ranges.rst   |  33 +++
 .../checkers/modernize/use-ranges.cpp | 183 +
 11 files changed, 725 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseRangesCheck.h
 create mode 100644 clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/utils/UseRangesCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-ranges.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 576805c4c7f18..4f68c487cac9d 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -40,6 +40,7 @@ add_clang_library(clangTidyModernizeModule
   UseNoexceptCheck.cpp
   UseNullptrCheck.cpp
   UseOverrideCheck.cpp
+  UseRangesCheck.cpp
   UseStartsEndsWithCheck.cpp
   UseStdFormatCheck.cpp
   UseStdNumbersCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index b9c7a2dc383e8..1860759332063 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -41,6 +41,7 @@
 #include "UseNoexceptCheck.h"
 #include "UseNullptrCheck.h"
 #include "UseOverrideCheck.h"
+#include "UseRangesCheck.h"
 #include "UseStartsEndsWithCheck.h"
 #include "UseStdFormatCheck.h"
 #include "UseStdNumbersCheck.h"
@@ -75,6 +76,7 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck("modernize-pass-by-value");
 CheckFactories.registerCheck(
 "modernize-use-designated-initializers");
+CheckFactories.registerCheck("modernize-use-ranges");
 CheckFactories.registerCheck(
 "modernize-use-starts-ends-with");
 
CheckFactories.registerCheck("modernize-use-std-format");
diff --git a/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
new file mode 100644
index 0..84183046d4705
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
@@ -0,0 +1,151 @@
+//===--- UseRangesCheck.cpp - clang-tidy 
--===//
+//
+// 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 "UseRangesCheck.h"
+#include "clang/AST/Decl.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace clang::tidy::modernize {
+
+utils::UseRangesCheck::ReplacerMap UseRangesCheck::getReplacerMap() const {
+  class StdReplacer : public utils::UseRangesCheck::Replacer {
+  public:
+explicit StdReplacer(SmallVector Indexes)
+: Indexes(std::move(Indexes)) {}
+std::string getReplaceName(const NamedDecl &OriginalName) const override {
+  return ("std::ranges::" + OriginalName.getName()).str();
+}
+ArrayRef getReplacementSignatures() const 
override {
+  return Indexes;
+}
+std::optional
+getHeaderInclusion(const NamedDecl & /*OriginalName*/) const override {
+  return "";
+}
+
+  private:
+SmallVector Indexes;
+  };
+
+  utils::UseRangesCheck::ReplacerMap Result;
+  
+  // template Func(Iter first, Iter last,...).
+  static const Signature SingleRangeArgs = {{0}};
+  // template
+  // Func(Policy policy, Iter first, // Iter last,...).
+  static const Signature SingleRangeExecPolicy = {{1}};
+  // template
+  // Func(Iter1 first1, Iter1 last1, Iter2 first2, Iter2 last2,...).
+  static const Signature TwoRangeArgs = {{0}, {2}};
+  // template
+  // Func(Policy policy, Iter1 first1, Iter1 last1, Iter2 first2, Iter2

[clang] [llvm] [X86][CodeGen] security check cookie execute only when needed (PR #95904)

2024-07-05 Thread Simon Pilgrim via cfe-commits

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

LGTM

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

2024-07-05 Thread Nathan James via cfe-commits


@@ -0,0 +1,253 @@
+//===--- UseRangesCheck.cpp - clang-tidy 
--===//
+//
+// 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 "UseRangesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallBitVector.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+static constexpr const char BoundCall[] = "CallExpr";
+static constexpr const char FuncDecl[] = "FuncDecl";
+static constexpr const char ArgName[] = "ArgName";
+
+namespace clang::tidy::utils {
+
+static bool operator==(const UseRangesCheck::Replacer::Indexes &L,
+   const UseRangesCheck::Replacer::Indexes &R) {
+  return std::tie(L.BeginArg, L.EndArg, L.ReplaceArg) ==
+ std::tie(R.BeginArg, R.EndArg, R.ReplaceArg);
+}
+
+std::string
+getFullPrefix(ArrayRef Signature) {
+  std::string Output;
+  llvm::raw_string_ostream OS(Output);
+  for (auto Item : Signature) {
+OS << Item.BeginArg << ":" << Item.EndArg << ":"
+   << (Item.ReplaceArg == Item.First ? '0' : '1');
+  }
+  return Output;
+}
+
+static llvm::hash_code hash_value(const UseRangesCheck::Replacer::Indexes &L) {
+  return llvm::hash_combine(L.BeginArg, L.EndArg, L.ReplaceArg);
+}
+
+namespace {
+
+AST_MATCHER(Expr, hasSideEffects) {
+  return Node.HasSideEffects(Finder->getASTContext());
+}
+
+AST_MATCHER_P(Expr, isEquivalentToBound, std::string, Other) {
+  llvm::FoldingSetNodeID NodeRepr;
+  Node.Profile(NodeRepr, Finder->getASTContext(), true);
+  return Builder->removeBindings(
+  [this, &Finder,
+   &NodeRepr](const ast_matchers::internal::BoundNodesMap &Nodes) {
+auto BoundNode = Nodes.getNodeAs(Other);
+if (!BoundNode)
+  return true;
+llvm::FoldingSetNodeID BoundRepr;
+BoundNode->Profile(BoundRepr, Finder->getASTContext(), true);
+return BoundRepr != NodeRepr;
+  });
+}
+} // namespace
+
+static auto makeMatcher(bool IsBegin, StringRef Prefix) {
+  auto Member =
+  IsBegin ? expr(unless(hasSideEffects())).bind((ArgName + Prefix).str())
+  : expr(isEquivalentToBound((ArgName + Prefix).str()));
+  return expr(
+  anyOf(cxxMemberCallExpr(
+callee(cxxMethodDecl(IsBegin ? hasAnyName("begin", "cbegin")
+ : hasAnyName("end", "cend"))),
+on(Member)),
+callExpr(argumentCountIs(1), hasArgument(0, Member),
+ hasDeclaration(functionDecl(
+ IsBegin ? hasAnyName("::std::begin", "::std::cbegin")
+ : hasAnyName("::std::end", 
"::std::cend"));
+}
+static ast_matchers::internal::Matcher
+makeMatcherPair(StringRef State,
+const UseRangesCheck::Replacer::Indexes &Indexes) {
+  auto ArgPostfix = std::to_string(Indexes.BeginArg);
+  SmallString<64> ID = {BoundCall, State};
+  return callExpr(argumentCountAtLeast(
+  std::max(Indexes.BeginArg, Indexes.EndArg) + 1),
+  hasArgument(Indexes.BeginArg, makeMatcher(true, ArgPostfix)),
+  hasArgument(Indexes.EndArg, makeMatcher(false, ArgPostfix)))
+  .bind(ID);
+}
+
+void UseRangesCheck::registerMatchers(MatchFinder *Finder) {
+  Replaces = GetReplacerMap();
+  llvm::DenseSet>> Seen;
+  for (auto I = Replaces.begin(), E = Replaces.end(); I != E; ++I) {
+const auto &Replacer = I->getValue();
+const auto &Signatures = Replacer->getReplacementSignatures();
+if (Seen.contains(Signatures))
+  continue;
+assert(!Signatures.empty() &&
+   llvm::all_of(Signatures, [](auto index) { return !index.empty(); 
}));
+std::vector Names(1, I->getKey());
+for (auto J = std::next(I); J != E; ++J) {
+  if (J->getValue()->getReplacementSignatures() == Signatures) {
+Names.push_back(J->getKey());
+  }
+}
+std::vector TotalMatchers;
+// As we match on the first matched signature, we need to ensure that any
+SmallVector> SigVec(Signatures);
+llvm::sort(SigVec, [](auto &L, auto &R) { return R.size() < L.size(); });
+for (const auto &Signature : SigVec) {
+  std::vector Matche

[clang] f926e19 - Reapply "[clang][Interp] Fix init chain in local initializers"

2024-07-05 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-07-05T12:16:18+02:00
New Revision: f926e19aa9c0bdca3f05322e1b62562a9a3a05e2

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

LOG: Reapply "[clang][Interp] Fix init chain in local initializers"

This reverts commit 2dda8a2650927e4b0fbb459507684455e196d9a9.

Added: 


Modified: 
clang/lib/AST/Interp/Compiler.cpp
clang/lib/AST/Interp/Compiler.h
clang/lib/AST/Interp/EvalEmitter.cpp
clang/lib/AST/Interp/Pointer.h
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Compiler.cpp 
b/clang/lib/AST/Interp/Compiler.cpp
index 2fd20d8022126..2ada68f6bc756 100644
--- a/clang/lib/AST/Interp/Compiler.cpp
+++ b/clang/lib/AST/Interp/Compiler.cpp
@@ -85,8 +85,12 @@ bool InitLink::emit(Compiler *Ctx, const Expr *E) 
const {
   case K_Field:
 // We're assuming there's a base pointer on the stack already.
 return Ctx->emitGetPtrFieldPop(Offset, E);
+  case K_Temp:
+return Ctx->emitGetPtrLocal(Offset, E);
   case K_Decl:
 return Ctx->visitDeclRef(D, E);
+  default:
+llvm_unreachable("Unhandled InitLink kind");
   }
   return true;
 }
@@ -1330,6 +1334,7 @@ bool Compiler::visitInitList(ArrayRef Inits,
 
 auto initCompositeField = [=](const Record::Field *FieldToInit,
   const Expr *Init) -> bool {
+  InitLinkScope ILS(this, InitLink::Field(FieldToInit->Offset));
   // Non-primitive case. Get a pointer to the field-to-initialize
   // on the stack and recurse into visitInitializer().
   if (!this->emitGetPtrField(FieldToInit->Offset, Init))
@@ -2271,6 +2276,7 @@ bool Compiler::VisitMaterializeTemporaryExpr(
 const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();
 if (std::optional LocalIndex =
 allocateLocal(Inner, E->getExtendingDecl())) {
+  InitLinkScope ILS(this, InitLink::Temp(*LocalIndex));
   if (!this->emitGetPtrLocal(*LocalIndex, E))
 return false;
   return this->visitInitializer(SubExpr);
@@ -2449,6 +2455,7 @@ bool Compiler::VisitCXXConstructExpr(const 
CXXConstructExpr *E) {
 
 // Trivial copy/move constructor. Avoid copy.
 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
+Ctor->isTrivial() &&
 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
 T->getAsCXXRecordDecl()))
   return this->visitInitializer(E->getArg(0));
@@ -3583,6 +3590,7 @@ VarCreationState Compiler::visitVarDecl(const 
VarDecl *VD, bool Topleve
 return !Init || (checkDecl() && initGlobal(*GlobalIndex));
   } else {
 VariableScope LocalScope(this, VD);
+InitLinkScope ILS(this, InitLink::Decl(VD));
 
 if (VarT) {
   unsigned Offset = this->allocateLocalPrimitive(
@@ -3917,7 +3925,8 @@ bool Compiler::VisitCXXDefaultInitExpr(const 
CXXDefaultInitExpr *E) {
   SourceLocScope SLS(this, E);
 
   bool Old = InitStackActive;
-  InitStackActive = !isa(E->getUsedContext());
+  InitStackActive =
+  !(E->getUsedContext()->getDeclKind() == Decl::CXXConstructor);
   bool Result = this->delegate(E->getExpr());
   InitStackActive = Old;
   return Result;
@@ -3979,8 +3988,14 @@ bool Compiler::VisitCXXThisExpr(const 
CXXThisExpr *E) {
   // currently being initialized. Here we emit the necessary instruction(s) for
   // this scenario.
   if (InitStackActive && !InitStack.empty()) {
-for (const InitLink &IL : InitStack) {
-  if (!IL.emit(this, E))
+unsigned StartIndex = 0;
+for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
+  if (InitStack[StartIndex].Kind != InitLink::K_Field)
+break;
+}
+
+for (unsigned I = StartIndex, N = InitStack.size(); I != N; ++I) {
+  if (!InitStack[I].emit(this, E))
 return false;
 }
 return true;

diff  --git a/clang/lib/AST/Interp/Compiler.h b/clang/lib/AST/Interp/Compiler.h
index d28526c76fe13..1405abfc1a1e2 100644
--- a/clang/lib/AST/Interp/Compiler.h
+++ b/clang/lib/AST/Interp/Compiler.h
@@ -47,7 +47,8 @@ struct InitLink {
   enum {
 K_This = 0,
 K_Field = 1,
-K_Decl = 2,
+K_Temp = 2,
+K_Decl = 3,
   };
 
   static InitLink This() { return InitLink{K_This}; }
@@ -56,6 +57,11 @@ struct InitLink {
 IL.Offset = Offset;
 return IL;
   }
+  static InitLink Temp(unsigned Offset) {
+InitLink IL{K_Temp};
+IL.Offset = Offset;
+return IL;
+  }
   static InitLink Decl(const ValueDecl *D) {
 InitLink IL{K_Decl};
 IL.D = D;
@@ -66,7 +72,6 @@ struct InitLink {
   template 
   bool emit(Compiler *Ctx, const Expr *E) const;
 
-private:
   uint32_t Kind;
   union {
 unsigned Offset;

diff  --git a/clang/lib/AST/Interp/EvalEmitter.cpp 
b/clang/lib/AST/Interp/EvalEmitter.cpp
index 5d20a0b8182a9..

[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

2024-07-05 Thread Nathan James via cfe-commits

https://github.com/njames93 updated 
https://github.com/llvm/llvm-project/pull/97764

>From ad55d54bf76a2b0a1544acb143446869135e224f Mon Sep 17 00:00:00 2001
From: Nathan James 
Date: Tue, 2 Jul 2024 14:25:44 +0100
Subject: [PATCH 1/2] Add a modernize-use-ranges check

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/ModernizeTidyModule.cpp |   2 +
 .../clang-tidy/modernize/UseRangesCheck.cpp   | 150 +++
 .../clang-tidy/modernize/UseRangesCheck.h |  31 +++
 .../clang-tidy/utils/CMakeLists.txt   |   1 +
 .../clang-tidy/utils/UseRangesCheck.cpp   | 248 ++
 .../clang-tidy/utils/UseRangesCheck.h |  68 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../checks/modernize/use-ranges.rst   |  33 +++
 .../checkers/modernize/use-ranges.cpp | 183 +
 11 files changed, 724 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseRangesCheck.h
 create mode 100644 clang-tools-extra/clang-tidy/utils/UseRangesCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/utils/UseRangesCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-ranges.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 576805c4c7f18..4f68c487cac9d 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -40,6 +40,7 @@ add_clang_library(clangTidyModernizeModule
   UseNoexceptCheck.cpp
   UseNullptrCheck.cpp
   UseOverrideCheck.cpp
+  UseRangesCheck.cpp
   UseStartsEndsWithCheck.cpp
   UseStdFormatCheck.cpp
   UseStdNumbersCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index b9c7a2dc383e8..1860759332063 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -41,6 +41,7 @@
 #include "UseNoexceptCheck.h"
 #include "UseNullptrCheck.h"
 #include "UseOverrideCheck.h"
+#include "UseRangesCheck.h"
 #include "UseStartsEndsWithCheck.h"
 #include "UseStdFormatCheck.h"
 #include "UseStdNumbersCheck.h"
@@ -75,6 +76,7 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck("modernize-pass-by-value");
 CheckFactories.registerCheck(
 "modernize-use-designated-initializers");
+CheckFactories.registerCheck("modernize-use-ranges");
 CheckFactories.registerCheck(
 "modernize-use-starts-ends-with");
 
CheckFactories.registerCheck("modernize-use-std-format");
diff --git a/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
new file mode 100644
index 0..3da00b56df9fc
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
@@ -0,0 +1,150 @@
+//===--- UseRangesCheck.cpp - clang-tidy 
--===//
+//
+// 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 "UseRangesCheck.h"
+#include "clang/AST/Decl.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace clang::tidy::modernize {
+
+utils::UseRangesCheck::ReplacerMap UseRangesCheck::getReplacerMap() const {
+  class StdReplacer : public utils::UseRangesCheck::Replacer {
+  public:
+explicit StdReplacer(SmallVector Indexes)
+: Indexes(std::move(Indexes)) {}
+std::string getReplaceName(const NamedDecl &OriginalName) const override {
+  return ("std::ranges::" + OriginalName.getName()).str();
+}
+ArrayRef
+getReplacementSignatures() const override {
+  return Indexes;
+}
+std::optional
+getHeaderInclusion(const NamedDecl & /*OriginalName*/) const override {
+  return "";
+}
+
+  private:
+SmallVector Indexes;
+  };
+
+  utils::UseRangesCheck::ReplacerMap Result;
+
+  // template Func(Iter first, Iter last,...).
+  static const Signature SingleRangeArgs = {{0}};
+  // template
+  // Func(Policy policy, Iter first, // Iter last,...).
+  static const Signature SingleRangeExecPolicy = {{1}};
+  // template
+  // Func(Iter1 first1, Iter1 last1, Iter2 first2, Iter2 last2,...).
+  static const Signature TwoRangeArgs = {{0}, {2}};
+  // template
+  // Func(Policy policy, Iter1 first1, Iter1 last1, Iter2 first2, Ite

[clang] [libcxx] [llvm] [mlir] [openmp] [CodeGen] Add dump() to MachineTraceMetrics.h (PR #97799)

2024-07-05 Thread Pengcheng Wang via cfe-commits

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


[clang] [libcxx] [llvm] [mlir] [openmp] [CodeGen] Add dump() to MachineTraceMetrics.h (PR #97799)

2024-07-05 Thread Pengcheng Wang via cfe-commits

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

2024-07-05 Thread Nathan James via cfe-commits


@@ -0,0 +1,24 @@
+.. title:: clang-tidy - modernize-use-ranges
+
+modernize-use-ranges
+
+
+Detects calls to standard library iterator algorithms that could be replaced
+with a ranges version instead
+

njames93 wrote:

I'm not sure how necessary a table of all the possible replacements this check 
supports is.
It sounds like adding that is just an extra maintenance burden.

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


[clang] [libclc] [llvm] [libclc] More cross compilation fixes (PR #97811)

2024-07-05 Thread Harald van Dijk via cfe-commits

https://github.com/hvdijk created 
https://github.com/llvm/llvm-project/pull/97811

* Move the setup_host_tool calls to the directories of their tool. Although it 
works to call it in libclc, it can only appear in a single location so it fails 
the "what if everyone did this?" test and causes problems for downstream code 
that also wants to use native versions of these tools from other projects.
* Correct the TARGET "${${tool}_target}" check. "${${tool}_target}" may be set 
to the path to the executable, which works in dependencies but cannot be tested 
using if(TARGET). For lack of a better alternative, just check that 
"${${tool}_target}" is non-empty and trust that if it is, it is set to a 
meaningful value. If somehow it turns out to be a valid target, its value will 
still show up in error messages anyway.
* Account for llvm-spirv possibly being provided in-tree. Per 
https://github.com/KhronosGroup/SPIRV-LLVM-Translator?tab=readme-ov-file#llvm-in-tree-build
 it is possible to drop llvm-spirv into LLVM and have it built as part of 
LLVM's build. In this configuration, cross builds of LLVM require a native 
version of llvm-spirv to be built. Note: having this work in cross builds also 
requires a change to SPIRV-LLVM-Translator.

>From 8c16c7d759cc9113e2c045c8b7a76cc61c19064a Mon Sep 17 00:00:00 2001
From: Harald van Dijk 
Date: Fri, 5 Jul 2024 11:24:45 +0100
Subject: [PATCH] [libclc] More cross compilation fixes

* Move the setup_host_tool calls to the directories of their tool.
  Although it works to call it in libclc, it can only appear in a single
  location so it fails the "what if everyone did this?" test and causes
  problems for downstream code that also wants to use native versions of
  these tools from other projects.
* Correct the TARGET "${${tool}_target}" check. "${${tool}_target}" may
  be set to the path to the executable, which works in dependencies but
  cannot be tested using if(TARGET). For lack of a better alternative,
  just check that "${${tool}_target}" is non-empty and trust that if it
  is, it is set to a meaningful value. If somehow it turns out to be a
  valid target, its value will still show up in error messages anyway.
* Account for llvm-spirv possibly being provided in-tree. Per
  
https://github.com/KhronosGroup/SPIRV-LLVM-Translator?tab=readme-ov-file#llvm-in-tree-build
  it is possible to drop llvm-spirv into LLVM and have it built as part
  of LLVM's build. In this configuration, cross builds of LLVM require a
  native version of llvm-spirv to be built. Note: having this work in
  cross builds also requires a change to SPIRV-LLVM-Translator.
---
 clang/tools/driver/CMakeLists.txt   |  2 ++
 libclc/CMakeLists.txt   | 30 +++--
 llvm/tools/llvm-as/CMakeLists.txt   |  2 ++
 llvm/tools/llvm-link/CMakeLists.txt |  2 ++
 llvm/tools/opt/CMakeLists.txt   |  2 ++
 5 files changed, 24 insertions(+), 14 deletions(-)

diff --git a/clang/tools/driver/CMakeLists.txt 
b/clang/tools/driver/CMakeLists.txt
index 290bf2a42536d..f9e71223f47c4 100644
--- a/clang/tools/driver/CMakeLists.txt
+++ b/clang/tools/driver/CMakeLists.txt
@@ -38,6 +38,8 @@ add_clang_tool(clang
   GENERATE_DRIVER
   )
 
+setup_host_tool(clang CLANG clang_exe clang_target)
+
 clang_target_link_libraries(clang
   PRIVATE
   clangBasic
diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index 4f5625ff94916..35136648d3591 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -73,10 +73,10 @@ else()
   endif()
 
   if( NOT EXISTS ${LIBCLC_CUSTOM_LLVM_TOOLS_BINARY_DIR} )
-setup_host_tool( clang CLANG clang_exe clang_target )
-setup_host_tool( llvm-as LLVM_AS llvm-as_exe llvm-as_target )
-setup_host_tool( llvm-link LLVM_LINK llvm-link_exe llvm-link_target )
-setup_host_tool( opt OPT opt_exe opt_target )
+get_host_tool_path( clang CLANG clang_exe clang_target )
+get_host_tool_path( llvm-as LLVM_AS llvm-as_exe llvm-as_target )
+get_host_tool_path( llvm-link LLVM_LINK llvm-link_exe llvm-link_target )
+get_host_tool_path( opt OPT opt_exe opt_target )
   endif()
 endif()
 
@@ -97,17 +97,19 @@ if( EXISTS ${LIBCLC_CUSTOM_LLVM_TOOLS_BINARY_DIR} )
 endif()
 
 foreach( tool IN ITEMS clang opt llvm-as llvm-link )
-  if( NOT EXISTS "${${tool}_exe}" AND NOT TARGET "${${tool}_target}" )
+  if( NOT EXISTS "${${tool}_exe}" AND "${tool}_target" STREQUAL "" )
 message( FATAL_ERROR "libclc toolchain incomplete - missing tool ${tool}!" 
)
   endif()
 endforeach()
 
 # llvm-spirv is an optional dependency, used to build spirv-* targets.
-find_program( LLVM_SPIRV llvm-spirv PATHS ${LLVM_TOOLS_BINARY_DIR} 
NO_DEFAULT_PATH )
-
-if( LLVM_SPIRV )
-  add_executable( libclc::llvm-spirv IMPORTED GLOBAL )
-  set_target_properties( libclc::llvm-spirv PROPERTIES IMPORTED_LOCATION 
${LLVM_SPIRV} )
+# It may be provided in-tree or externally.
+if( TARGET llvm-spirv )
+  get_host_tool_path( llvm-spirv LLVM_SPIRV llvm-spirv_exe llvm-spirv_target )
+else()
+  find_p

[clang] [libclc] [llvm] [libclc] More cross compilation fixes (PR #97811)

2024-07-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Harald van Dijk (hvdijk)


Changes

* Move the setup_host_tool calls to the directories of their tool. Although it 
works to call it in libclc, it can only appear in a single location so it fails 
the "what if everyone did this?" test and causes problems for downstream code 
that also wants to use native versions of these tools from other projects.
* Correct the TARGET "${${tool}_target}" check. "${${tool}_target}" may be set 
to the path to the executable, which works in dependencies but cannot be tested 
using if(TARGET). For lack of a better alternative, just check that 
"${${tool}_target}" is non-empty and trust that if it is, it is set to a 
meaningful value. If somehow it turns out to be a valid target, its value will 
still show up in error messages anyway.
* Account for llvm-spirv possibly being provided in-tree. Per 
https://github.com/KhronosGroup/SPIRV-LLVM-Translator?tab=readme-ov-file#llvm-in-tree-build
 it is possible to drop llvm-spirv into LLVM and have it built as part of 
LLVM's build. In this configuration, cross builds of LLVM require a native 
version of llvm-spirv to be built. Note: having this work in cross builds also 
requires a change to SPIRV-LLVM-Translator.

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


5 Files Affected:

- (modified) clang/tools/driver/CMakeLists.txt (+2) 
- (modified) libclc/CMakeLists.txt (+16-14) 
- (modified) llvm/tools/llvm-as/CMakeLists.txt (+2) 
- (modified) llvm/tools/llvm-link/CMakeLists.txt (+2) 
- (modified) llvm/tools/opt/CMakeLists.txt (+2) 


``diff
diff --git a/clang/tools/driver/CMakeLists.txt 
b/clang/tools/driver/CMakeLists.txt
index 290bf2a42536dd..f9e71223f47c4d 100644
--- a/clang/tools/driver/CMakeLists.txt
+++ b/clang/tools/driver/CMakeLists.txt
@@ -38,6 +38,8 @@ add_clang_tool(clang
   GENERATE_DRIVER
   )
 
+setup_host_tool(clang CLANG clang_exe clang_target)
+
 clang_target_link_libraries(clang
   PRIVATE
   clangBasic
diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index 4f5625ff949168..35136648d35917 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -73,10 +73,10 @@ else()
   endif()
 
   if( NOT EXISTS ${LIBCLC_CUSTOM_LLVM_TOOLS_BINARY_DIR} )
-setup_host_tool( clang CLANG clang_exe clang_target )
-setup_host_tool( llvm-as LLVM_AS llvm-as_exe llvm-as_target )
-setup_host_tool( llvm-link LLVM_LINK llvm-link_exe llvm-link_target )
-setup_host_tool( opt OPT opt_exe opt_target )
+get_host_tool_path( clang CLANG clang_exe clang_target )
+get_host_tool_path( llvm-as LLVM_AS llvm-as_exe llvm-as_target )
+get_host_tool_path( llvm-link LLVM_LINK llvm-link_exe llvm-link_target )
+get_host_tool_path( opt OPT opt_exe opt_target )
   endif()
 endif()
 
@@ -97,17 +97,19 @@ if( EXISTS ${LIBCLC_CUSTOM_LLVM_TOOLS_BINARY_DIR} )
 endif()
 
 foreach( tool IN ITEMS clang opt llvm-as llvm-link )
-  if( NOT EXISTS "${${tool}_exe}" AND NOT TARGET "${${tool}_target}" )
+  if( NOT EXISTS "${${tool}_exe}" AND "${tool}_target" STREQUAL "" )
 message( FATAL_ERROR "libclc toolchain incomplete - missing tool ${tool}!" 
)
   endif()
 endforeach()
 
 # llvm-spirv is an optional dependency, used to build spirv-* targets.
-find_program( LLVM_SPIRV llvm-spirv PATHS ${LLVM_TOOLS_BINARY_DIR} 
NO_DEFAULT_PATH )
-
-if( LLVM_SPIRV )
-  add_executable( libclc::llvm-spirv IMPORTED GLOBAL )
-  set_target_properties( libclc::llvm-spirv PROPERTIES IMPORTED_LOCATION 
${LLVM_SPIRV} )
+# It may be provided in-tree or externally.
+if( TARGET llvm-spirv )
+  get_host_tool_path( llvm-spirv LLVM_SPIRV llvm-spirv_exe llvm-spirv_target )
+else()
+  find_program( LLVM_SPIRV llvm-spirv PATHS ${LLVM_TOOLS_BINARY_DIR} 
NO_DEFAULT_PATH )
+  set( llvm-spirv_exe "${LLVM_SPIRV}" )
+  set( llvm-spirv_target )
 endif()
 
 # List of all targets. Note that some are added dynamically below.
@@ -130,7 +132,7 @@ endif()
 
 # spirv-mesa3d and spirv64-mesa3d targets can only be built with the (optional)
 # llvm-spirv external tool.
-if( TARGET libclc::llvm-spirv )
+if( llvm-spirv_exe )
   list( APPEND LIBCLC_TARGETS_ALL  spirv-mesa3d- spirv64-mesa3d- )
 endif()
 
@@ -143,7 +145,7 @@ list( SORT LIBCLC_TARGETS_TO_BUILD )
 # Verify that the user hasn't requested mesa3d targets without an available
 # llvm-spirv tool.
 if( "spirv-mesa3d-" IN_LIST LIBCLC_TARGETS_TO_BUILD OR "spirv64-mesa3d-" 
IN_LIST LIBCLC_TARGETS_TO_BUILD )
-  if( NOT TARGET libclc::llvm-spirv )
+  if( NOT llvm-spirv_exe )
 message( FATAL_ERROR "SPIR-V targets requested, but spirv-tools is not 
installed" )
   endif()
 endif()
@@ -401,8 +403,8 @@ foreach( t ${LIBCLC_TARGETS_TO_BUILD} )
 if( ARCH STREQUAL spirv OR ARCH STREQUAL spirv64 )
   set( spv_suffix ${arch_suffix}.spv )
   add_custom_command( OUTPUT ${spv_suffix}
-COMMAND libclc::llvm-spirv ${spvflags} -o ${spv_suffix} 
${builtins_link_lib}
-DEPENDS ${builtins_link_lib} ${builtins_link_lib_tgt}
+C

[clang] 2f0700a - [clang][Interp] Add a missing template keyword

2024-07-05 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-07-05T12:28:17+02:00
New Revision: 2f0700a84311d1a8b0fc12499fe9480ccbd188e9

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

LOG: [clang][Interp] Add a missing template keyword

This broke a buildbot:
https://lab.llvm.org/buildbot/#/builders/190/builds/1326

Added: 


Modified: 
clang/lib/AST/Interp/Compiler.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Compiler.cpp 
b/clang/lib/AST/Interp/Compiler.cpp
index 2ada68f6bc756..3d9a0358c5487 100644
--- a/clang/lib/AST/Interp/Compiler.cpp
+++ b/clang/lib/AST/Interp/Compiler.cpp
@@ -3995,7 +3995,7 @@ bool Compiler::VisitCXXThisExpr(const 
CXXThisExpr *E) {
 }
 
 for (unsigned I = StartIndex, N = InitStack.size(); I != N; ++I) {
-  if (!InitStack[I].emit(this, E))
+  if (!InitStack[I].template emit(this, E))
 return false;
 }
 return true;



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


[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)

2024-07-05 Thread via cfe-commits

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

LGTM, thanks

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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

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


@@ -0,0 +1,24 @@
+.. title:: clang-tidy - modernize-use-ranges
+
+modernize-use-ranges
+
+
+Detects calls to standard library iterator algorithms that could be replaced
+with a ranges version instead
+

PiotrZSL wrote:

Table/list anything, just so user would know what is actually being replaced by 
check.

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


[clang] [RFC] [clang][Toolchain] Treat "pc"/"unknown" vendor interchangeable (PR #97802)

2024-07-05 Thread Azat Khuzhin via cfe-commits

https://github.com/azat updated https://github.com/llvm/llvm-project/pull/97802

>From 1d78d8362a4a10c8d8c2d5a78171e3fb5774daef Mon Sep 17 00:00:00 2001
From: Azat Khuzhin 
Date: Fri, 5 Jul 2024 11:15:15 +0200
Subject: [PATCH] [clang][Toolchain] Treat "pc"/"unknown" vendor
 interchangeable

Right now if you have runtime libraries under
lib/x86_64-unknown-linux-gnu you should use --target
x86_64-unknown-linux-gnu, x86_64-pc-linux-gnu will not work.

Treat the interchangeable so that you can use any.

The initial reason for this patch is that debian packages uses
x86_64-pc-linux-gnu, and after they enabled
LLVM_ENABLE_PER_TARGET_RUNTIME_DIR [1], clang cannot find runtime
libraries for sanitizers.

  [1]: 
https://salsa.debian.org/pkg-llvm-team/llvm-toolchain/-/commit/9ca35f30383d89e4fdd45d15e0eb82c832df4b8c
---
 clang/lib/Driver/ToolChain.cpp   | 20 
 clang/test/Driver/pc-unknown-toolchain.c |  6 ++
 2 files changed, 26 insertions(+)
 create mode 100644 clang/test/Driver/pc-unknown-toolchain.c

diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 977e08390800d..43ec3c234ba14 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -765,6 +765,26 @@ ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
   if (auto Path = getPathForTriple(getTriple()))
 return *Path;
 
+  // Treat "pc" and "unknown" vendors interchangeable
+  switch (getTriple().getVendor()) {
+  case Triple::UnknownVendor: {
+llvm::Triple TripleFallback = Triple;
+TripleFallback.setVendor(Triple::PC);
+if (auto Path = getPathForTriple(TripleFallback))
+  return *Path;
+break;
+  }
+  case Triple::PC: {
+llvm::Triple TripleFallback = Triple;
+TripleFallback.setVendor(Triple::UnknownVendor);
+if (auto Path = getPathForTriple(TripleFallback))
+  return *Path;
+break;
+  }
+  default:
+break;
+  }
+
   // When building with per target runtime directories, various ways of naming
   // the Arm architecture may have been normalised to simply "arm".
   // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
diff --git a/clang/test/Driver/pc-unknown-toolchain.c 
b/clang/test/Driver/pc-unknown-toolchain.c
new file mode 100644
index 0..01eaebb6d0eec
--- /dev/null
+++ b/clang/test/Driver/pc-unknown-toolchain.c
@@ -0,0 +1,6 @@
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### %s -fsanitize=address --target=x86_64-pc-linux-gnu 2>&1 | 
FileCheck -check-prefix=CHECK-ASAN-PC %s
+// CHECK-ASAN-PC: x86_64-unknown-linux-gnu/libclang_rt.asan_static.a
+// RUN: %clang -### %s -fsanitize=address --target=x86_64-unknown-linux-gnu 
2>&1 | FileCheck -check-prefix=CHECK-ASAN-UNKNOWN %s
+// CHECK-ASAN-UNKNOWN: x86_64-unknown-linux-gnu/libclang_rt.asan_static.a

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


[clang] [RFC] [clang][Toolchain] Treat "pc"/"unknown" vendor interchangeable (PR #97802)

2024-07-05 Thread Azat Khuzhin via cfe-commits

azat wrote:

I've excluded new test for windows 
(https://buildkite.com/llvm-project/github-pull-requests/builds/78458)

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


[clang] 00c622e - [clang][Interp][Test] Add test for #97302

2024-07-05 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-07-05T12:44:32+02:00
New Revision: 00c622e596f918d9d83674b58097c8982ae1af95

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

LOG: [clang][Interp][Test] Add test for #97302

Fixes #97302

Added: 


Modified: 
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index 1554e54275598a..f27c895e899486 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -494,6 +494,12 @@ namespace DeclRefs {
   constexpr B b;
   static_assert(b.a.m == 100, "");
   static_assert(b.a.f == 100, "");
+
+  constexpr B b2;
+  static_assert(b2.a.m == 100, "");
+  static_assert(b2.a.f == 100, "");
+  static_assert(b2.a.f == 101, ""); // both-error {{failed}} \
+// both-note {{evaluates to '100 == 101'}}
 }
 
 namespace PointerArith {



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


[libunwind] [libunwind] fix unwinding from signal handler (PR #92291)

2024-07-05 Thread Azat Khuzhin via cfe-commits

azat wrote:

Can someone take a look? Maybe @MaskRay @compnerd (according to the most 
frequent reviewers from `Reviewed By` tag)

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


[clang] [llvm] [PowerPC] add TargetParser for PPC target (PR #97541)

2024-07-05 Thread Chen Zheng via cfe-commits

https://github.com/chenzheng1030 updated 
https://github.com/llvm/llvm-project/pull/97541

>From 405639a8847111e401d5c2b69bb801c1c0ccadb7 Mon Sep 17 00:00:00 2001
From: Chen Zheng 
Date: Wed, 3 Jul 2024 04:42:25 -0400
Subject: [PATCH 1/2] [PowerPC] add TargetParser for PPC target For now only
 focus on the CPU type, will work on the CPU features part later.

---
 clang/lib/Basic/Targets/PPC.cpp   |  18 +--
 clang/lib/Driver/ToolChains/Arch/PPC.cpp  |  72 ---
 clang/lib/Driver/ToolChains/Arch/PPC.h|   4 -
 clang/lib/Driver/ToolChains/Clang.cpp |   8 +-
 clang/lib/Driver/ToolChains/CommonArgs.cpp|   5 +-
 clang/test/CodeGen/aix-builtin-cpu-is.c   |  42 +++---
 clang/test/Misc/target-invalid-cpu-note.c |   2 +-
 .../llvm/TargetParser/PPCTargetParser.def |  53 +++-
 .../llvm/TargetParser/PPCTargetParser.h   |  37 ++
 llvm/lib/TargetParser/CMakeLists.txt  |   1 +
 llvm/lib/TargetParser/PPCTargetParser.cpp | 120 ++
 .../secondary/llvm/lib/TargetParser/BUILD.gn  |   1 +
 12 files changed, 250 insertions(+), 113 deletions(-)
 create mode 100644 llvm/include/llvm/TargetParser/PPCTargetParser.h
 create mode 100644 llvm/lib/TargetParser/PPCTargetParser.cpp

diff --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp
index 89c5566f7ad09..5543f4a100c46 100644
--- a/clang/lib/Basic/Targets/PPC.cpp
+++ b/clang/lib/Basic/Targets/PPC.cpp
@@ -14,6 +14,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/MacroBuilder.h"
 #include "clang/Basic/TargetBuiltins.h"
+#include "llvm/TargetParser/PPCTargetParser.h"
 
 using namespace clang;
 using namespace clang::targets;
@@ -866,25 +867,12 @@ ArrayRef 
PPCTargetInfo::getGCCAddlRegNames() const {
   return llvm::ArrayRef(GCCAddlRegNames);
 }
 
-static constexpr llvm::StringLiteral ValidCPUNames[] = {
-{"generic"}, {"440"}, {"450"},{"601"},   {"602"},
-{"603"}, {"603e"},{"603ev"},  {"604"},   {"604e"},
-{"620"}, {"630"}, {"g3"}, {"7400"},  {"g4"},
-{"7450"},{"g4+"}, {"750"},{"8548"},  {"970"},
-{"g5"},  {"a2"},  {"e500"},   {"e500mc"},{"e5500"},
-{"power3"},  {"pwr3"},{"power4"}, {"pwr4"},  {"power5"},
-{"pwr5"},{"power5x"}, {"pwr5x"},  {"power6"},{"pwr6"},
-{"power6x"}, {"pwr6x"},   {"power7"}, {"pwr7"},  {"power8"},
-{"pwr8"},{"power9"},  {"pwr9"},   {"power10"},   {"pwr10"},
-{"powerpc"}, {"ppc"}, {"ppc32"},  {"powerpc64"}, {"ppc64"},
-{"powerpc64le"}, {"ppc64le"}, {"future"}};
-
 bool PPCTargetInfo::isValidCPUName(StringRef Name) const {
-  return llvm::is_contained(ValidCPUNames, Name);
+  return llvm::PPC::isValidCPU(Name);
 }
 
 void PPCTargetInfo::fillValidCPUList(SmallVectorImpl &Values) const 
{
-  Values.append(std::begin(ValidCPUNames), std::end(ValidCPUNames));
+  llvm::PPC::fillValidCPUList(Values);
 }
 
 void PPCTargetInfo::adjust(DiagnosticsEngine &Diags, LangOptions &Opts) {
diff --git a/clang/lib/Driver/ToolChains/Arch/PPC.cpp 
b/clang/lib/Driver/ToolChains/Arch/PPC.cpp
index 634c096523319..b63e16c22370d 100644
--- a/clang/lib/Driver/ToolChains/Arch/PPC.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/PPC.cpp
@@ -20,78 +20,6 @@ using namespace clang::driver::tools;
 using namespace clang;
 using namespace llvm::opt;
 
-static std::string getPPCGenericTargetCPU(const llvm::Triple &T) {
-  // LLVM may default to generating code for the native CPU,
-  // but, like gcc, we default to a more generic option for
-  // each architecture. (except on AIX)
-  if (T.isOSAIX())
-return "pwr7";
-  else if (T.getArch() == llvm::Triple::ppc64le)
-return "ppc64le";
-  else if (T.getArch() == llvm::Triple::ppc64)
-return "ppc64";
-  else
-return "ppc";
-}
-
-static std::string normalizeCPUName(StringRef CPUName, const llvm::Triple &T) {
-  // Clang/LLVM does not actually support code generation
-  // for the 405 CPU. However, there are uses of this CPU ID
-  // in projects that previously used GCC and rely on Clang
-  // accepting it. Clang has always ignored it and passed the
-  // generic CPU ID to the back end.
-  if (CPUName == "generic" || CPUName == "405")
-return getPPCGenericTargetCPU(T);
-
-  if (CPUName == "native") {
-std::string CPU = std::string(llvm::sys::getHostCPUName());
-if (!CPU.empty() && CPU != "generic")
-  return CPU;
-else
-  return getPPCGenericTargetCPU(T);
-  }
-
-  return llvm::StringSwitch(CPUName)
-  .Case("common", "generic")
-  .Case("440fp", "440")
-  .Case("630", "pwr3")
-  .Case("G3", "g3")
-  .Case("G4", "g4")
-  .Case("G4+", "g4+")
-  .Case("8548", "e500")
-  .Case("G5", "g5")
-  .Case("power3", "pwr3")
-  .Case("power4", "pwr4")
-  .Case("power5", "pwr5")
-  .Case("power5x", "pwr5x")
-  .Case("power6", "pwr6")
-  .Case("power6x", "pwr6x")
-  .Case("po

[clang] [llvm] [PowerPC] add TargetParser for PPC target (PR #97541)

2024-07-05 Thread Chen Zheng via cfe-commits

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


[clang] [llvm] [PowerPC] add TargetParser for PPC target (PR #97541)

2024-07-05 Thread Chen Zheng via cfe-commits


@@ -85,8 +85,59 @@
 #define AIX_PPC9_VALUE 0x0002
 #define AIX_PPC10_VALUE 0x0004
 
-// __builtin_cpu_is() and __builtin_cpu_supports() are supported only on 
Power7 and up on AIX.
 // PPC_CPU(Name, Linux_SUPPORT_METHOD, LinuxID, AIX_SUPPORT_METHOD, AIXID)
+
+// Valid CPUs not supported by __builtin_cpu_is()
+PPC_CPU("generic",BUILTIN_PPC_FALSE,0,BUILTIN_PPC_FALSE,0)
+PPC_CPU("440",SYS_CALL,42,BUILTIN_PPC_FALSE,0)

chenzheng1030 wrote:

I added some cpu checks in `clang/test/CodeGen/builtin-cpu-supports.c`.

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


[clang] [llvm] [PowerPC] add TargetParser for PPC target (PR #97541)

2024-07-05 Thread Chen Zheng via cfe-commits

https://github.com/chenzheng1030 commented:

Thanks for your comments @daltenty @ecnelises . Comments addressed.

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


[clang] [llvm] [PowerPC] add TargetParser for PPC target (PR #97541)

2024-07-05 Thread Chen Zheng via cfe-commits


@@ -0,0 +1,120 @@
+//=== PPCTargetParser.cpp - Parser for target features --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements a target parser to recognise hardware features
+// for PPC CPUs.
+//
+//===--===//
+
+#include "llvm/TargetParser/PPCTargetParser.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/TargetParser/Host.h"
+
+namespace llvm {
+namespace PPC {
+
+struct CPUInfo {
+  StringLiteral Name;
+  // FIXME: add the features field for this CPU.
+};
+
+constexpr CPUInfo PPCCPUInfo[] = {
+#define PPC_CPU(Name, Linux_SUPPORT_METHOD, LinuxID, AIX_SUPPORT_METHOD,   
\
+AIXID) 
\
+  Name,
+#include "llvm/TargetParser/PPCTargetParser.def"
+};
+
+static const CPUInfo *getCPUInfoByName(StringRef CPU) {
+  for (auto &C : PPCCPUInfo)
+if (C.Name == CPU)
+  return &C;
+  return nullptr;
+}
+
+StringRef normalizeCPUName(StringRef CPUName) {
+  // Clang/LLVM does not actually support code generation
+  // for the 405 CPU. However, there are uses of this CPU ID
+  // in projects that previously used GCC and rely on Clang
+  // accepting it. Clang has always ignored it and passed the
+  // generic CPU ID to the back end.
+  return StringSwitch(CPUName)
+  .Cases("common", "405", "generic")
+  .Cases("ppc440", "440fp", "440")
+  .Cases("630", "power3", "pwr3")
+  .Case("G3", "g3")
+  .Case("G4", "g4")
+  .Case("G4+", "g4+")
+  .Case("8548", "e500")
+  .Case("ppc970", "970")
+  .Case("G5", "g5")
+  .Case("ppca2", "a2")
+  .Case("power4", "pwr4")
+  .Case("power5", "pwr5")
+  .Case("power5x", "pwr5x")
+  .Case("power5+", "pwr5+")
+  .Case("power6", "pwr6")
+  .Case("power6x", "pwr6x")
+  .Case("power7", "pwr7")
+  .Case("power8", "pwr8")
+  .Case("power9", "pwr9")
+  .Case("power10", "pwr10")
+  .Cases("powerpc", "powerpc32", "ppc")
+  .Case("powerpc64", "ppc64")
+  .Case("powerpc64le", "ppc64le")
+  .Default(CPUName);
+}
+
+void fillValidCPUList(SmallVectorImpl &Values) {
+  for (const auto &C : PPCCPUInfo)
+Values.emplace_back(C.Name);
+}
+
+void fillValidTuneCPUList(SmallVectorImpl &Values) {
+  for (const auto &C : PPCCPUInfo)
+Values.emplace_back(C.Name);
+}
+
+bool isValidCPU(StringRef CPU) {
+  const CPUInfo *Info = getCPUInfoByName(CPU);
+  if (!Info)
+return false;
+  return true;
+}
+
+StringRef getPPCGenericTargetCPU(const Triple &T, StringRef CPUName) {
+  if (!CPUName.empty()) {
+if (CPUName == "native") {
+  std::string CPU = std::string(sys::getHostCPUName());
+  if (!CPU.empty() && CPU != "generic")
+return CPU;
+}
+
+StringRef CPU = normalizeCPUName(CPUName);
+if (CPU != "generic")
+  return CPU;
+  }
+
+  // LLVM may default to generating code for the native CPU, but, like gcc, we
+  // default to a more generic option for each architecture. (except on AIX)
+  if (T.isOSAIX())
+return "pwr7";
+  else if (T.getArch() == Triple::ppc64le)
+return "ppc64le";
+  else if (T.getArch() == Triple::ppc64)
+return "ppc64";

chenzheng1030 wrote:

This is a good comment. Let's change this in another patch. Thanks.

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


[clang] [llvm] [PowerPC] add TargetParser for PPC target (PR #97541)

2024-07-05 Thread Chen Zheng via cfe-commits


@@ -1,52 +1,60 @@
-// RUN: echo "int main() { return __builtin_cpu_is(\"ppc970\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"ppc970\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"ppc-cell-be\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"ppc-cell-be\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"ppca2\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"ppca2\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"ppc405\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"ppc405\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"ppc440\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"ppc440\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"ppc464\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"ppc464\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"ppc476\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"ppc476\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"power4\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"power4\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"power5\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"power5\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"power5+\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"power5+\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"power6\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"power6\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"power6x\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"power6x\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"power7\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"power7\");}" > %t.c
 // RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s -DVALUE=32768 \
 // RUN:   --check-prefix=CHECKOP
 
-// RUN: echo "int main() { return __builtin_cpu_is(\"power8\");}" > %t.c 
+// RUN: echo "int main() { return __builtin_cpu_is(\"pwr7\");}" > %t.c
+// RUN: %clang_cc1 -triple powerpc-ibm-aix7.2.0.0 -emit-llvm -o - %t.c | 
FileCheck %s -DVALUE=32768 \
+// RUN:   --check-prefix=CHECKOP
+
+// RUN: echo "int main() { return __builtin_cpu_is(\"power8\");}" > %t.c

chenzheng1030 wrote:

ha, I just want to avoid unnecessary tests. Coverage should be enough by 
checking pwr7 and pwr10. If you think pwr8 and pwr9 cases are necessary, I can 
add them

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


[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)

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

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/97733

>From f009148063ba41d39fc844f4432ceb51377f381c Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Thu, 4 Jul 2024 17:05:11 +0300
Subject: [PATCH 1/4] [clang] Implement P3144R2 "Deleting a Pointer to an
 Incomplete Type Should be Ill-formed"

---
 .../clang/Basic/DiagnosticSemaKinds.td|  2 ++
 clang/lib/Sema/SemaExprCXX.cpp| 12 ++---
 clang/test/CXX/drs/cwg5xx.cpp | 22 +---
 clang/test/SemaCXX/new-delete.cpp | 26 ---
 4 files changed, 41 insertions(+), 21 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 3df64b2ecef1b..5c3e311ac6382 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7991,6 +7991,8 @@ def err_ambiguous_delete_operand : Error<
 def warn_delete_incomplete : Warning<
   "deleting pointer to incomplete type %0 may cause undefined behavior">,
   InGroup;
+def err_delete_incomplete : Error<
+  "cannot delete pointer to incomplete type %0">;
 def err_delete_incomplete_class_type : Error<
   "deleting incomplete class type %0; no conversions to pointer type">;
 def err_delete_explicit_conversion : Error<
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 69074f92a0286..fcf2189a308a8 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -3719,8 +3719,11 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool 
UseGlobal,
   // The C++ standard bans deleting a pointer to a non-object type, which
   // effectively bans deletion of "void*". However, most compilers support
   // this, so we treat it as a warning unless we're in a SFINAE context.
-  Diag(StartLoc, diag::ext_delete_void_ptr_operand)
-<< Type << Ex.get()->getSourceRange();
+  // But we still prohibit this since C++26.
+  Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
+  : diag::ext_delete_void_ptr_operand)
+  << (LangOpts.CPlusPlus26 ? Pointee : Type)
+  << Ex.get()->getSourceRange();
 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
Pointee->isSizelessType()) {
   return ExprError(Diag(StartLoc, diag::err_delete_operand)
@@ -3729,7 +3732,10 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool 
UseGlobal,
   // FIXME: This can result in errors if the definition was imported from a
   // module but is hidden.
   if (!RequireCompleteType(StartLoc, Pointee,
-   diag::warn_delete_incomplete, Ex.get())) {
+   LangOpts.CPlusPlus26
+   ? diag::err_delete_incomplete
+   : diag::warn_delete_incomplete,
+   Ex.get())) {
 if (const RecordType *RT = PointeeElem->getAs())
   PointeeRD = cast(RT->getDecl());
   }
diff --git a/clang/test/CXX/drs/cwg5xx.cpp b/clang/test/CXX/drs/cwg5xx.cpp
index 9d890f981348a..6a0bb7a196669 100644
--- a/clang/test/CXX/drs/cwg5xx.cpp
+++ b/clang/test/CXX/drs/cwg5xx.cpp
@@ -1,9 +1,10 @@
-// RUN: %clang_cc1 -std=c++98 %s 
-verify=expected,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions -fcxx-exceptions 
-pedantic-errors
-// RUN: %clang_cc1 -std=c++11 %s 
-verify=expected,cxx98-11,cxx98-14,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
-// RUN: %clang_cc1 -std=c++14 %s 
-verify=expected,cxx98-14,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions 
-pedantic-errors
-// RUN: %clang_cc1 -std=c++17 %s 
-verify=expected,since-cxx17,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions 
-pedantic-errors
-// RUN: %clang_cc1 -std=c++20 %s 
-verify=expected,since-cxx20,since-cxx17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
-// RUN: %clang_cc1 -std=c++23 %s 
-verify=expected,since-cxx23,since-cxx20,since-cxx17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++98 %s 
-verify=expected,cxx98-23,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 %s 
-verify=expected,cxx98-23,cxx98-11,cxx98-14,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++14 %s 
-verify=expected,cxx98-23,cxx98-14,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++17 %s 
-verify=expected,cxx98-23,since-cxx17,cxx98-17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++20 %s 
-verify=expected,cxx98-23,since-cxx20,since-cxx17,since-cxx11 -fexceptions 
-fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++23 %s 
-verify=expected,cxx98-23,since-cxx23,since-cxx20,since-cxx17,since-cxx11 
-fexceptions -fcxx-exce

[clang] [clang] Support --sysroot= for ${arch}-windows-msvc targets (PR #96417)

2024-07-05 Thread via cfe-commits

zmodem wrote:

> I extract all files from msvc installations and windows SDK and put them in 
> the format of what a normal sysroot would do on other platforms. Basically, 
> unify the behavior with another platform.

Isn't it better to point Clang at MSVC and the Windows SDK as they're normally 
installed?

This patch seems specific to your custom setup, not something that would be 
useful for others.

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


[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

2024-07-05 Thread Mital Ashok via cfe-commits


@@ -3183,8 +3193,35 @@ bool Lexer::LexEndOfFile(Token &Result, const char 
*CurPtr) {
   DiagID = diag::ext_no_newline_eof;
 }
 
-Diag(BufferEnd, DiagID)
-  << FixItHint::CreateInsertion(EndLoc, "\n");
+if (LastNewline.empty()) {
+  Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n");
+} else {
+  // While the file physically ends in a newline, the previous
+  // line might have ended in a splice, so it would be deleted
+  StringRef WithoutLastNewline =
+  StringRef(BufferStart, LastNewline.data() - BufferStart);
+  while (!WithoutLastNewline.empty()) {
+if (isHorizontalWhitespace(WithoutLastNewline.back())) {
+  WithoutLastNewline = WithoutLastNewline.drop_back();
+} else {
+  break;
+}
+  }
+
+  if (WithoutLastNewline.ends_with('\\') ||
+  (LangOpts.Trigraphs && WithoutLastNewline.ends_with("??"
+  "/"))) {

MitalAshok wrote:

That gives a "warning: trigraph ignored [-Wtrigraphs]" warning when compiling 
this

clang-format refuses to put concatenated string literals on the same line.

I've changed this and added a comment, but let me know if this could be done in 
a cleaner way

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


[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

2024-07-05 Thread Mital Ashok via cfe-commits


@@ -647,6 +647,8 @@ Improvements to Clang's diagnostics
 
 - Clang now shows implicit deduction guides when diagnosing overload 
resolution failure. #GH92393.
 
+- Clang now emits ``-Wnewline-eof`` when the last newline is deleted by a 
preceding backslash. #GH41571.

MitalAshok wrote:

Is the space before the full stop intentional?

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


[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)

2024-07-05 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/97585

>From 8af656659b79d76c971b01f1f4c14dc7315565b8 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Fri, 21 Jun 2024 18:55:38 +0100
Subject: [PATCH 1/8] [Clang] Warn on backslash-newline-EOF

---
 clang/docs/ReleaseNotes.rst   |  2 +
 .../include/clang/Basic/DiagnosticLexKinds.td |  1 +
 clang/lib/Lex/Lexer.cpp   | 39 +--
 clang/test/CXX/drs/cwg16xx.cpp|  9 +
 clang/test/CXX/drs/cwg2747.cpp| 11 ++
 clang/test/CXX/drs/cwg27xx.cpp|  2 +
 .../test/Preprocessor/backslash_newline_eof.c | 12 ++
 .../Preprocessor/backslash_without_newline.c  |  8 
 .../Preprocessor/backslash_without_newline.h  |  4 ++
 clang/www/cxx_dr_status.html  |  4 +-
 10 files changed, 87 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CXX/drs/cwg2747.cpp
 create mode 100644 clang/test/Preprocessor/backslash_newline_eof.c
 create mode 100644 clang/test/Preprocessor/backslash_without_newline.c
 create mode 100644 clang/test/Preprocessor/backslash_without_newline.h

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f40fd1cd145bb..7c0ac3a504f98 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -647,6 +647,8 @@ Improvements to Clang's diagnostics
 
 - Clang now shows implicit deduction guides when diagnosing overload 
resolution failure. #GH92393.
 
+- Clang now emits ``-Wnewline-eof`` when the last newline is deleted by a 
preceding backslash.
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 12d7b8c0205ee..e6b2c1385944c 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -56,6 +56,7 @@ def ext_no_newline_eof : Extension<"no newline at end of 
file">,
   InGroup;
 def warn_no_newline_eof : Warning<"no newline at end of file">,
   InGroup, DefaultIgnore;
+def note_backslash_newline_eof : Note<"last newline deleted by splice here">;
 
 def warn_cxx98_compat_no_newline_eof : Warning<
   "C++98 requires newline at end of file">,
diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp
index e59c7805b3862..0e540834b473b 100644
--- a/clang/lib/Lex/Lexer.cpp
+++ b/clang/lib/Lex/Lexer.cpp
@@ -3165,7 +3165,17 @@ bool Lexer::LexEndOfFile(Token &Result, const char 
*CurPtr) {
 
   // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
   // a pedwarn.
-  if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
+  if (CurPtr != BufferStart) {
+StringRef LastNewline;
+if (CurPtr[-1] == '\r' || CurPtr[-1] == '\n') {
+  LastNewline = StringRef(CurPtr - 1, 1);
+  if (CurPtr - 1 != BufferStart && CurPtr[-2] != CurPtr[-1] &&
+  (CurPtr[-2] == '\r' || CurPtr[-2] == '\n')) {
+// \r\n or \n\r is one newline
+LastNewline = StringRef(CurPtr - 2, 2);
+  }
+}
+
 DiagnosticsEngine &Diags = PP->getDiagnostics();
 SourceLocation EndLoc = getSourceLocation(BufferEnd);
 unsigned DiagID;
@@ -3183,8 +3193,31 @@ bool Lexer::LexEndOfFile(Token &Result, const char 
*CurPtr) {
   DiagID = diag::ext_no_newline_eof;
 }
 
-Diag(BufferEnd, DiagID)
-  << FixItHint::CreateInsertion(EndLoc, "\n");
+if (LastNewline.empty()) {
+  Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n");
+} else {
+  // While the file physically ends in a newline, the previous
+  // line might have ended in a splice, so it would be deleted
+  const char *LastSpliceLocation = LastNewline.data();
+  while (LastSpliceLocation != BufferStart &&
+ isHorizontalWhitespace(*--LastSpliceLocation))
+;
+
+  bool LastIsSplice = *LastSpliceLocation == '\\';
+  if (*LastSpliceLocation == '/' && LangOpts.Trigraphs)
+// Check for "??/" trigraph for "\"
+LastIsSplice =
+LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?' 
&&
+LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?';
+
+  if (LastIsSplice) {
+PP->Diag(getSourceLocation(LastNewline.data(), LastNewline.size()),
+ DiagID);
+Diag(LastSpliceLocation, diag::note_backslash_newline_eof)
+<< FixItHint::CreateRemoval(getSourceLocation(
+   LastSpliceLocation, *LastSpliceLocation == '\\' ? 1 : 3));
+  }
+}
   }
 
   BufferPtr = CurPtr;
diff --git a/clang/test/CXX/drs/cwg16xx.cpp b/clang/test/CXX/drs/cwg16xx.cpp
index cf6b45ceabf2c..dca941fa30624 100644
--- a/clang/test/CXX/drs/cwg16xx.cpp
+++ b/clang/test/CXX/drs/cwg16xx.cpp
@@ -536,3 +536,12 @@ namespace cwg1696 { // cwg1696: 7
   };
 #endif
 }
+
+// cwg1698: yes
+// This file intentionally does not end in a ne

[clang] [llvm] [PowerPC] Diagnose musttail instead of crash inside backend (PR #93267)

2024-07-05 Thread Chen Zheng via cfe-commits

chenzheng1030 wrote:

@efriedma-quic sorry to bother you. Do you think the new update is the correct 
one? Thanks very much.

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


[clang] [clang] Allow class with anonymous union member to be const-default-constructible even if a union member has a default member initializer (#95854) (PR #96301)

2024-07-05 Thread Rajveer Singh Bharadwaj via cfe-commits

https://github.com/Rajveer100 updated 
https://github.com/llvm/llvm-project/pull/96301

>From 3fb29e52b7227c2778942b3ca941112596ce89c1 Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Fri, 21 Jun 2024 18:26:36 +0530
Subject: [PATCH] [clang] Allow class with anonymous union member to be
 const-default-constructible even if a union member has a default member
 initializer (#95854)

Resolves #95854

  Clang incorrectly considers a class with an anonymous union member to not be
  const-default-constructible even if a union member has a default member 
initializer.
  This is valid as per ``8.3`` in `Draft C++ Standard 
`_.
  The ``allowConstDefaultInit`` member function in ``CXXRecordDecl`` needs
  special-case unions to handle the rule. (#GH95854).

```
struct A {
  union {
int n = 0;
int m;
  };
};
const A a;
```

-- As per https://eel.is/c++draft/dcl.init#general-8.3
---
 clang/docs/ReleaseNotes.rst   |  6 ++
 clang/include/clang/AST/DeclCXX.h |  3 ++-
 clang/lib/AST/DeclCXX.cpp |  9 -
 clang/test/SemaCXX/GH95854.cpp| 21 +
 4 files changed, 37 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaCXX/GH95854.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 45676a02b760b..c107304ea95f7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -624,6 +624,12 @@ Bug Fixes in This Version
 
 - ``__is_array`` and ``__is_bounded_array`` no longer return ``true`` for
   zero-sized arrays. Fixes (#GH54705).
+  
+- Clang incorrectly considers a class with an anonymous union member to not be 
+  const-default-constructible even if a union member has a default member 
initializer. 
+  This is valid as per ``8.3`` in `Draft C++ Standard 
`_.
+  The ``allowConstDefaultInit`` member function in ``CXXRecordDecl`` needs 
+  special-case unions to handle the rule. (#GH95854).
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index fb52ac804849d..f4d90e19e0e05 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1392,7 +1392,8 @@ class CXXRecordDecl : public RecordDecl {
   bool allowConstDefaultInit() const {
 return !data().HasUninitializedFields ||
!(data().HasDefaultedDefaultConstructor ||
- needsImplicitDefaultConstructor());
+ needsImplicitDefaultConstructor()) ||
+   (isUnion() && isEmpty());
   }
 
   /// Determine whether this class has a destructor which has no
diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index 75c441293d62e..0b963cb305d27 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1018,6 +1018,9 @@ void CXXRecordDecl::addedMember(Decl *D) {
 if (isUnion() && !Field->isAnonymousStructOrUnion())
   data().HasVariantMembers = true;
 
+if (isUnion() && IsFirstField)
+  data().HasUninitializedFields = true;
+
 // C++0x [class]p9:
 //   A POD struct is a class that is both a trivial class and a
 //   standard-layout class, and has no non-static data members of type
@@ -1086,7 +1089,11 @@ void CXXRecordDecl::addedMember(Decl *D) {
 data().DefaultedCopyConstructorIsDeleted = true;
 }
 
-if (!Field->hasInClassInitializer() && !Field->isMutable()) {
+if (isUnion() && !Field->isMutable()) {
+  if (Field->hasInClassInitializer()) {
+data().HasUninitializedFields = false;
+  }
+} else if (!Field->hasInClassInitializer() && !Field->isMutable()) {
   if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) {
 if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit())
   data().HasUninitializedFields = true;
diff --git a/clang/test/SemaCXX/GH95854.cpp b/clang/test/SemaCXX/GH95854.cpp
new file mode 100644
index 0..62ae549f2496f
--- /dev/null
+++ b/clang/test/SemaCXX/GH95854.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify %s
+//
+// -expected-no-diagnostics
+
+struct A {
+  union {
+int n = 0;
+int m;
+  };
+};
+const A a;
+
+struct B {
+  union {
+struct {
+  int n = 5;
+  int m;
+};
+  };
+};
+const B b; // expected-error {{default initialization of an object of const 
type 'const B' without a user-provided default constructor}}

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


[clang] [clang] Allow class with anonymous union member to be const-default-constructible even if a union member has a default member initializer (#95854) (PR #96301)

2024-07-05 Thread Rajveer Singh Bharadwaj via cfe-commits

https://github.com/Rajveer100 updated 
https://github.com/llvm/llvm-project/pull/96301

>From 751e630dbf54ef6f3a1209a5d09f99093ad84cae Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Fri, 21 Jun 2024 18:26:36 +0530
Subject: [PATCH] [clang] Allow class with anonymous union member to be
 const-default-constructible even if a union member has a default member
 initializer (#95854)

Resolves #95854

  Clang incorrectly considers a class with an anonymous union member to not be
  const-default-constructible even if a union member has a default member 
initializer.
  This is valid as per ``8.3`` in `Draft C++ Standard 
`_.
  The ``allowConstDefaultInit`` member function in ``CXXRecordDecl`` needs
  special-case unions to handle the rule. (#GH95854).

```
struct A {
  union {
int n = 0;
int m;
  };
};
const A a;
```

-- As per https://eel.is/c++draft/dcl.init#general-8.3
---
 clang/docs/ReleaseNotes.rst   |  6 ++
 clang/include/clang/AST/DeclCXX.h |  3 ++-
 clang/lib/AST/DeclCXX.cpp |  9 -
 clang/test/SemaCXX/GH95854.cpp| 21 +
 4 files changed, 37 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaCXX/GH95854.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 36cf615a4287cc..35259760adc60f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -756,6 +756,12 @@ Bug Fixes in This Version
 
 - ``__is_array`` and ``__is_bounded_array`` no longer return ``true`` for
   zero-sized arrays. Fixes (#GH54705).
+  
+- Clang incorrectly considers a class with an anonymous union member to not be 
+  const-default-constructible even if a union member has a default member 
initializer. 
+  This is valid as per ``8.3`` in `Draft C++ Standard 
`_.
+  The ``allowConstDefaultInit`` member function in ``CXXRecordDecl`` needs 
+  special-case unions to handle the rule. (#GH95854).
 
 - Correctly reject declarations where a statement is required in C.
   Fixes #GH92775
diff --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index fb52ac804849d8..f4d90e19e0e05e 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1392,7 +1392,8 @@ class CXXRecordDecl : public RecordDecl {
   bool allowConstDefaultInit() const {
 return !data().HasUninitializedFields ||
!(data().HasDefaultedDefaultConstructor ||
- needsImplicitDefaultConstructor());
+ needsImplicitDefaultConstructor()) ||
+   (isUnion() && isEmpty());
   }
 
   /// Determine whether this class has a destructor which has no
diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index d5c140fd343895..16f0a2b4592ed0 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1018,6 +1018,9 @@ void CXXRecordDecl::addedMember(Decl *D) {
 if (isUnion() && !Field->isAnonymousStructOrUnion())
   data().HasVariantMembers = true;
 
+if (isUnion() && IsFirstField)
+  data().HasUninitializedFields = true;
+
 // C++0x [class]p9:
 //   A POD struct is a class that is both a trivial class and a
 //   standard-layout class, and has no non-static data members of type
@@ -1086,7 +1089,11 @@ void CXXRecordDecl::addedMember(Decl *D) {
 data().DefaultedCopyConstructorIsDeleted = true;
 }
 
-if (!Field->hasInClassInitializer() && !Field->isMutable()) {
+if (isUnion() && !Field->isMutable()) {
+  if (Field->hasInClassInitializer()) {
+data().HasUninitializedFields = false;
+  }
+} else if (!Field->hasInClassInitializer() && !Field->isMutable()) {
   if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) {
 if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit())
   data().HasUninitializedFields = true;
diff --git a/clang/test/SemaCXX/GH95854.cpp b/clang/test/SemaCXX/GH95854.cpp
new file mode 100644
index 00..62ae549f2496f0
--- /dev/null
+++ b/clang/test/SemaCXX/GH95854.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify %s
+//
+// -expected-no-diagnostics
+
+struct A {
+  union {
+int n = 0;
+int m;
+  };
+};
+const A a;
+
+struct B {
+  union {
+struct {
+  int n = 5;
+  int m;
+};
+  };
+};
+const B b; // expected-error {{default initialization of an object of const 
type 'const B' without a user-provided default constructor}}

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


[clang] [clang] Allow class with anonymous union member to be const-default-constructible even if a union member has a default member initializer (#95854) (PR #96301)

2024-07-05 Thread Rajveer Singh Bharadwaj via cfe-commits

Rajveer100 wrote:

@zygoloid 
Let me know if the new changes work well.

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


[clang] [llvm] [BPF] Fix linking issues in static map initializers (PR #91310)

2024-07-05 Thread Nick Zavaritsky via cfe-commits

https://github.com/mejedi updated 
https://github.com/llvm/llvm-project/pull/91310

>From a9682a1eefc360c9f0e517601d0d8cc4b5e9f16f Mon Sep 17 00:00:00 2001
From: Nick Zavaritsky 
Date: Sun, 5 May 2024 10:20:52 +
Subject: [PATCH] [BPF] Fix linking issues in static map initializers

When BPF object files are linked with bpftool, every symbol must be
accompanied by BTF info. Ensure that extern functions referenced by
global variable initializers are included in BTF.

The primary motivation is "static" initialization of PROG maps:

  extern int elsewhere(struct xdp_md *);

  struct {
__uint(type, BPF_MAP_TYPE_PROG_ARRAY);
__uint(max_entries, 1);
__type(key, int);
__type(value, int);
__array(values, int (struct xdp_md *));
  } prog_map SEC(".maps") = { .values = { elsewhere } };

BPF backend needs debug info to produce BTF. Debug info is not
normally generated for external variables and functions. Previously, it
was solved differently for variables (collecting variable declarations
in ExternalDeclarations vector) and functions (logic invoked during
codegen in CGExpr.cpp).

This patch generalises ExternalDefclarations to include both function
and variable declarations. This change ensures that function references
are not missed no matter the context. Previously external functions
referenced in constant expressions lacked debug info.
---
 clang/include/clang/AST/ASTConsumer.h |  3 +-
 .../clang/Frontend/MultiplexConsumer.h|  2 +-
 clang/include/clang/Sema/Sema.h   |  2 +-
 clang/lib/CodeGen/BackendConsumer.h   |  2 +-
 clang/lib/CodeGen/CGExpr.cpp  | 17 +-
 clang/lib/CodeGen/CodeGenAction.cpp   |  2 +-
 clang/lib/CodeGen/CodeGenModule.cpp   | 19 ++-
 clang/lib/CodeGen/CodeGenModule.h |  3 +-
 clang/lib/CodeGen/ModuleBuilder.cpp   |  2 +-
 clang/lib/Frontend/MultiplexConsumer.cpp  |  2 +-
 clang/lib/Interpreter/IncrementalParser.cpp   |  2 +-
 clang/lib/Sema/SemaDecl.cpp   |  8 +++
 .../test/CodeGen/bpf-debug-info-extern-func.c |  9 
 clang/test/CodeGen/bpf-debug-info-unref.c | 11 
 llvm/lib/Target/BPF/BTFDebug.cpp  | 23 
 llvm/lib/Target/BPF/BTFDebug.h|  4 ++
 llvm/test/CodeGen/BPF/BTF/extern-var-func2.ll | 54 +++
 17 files changed, 139 insertions(+), 26 deletions(-)
 create mode 100644 clang/test/CodeGen/bpf-debug-info-extern-func.c
 create mode 100644 clang/test/CodeGen/bpf-debug-info-unref.c
 create mode 100644 llvm/test/CodeGen/BPF/BTF/extern-var-func2.ll

diff --git a/clang/include/clang/AST/ASTConsumer.h 
b/clang/include/clang/AST/ASTConsumer.h
index ebcd8059284d8..447f2592d2359 100644
--- a/clang/include/clang/AST/ASTConsumer.h
+++ b/clang/include/clang/AST/ASTConsumer.h
@@ -23,6 +23,7 @@ namespace clang {
   class ASTDeserializationListener; // layering violation because void* is ugly
   class SemaConsumer; // layering violation required for safe SemaConsumer
   class TagDecl;
+  class DeclaratorDecl;
   class VarDecl;
   class FunctionDecl;
   class ImportDecl;
@@ -105,7 +106,7 @@ class ASTConsumer {
   /// CompleteExternalDeclaration - Callback invoked at the end of a 
translation
   /// unit to notify the consumer that the given external declaration should be
   /// completed.
-  virtual void CompleteExternalDeclaration(VarDecl *D) {}
+  virtual void CompleteExternalDeclaration(DeclaratorDecl *D) {}
 
   /// Callback invoked when an MSInheritanceAttr has been attached to a
   /// CXXRecordDecl.
diff --git a/clang/include/clang/Frontend/MultiplexConsumer.h 
b/clang/include/clang/Frontend/MultiplexConsumer.h
index 4ed0d86d3cdfb..e49e3392d1f31 100644
--- a/clang/include/clang/Frontend/MultiplexConsumer.h
+++ b/clang/include/clang/Frontend/MultiplexConsumer.h
@@ -67,7 +67,7 @@ class MultiplexConsumer : public SemaConsumer {
   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
   void HandleImplicitImportDecl(ImportDecl *D) override;
   void CompleteTentativeDefinition(VarDecl *D) override;
-  void CompleteExternalDeclaration(VarDecl *D) override;
+  void CompleteExternalDeclaration(DeclaratorDecl *D) override;
   void AssignInheritanceModel(CXXRecordDecl *RD) override;
   void HandleVTable(CXXRecordDecl *RD) override;
   ASTMutationListener *GetASTMutationListener() override;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index fb3a5d25c635c..75a80540dbcbf 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3098,7 +3098,7 @@ class Sema final : public SemaBase {
   TentativeDefinitionsType TentativeDefinitions;
 
   /// All the external declarations encoutered and used in the TU.
-  SmallVector ExternalDeclarations;
+  SmallVector ExternalDeclarations;
 
   /// Generally null except when we temporarily switch decl contexts,
   /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
diff --git a/clang/lib/CodeGen/Ba

[clang] ccc0b66 - [clang] Avoid 'raw_string_ostream::str' (NFC)

2024-07-05 Thread Youngsuk Kim via cfe-commits

Author: Youngsuk Kim
Date: 2024-07-05T06:42:43-05:00
New Revision: ccc0b66d6971b64175b4e99c6d5baaa2830c4208

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

LOG: [clang] Avoid 'raw_string_ostream::str' (NFC)

Since `raw_string_ostream` doesn't own the string buffer, it is
desirable (in terms of memory safety) for users to directly reference
the string buffer rather than use `raw_string_ostream::str()`.

Work towards TODO item to remove `raw_string_ostream::str()`.

p.s. also remove some unneeded/dead code.

Added: 


Modified: 
clang/lib/AST/JSONNodeDumper.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
clang/lib/Sema/SemaCodeComplete.cpp

Removed: 




diff  --git a/clang/lib/AST/JSONNodeDumper.cpp 
b/clang/lib/AST/JSONNodeDumper.cpp
index 3bbb3a905e9b91..339477dc65f0f7 100644
--- a/clang/lib/AST/JSONNodeDumper.cpp
+++ b/clang/lib/AST/JSONNodeDumper.cpp
@@ -237,7 +237,7 @@ void JSONNodeDumper::Visit(const APValue &Value, QualType 
Ty) {
   std::string Str;
   llvm::raw_string_ostream OS(Str);
   Value.printPretty(OS, Ctx, Ty);
-  JOS.attribute("value", OS.str());
+  JOS.attribute("value", Str);
 }
 
 void JSONNodeDumper::Visit(const ConceptReference *CR) {
@@ -802,7 +802,7 @@ void JSONNodeDumper::VisitTemplateSpecializationType(
   std::string Str;
   llvm::raw_string_ostream OS(Str);
   TST->getTemplateName().print(OS, PrintPolicy);
-  JOS.attribute("templateName", OS.str());
+  JOS.attribute("templateName", Str);
 }
 
 void JSONNodeDumper::VisitInjectedClassNameType(
@@ -824,7 +824,7 @@ void JSONNodeDumper::VisitElaboratedType(const 
ElaboratedType *ET) {
 std::string Str;
 llvm::raw_string_ostream OS(Str);
 NNS->print(OS, PrintPolicy, /*ResolveTemplateArgs*/ true);
-JOS.attribute("qualifier", OS.str());
+JOS.attribute("qualifier", Str);
   }
   if (const TagDecl *TD = ET->getOwnedTagDecl())
 JOS.attribute("ownedTagDecl", createBareDeclRef(TD));
@@ -1246,7 +1246,7 @@ void JSONNodeDumper::VisitObjCMessageExpr(const 
ObjCMessageExpr *OME) {
   llvm::raw_string_ostream OS(Str);
 
   OME->getSelector().print(OS);
-  JOS.attribute("selector", OS.str());
+  JOS.attribute("selector", Str);
 
   switch (OME->getReceiverKind()) {
   case ObjCMessageExpr::Instance:
@@ -1277,7 +1277,7 @@ void JSONNodeDumper::VisitObjCBoxedExpr(const 
ObjCBoxedExpr *OBE) {
 llvm::raw_string_ostream OS(Str);
 
 MD->getSelector().print(OS);
-JOS.attribute("selector", OS.str());
+JOS.attribute("selector", Str);
   }
 }
 
@@ -1286,7 +1286,7 @@ void JSONNodeDumper::VisitObjCSelectorExpr(const 
ObjCSelectorExpr *OSE) {
   llvm::raw_string_ostream OS(Str);
 
   OSE->getSelector().print(OS);
-  JOS.attribute("selector", OS.str());
+  JOS.attribute("selector", Str);
 }
 
 void JSONNodeDumper::VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) {
@@ -1634,7 +1634,7 @@ void JSONNodeDumper::VisitStringLiteral(const 
StringLiteral *SL) {
   std::string Buffer;
   llvm::raw_string_ostream SS(Buffer);
   SL->outputString(SS);
-  JOS.attribute("value", SS.str());
+  JOS.attribute("value", Buffer);
 }
 void JSONNodeDumper::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *BLE) {
   JOS.attribute("value", BLE->getValue());

diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 64ab328a6d25f6..f354b0974d5f27 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -3029,7 +3029,7 @@ void Darwin::addClangCC1ASTargetOptions(
   std::string Arg;
   llvm::raw_string_ostream OS(Arg);
   OS << "-target-sdk-version=" << V;
-  CC1ASArgs.push_back(Args.MakeArgString(OS.str()));
+  CC1ASArgs.push_back(Args.MakeArgString(Arg));
 };
 
 if (isTargetMacCatalyst()) {
@@ -3052,7 +3052,7 @@ void Darwin::addClangCC1ASTargetOptions(
 std::string Arg;
 llvm::raw_string_ostream OS(Arg);
 OS << "-darwin-target-variant-sdk-version=" << SDKInfo->getVersion();
-CC1ASArgs.push_back(Args.MakeArgString(OS.str()));
+CC1ASArgs.push_back(Args.MakeArgString(Arg));
   } else if (const auto *MacOStoMacCatalystMapping =
  SDKInfo->getVersionMapping(
  DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
@@ -3063,7 +3063,7 @@ void Darwin::addClangCC1ASTargetOptions(
   std::string Arg;
   llvm::raw_string_ostream OS(Arg);
   OS << "-darwin-target-variant-sdk-version=" << *SDKVersion;
-  CC1ASArgs.push_back(Args.MakeArgString(OS.str()));
+  CC1ASArgs.push_back(Args.MakeArgString(Arg));
 }
   }
 }

diff  --git a/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp 
b/clang/lib/Frontend/Rewrite/RewriteModernObj

[clang] [Clang] fix cast failures by adjusting the resolution of record declaration contexts to handle semantic and lexical distinctions (PR #96228)

2024-07-05 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/96228

>From 9e2730da07df0ee5102912490a687ba40bf06def Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Mon, 24 Jun 2024 18:55:51 +0300
Subject: [PATCH] [Clang] fix cast failures by adjusting the resolution of
 record declaration contexts to handle semantic and lexical distinctions

---
 clang/docs/ReleaseNotes.rst|  1 +
 clang/lib/Sema/SemaDeclCXX.cpp |  5 -
 .../class.compare/class.compare.default/p1.cpp | 18 ++
 3 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index df579ae398c5ef..86bd8cf4a6210b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -934,6 +934,7 @@ Bug Fixes to C++ Support
 - Fix an assertion failure caused by parsing a lambda used as a default 
argument for the value of a
   forward-declared class. (#GH93512).
 - Fixed a bug in access checking inside return-type-requirement of compound 
requirements. (#GH93788).
+- Fixed failed assertion when resolving context of defaulted comparison method 
outside of struct. (#GH96043).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 9b220103247dd0..0ecad756d44999 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -9192,7 +9192,10 @@ ComputeDefaultedComparisonExceptionSpec(Sema &S, 
SourceLocation Loc,
 EnterExpressionEvaluationContext Context(
 S, Sema::ExpressionEvaluationContext::Unevaluated);
 
-CXXRecordDecl *RD = cast(FD->getLexicalParent());
+CXXRecordDecl *RD =
+cast(FD->getFriendObjectKind() == Decl::FOK_None
+? FD->getDeclContext()
+: FD->getLexicalDeclContext());
 SourceLocation BodyLoc =
 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
 StmtResult Body =
diff --git a/clang/test/CXX/class/class.compare/class.compare.default/p1.cpp 
b/clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
index 252860bfc4de07..ddf82f432c2eab 100644
--- a/clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
+++ b/clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
@@ -265,3 +265,21 @@ void f2() {
// access info for unnamed bit-field
 }
 }
+
+namespace GH96043 {
+template  class a {};
+template  b c(a);
+template  class e {
+public:
+  typedef a f;
+  f begin();
+};
+template  constexpr bool operator==(d h, g i) {
+  return *c(h.begin()) == *c(i.begin());
+}
+struct j {
+  e bar;
+  bool operator==(const j &) const;
+};
+bool j::operator==(const j &) const = default;
+}

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


[clang] [Clang] Access tls_guard via llvm.threadlocal.address (PR #96633)

2024-07-05 Thread via cfe-commits


@@ -1070,13 +1084,20 @@ 
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
   // Mark as initialized before initializing anything else. If the
   // initializers use previously-initialized thread_local vars, that's
   // probably supposed to be OK, but the standard doesn't say.
-  Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), 
Guard);
-
-  // The guard variable can't ever change again.
+  // Get the thread-local address via intrinsic.
+  if (IsTLS)
+GuardAddr = GuardAddr.withPointer(
+Builder.CreateThreadLocalAddress(Guard.getPointer()),
+NotKnownNonNull);
+  Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(), 1),
+  GuardAddr);
+
+  // Emit invariant start for TLS guard address.
   EmitInvariantStart(
   Guard.getPointer(),
   CharUnits::fromQuantity(
-  CGM.getDataLayout().getTypeAllocSize(GuardVal->getType(;
+  CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())),
+  IsTLS);

nikola-tesic-ns wrote:

I had similar concerns. IIUC, the safe(st possible) bet is to generate 
`threadlocal.address` at each access. In the view of this PR:
1. for the load of `tls_guard`
2. for the store into `tls_guard`
3. for the `invariant.start` intrinsic for `tls_guard`

I am not sure if there is a case where coroutine context switch could happen 
between `threadlocal.address` and its user instruction. If that is the case, 
then there is no guarantee for other use cases of `threadlocal.address` as well.
Do you agree or I am missing something?

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


[clang] [llvm] [PAC][Driver] Implement `-mbranch-protection=pauthabi` option (PR #97237)

2024-07-05 Thread Daniil Kovalev via cfe-commits

https://github.com/kovdan01 updated 
https://github.com/llvm/llvm-project/pull/97237

>From 3b4b1b1739b810d758e68f30c48b648963cff740 Mon Sep 17 00:00:00 2001
From: Daniil Kovalev 
Date: Mon, 1 Jul 2024 00:50:21 +0300
Subject: [PATCH 1/4] [PAC][Driver] Implement `-mbranch-protection=pauthabi`
 option

Enable the following ptrauth flags when `pauthabi` is passed as branch
protection:

- `intrinsics`;
- `calls`;
- `returns`;
- `auth-traps`;
- `vtable-pointer-address-discrimination`;
- `vtable-pointer-type-discrimination`;
- `init-fini`.

Co-authored-by: Anatoly Trosinenko 
---
 clang/lib/Driver/ToolChains/Clang.cpp | 38 +++
 clang/test/Driver/aarch64-ptrauth.c   | 36 ++
 .../llvm/TargetParser/ARMTargetParserCommon.h |  1 +
 .../TargetParser/ARMTargetParserCommon.cpp|  6 ++-
 4 files changed, 72 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 1b7cc82ea816ed..4ed1ece22b7aac 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1484,6 +1484,39 @@ void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
 }
 }
 
+static void handlePAuthABIOption(const ArgList &DriverArgs,
+ ArgStringList &CC1Args, const Driver &D) {
+  if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
+ options::OPT_fno_ptrauth_intrinsics))
+CC1Args.push_back("-fptrauth-intrinsics");
+
+  if (!DriverArgs.hasArg(options::OPT_fptrauth_calls,
+ options::OPT_fno_ptrauth_calls))
+CC1Args.push_back("-fptrauth-calls");
+
+  if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
+ options::OPT_fno_ptrauth_returns))
+CC1Args.push_back("-fptrauth-returns");
+
+  if (!DriverArgs.hasArg(options::OPT_fptrauth_auth_traps,
+ options::OPT_fno_ptrauth_auth_traps))
+CC1Args.push_back("-fptrauth-auth-traps");
+
+  if (!DriverArgs.hasArg(
+  options::OPT_fptrauth_vtable_pointer_address_discrimination,
+  options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
+CC1Args.push_back("-fptrauth-vtable-pointer-address-discrimination");
+
+  if (!DriverArgs.hasArg(
+  options::OPT_fptrauth_vtable_pointer_type_discrimination,
+  options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
+CC1Args.push_back("-fptrauth-vtable-pointer-type-discrimination");
+
+  if (!DriverArgs.hasArg(options::OPT_fptrauth_init_fini,
+ options::OPT_fno_ptrauth_init_fini))
+CC1Args.push_back("-fptrauth-init-fini");
+}
+
 static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
 ArgStringList &CmdArgs, bool isAArch64) {
   const Arg *A = isAArch64
@@ -1537,11 +1570,16 @@ static void CollectARMPACBTIOptions(const ToolChain 
&TC, const ArgList &Args,
 if (!isAArch64 && PBP.Key == "b_key")
   D.Diag(diag::warn_unsupported_branch_protection)
   << "b-key" << A->getAsString(Args);
+if (!isAArch64 && PBP.HasPauthABI)
+  D.Diag(diag::warn_unsupported_branch_protection)
+  << "pauthabi" << A->getAsString(Args);
 Scope = PBP.Scope;
 Key = PBP.Key;
 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
 IndirectBranches = PBP.BranchTargetEnforcement;
 GuardedControlStack = PBP.GuardedControlStack;
+if (isAArch64 && PBP.HasPauthABI)
+  handlePAuthABIOption(Args, CmdArgs, D);
   }
 
   CmdArgs.push_back(
diff --git a/clang/test/Driver/aarch64-ptrauth.c 
b/clang/test/Driver/aarch64-ptrauth.c
index fa0125f4b22a9a..dc63545a47a866 100644
--- a/clang/test/Driver/aarch64-ptrauth.c
+++ b/clang/test/Driver/aarch64-ptrauth.c
@@ -13,13 +13,33 @@
 // RUN:   %s 2>&1 | FileCheck %s --check-prefix=ALL
 // ALL: "-cc1"{{.*}} "-fptrauth-intrinsics" "-fptrauth-calls" 
"-fptrauth-returns" "-fptrauth-auth-traps" 
"-fptrauth-vtable-pointer-address-discrimination" 
"-fptrauth-vtable-pointer-type-discrimination" "-fptrauth-init-fini"
 
+// RUN: %clang -### -c --target=aarch64 -mbranch-protection=pauthabi %s 2>&1 | 
\
+// RUN:   FileCheck %s --check-prefix=PAUTHABI1
+// PAUTHABI1: "-cc1"{{.*}} "-fptrauth-intrinsics" "-fptrauth-calls" 
"-fptrauth-returns" "-fptrauth-auth-traps" 
"-fptrauth-vtable-pointer-address-discrimination" 
"-fptrauth-vtable-pointer-type-discrimination" "-fptrauth-init-fini"
+
+// RUN: %clang -### -c --target=aarch64 -mbranch-protection=pauthabi 
-fno-ptrauth-intrinsics \
+// RUN:   -fno-ptrauth-calls -fno-ptrauth-returns -fno-ptrauth-auth-traps \
+// RUN:   -fno-ptrauth-vtable-pointer-address-discrimination 
-fno-ptrauth-vtable-pointer-type-discrimination \
+// RUN:   -fno-ptrauth-init-fini %s 2>&1 | FileCheck %s 
--check-prefix=PAUTHABI2
+// PAUTHABI2-NOT: "-fptrauth-intrinsics"
+// PAUTHABI2-NOT: "-fptrauth-calls"
+// PAUTHABI2-NOT: "-fptrauth-returns"
+// PAUTHABI2-NOT: "-fptrauth-auth-traps"

  1   2   3   >