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

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


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

H-G-Hristov wrote:

@mordante I am not sure what I need to do. My experience with modules is 
minuscule. I think we only need to export global namespace level names and this 
is a class member. Could you please show an example. I couldn't find any.

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


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

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

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

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

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

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

[llvm] [clang] [RISCV] Add support for experimental Zimop extension (PR #74824)

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

wangpc-pp wrote:

> Please reorganize the patch as @dtcxzyw suggested. :-)
> 
> I didn't notice this extension before, so I may not be asking the right 
> question here: These MOPs can be redefined, then, are we able to schedule 
> them in compiler? Becase we don't know the cost of MOPs if we don't know how 
> MOPs are used. For example, MOPs can be redefined as simple ALU instructions, 
> or, it can be instructions with large cost like DIV/REM. I don't know how to 
> model it now, but I don't think defining Sched resources for MOPs is the 
> right way.

Just checked similar extensions in ARM (like AUT, PAC, BTI, etc.), these 
extensions are defined in NOP encoding space and their schedule resources will 
be overrided by `InstRW`.

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


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

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

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


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

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


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

H-G-Hristov wrote:

For consistency I changed the implementation to how it is implemented in the 
other methods. Would that be a good compromise?

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


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

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

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


[clang] [clang-tools-extra] [clang-tidy] Added new check to detect redundant inline keyword (PR #73069)

2023-12-10 Thread via cfe-commits
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin
Message-ID:
In-Reply-To: 


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


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

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

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


[flang] [clang] [flang][driver] Add -fno-fortran-main (link time) option to remove Fortran_main from link line (PR #74139)

2023-12-10 Thread Michael Klemm via cfe-commits

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


[clang] [clang-tools-extra] [clang-tidy] Added new check to detect redundant inline keyword (PR #73069)

2023-12-10 Thread via cfe-commits
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin
Message-ID:
In-Reply-To: 


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


[mlir] [flang] [lldb] [openmp] [clang] [libcxxabi] [compiler-rt] [llvm] [libcxx] [clang-tools-extra] [MachineCopyPropagation] When the source of PreviousCopy is undef, we cannot replace sub register (

2023-12-10 Thread via cfe-commits

DianQK wrote:

@nikic  Would you approve of this? Or do we need to add other codegen 
participants to review?
@davemgreen Any other comments?

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


[clang] [clang-tools-extra] [clang-tidy] Added new check to detect redundant inline keyword (PR #73069)

2023-12-10 Thread via cfe-commits
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin
Message-ID:
In-Reply-To: 


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


[clang] [clang-tools-extra] [clang-tidy] Added new check to detect redundant inline keyword (PR #73069)

2023-12-10 Thread via cfe-commits
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin,
=?utf-8?q?Félix-Antoine?= Constantin
Message-ID:
In-Reply-To: 



@@ -0,0 +1,113 @@
+//===--- RedundantInlineSpecifierCheck.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 "RedundantInlineSpecifierCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Token.h"
+
+#include "../utils/LexerUtils.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+AST_POLYMORPHIC_MATCHER(isInlineSpecified,
+AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
+VarDecl)) {
+  if (const auto *FD = dyn_cast(&Node))
+return FD->isInlineSpecified();
+  if (const auto *VD = dyn_cast(&Node))
+return VD->isInlineSpecified();
+  llvm_unreachable("Not a valid polymorphic type");
+}
+
+static std::optional
+getInlineTokenLocation(SourceRange RangeLocation, const SourceManager &Sources,
+   const LangOptions &LangOpts) {
+  SourceLocation Loc = RangeLocation.getBegin();
+  if (Loc.isMacroID())
+return std::nullopt;
+
+  Token FirstToken;
+  Lexer::getRawToken(Loc, FirstToken, Sources, LangOpts, true);
+  std::optional CurrentToken = FirstToken;
+  while (CurrentToken && CurrentToken->getLocation() < RangeLocation.getEnd() 
&&
+ CurrentToken->isNot(tok::eof)) {
+if (CurrentToken->is(tok::raw_identifier) &&
+CurrentToken->getRawIdentifier() == "inline")
+  return CurrentToken->getLocation();
+
+CurrentToken =
+Lexer::findNextToken(CurrentToken->getLocation(), Sources, LangOpts);
+  }
+  return std::nullopt;
+}
+
+void RedundantInlineSpecifierCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  functionDecl(isInlineSpecified(),
+   anyOf(isConstexpr(), isDeleted(), isDefaulted(),
+ isInAnonymousNamespace(),

FalcoGer wrote:

According to [cppref](https://en.cppreference.com/w/cpp/language/inline), 
static and anon namespace variables are implicitly inline when they are also 
constexpr.

It doesn't say anything about static functions, probably because a static, 
inline function makes no sense.

Statically declared functions are only visible in their TU, so inline would be 
redundant. Inline only allows redefinition across multiple TUs. Not sure if 
modules change any of that.

So technically it's pointless, not implicit. Same with templates.

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


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

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

xu-chiheng wrote:

> NFC, and

I have build scripts at https://github.com/xu-chiheng/Note
When bootstrapping Clang on Cygwin, there are various weird problems. 
Reducing the size of CallArgList solve them all.



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


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

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

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


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

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

xu-chiheng wrote:

> Would you please add some tests about your changes?
> 
> Also maybe it will be more useful to write some detailed descriptions, so 
> others can understand your code easily. Cheers!

Does to solve any problem.


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


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

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

xu-chiheng wrote:

> Would you please add some tests about your changes?
> 
> Also maybe it will be more useful to write some detailed descriptions, so 
> others can understand your code easily. Cheers!

To keep aligned with Cygwin GCC


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


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

2023-12-10 Thread Fangrui Song via cfe-commits

MaskRay wrote:

I hope that someone using illumos can test, but if it is hard to find one I can 
approve this.

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


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

2023-12-10 Thread via cfe-commits

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

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

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

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

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

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

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

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

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

[clang] 9a46518 - Revert "[clang] Remove unused variable 'ExprDependenceBits' in ASTWriterDecl.cpp (NFC)"

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

Author: Chuanqi Xu
Date: 2023-12-11T14:15:16+08:00
New Revision: 9a46518630869e7fcb495e72378abdbedf68d40d

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

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

This reverts commit 10951050b5f371eb3e7cacce1691c4eb2fe2eab5.
This should be part of 8c334627818437180176b16b1932 to revert
9406ea3fe32e59a7d2 completely.

Added: 


Modified: 
clang/lib/Serialization/ASTWriterDecl.cpp

Removed: 




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



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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2023-12-10 Thread Felix via cfe-commits


@@ -2645,10 +2653,14 @@ MCSection 
*TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
 const MCSymbol *Sym, const TargetMachine &TM) const {
   // Use TE storage-mapping class when large code model is enabled so that
   // the chance of needing -bbigtoc is decreased.
+  // The "_$TLSML" symbol for TLS local-dynamic mode requires XMC_TC.

orcguru wrote:

Looks like I have to keep the XMC_TC setting to make the assembler happy?

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


[clang] 8c33462 - Revert "[NFC] [Serialization] Packing more bits"

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

Author: Chuanqi Xu
Date: 2023-12-11T14:06:32+08:00
New Revision: 8c334627818437180176b16b1932b2a26372d8ae

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

LOG: Revert "[NFC] [Serialization] Packing more bits"

This reverts commit 9406ea3fe32e59a7d28de0dcbd0317b4cdfa4c62.

There are build bots complaining this. Revert it first to try to keep
the bots green.

Added: 


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

Removed: 




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

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

[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2023-12-10 Thread Felix via cfe-commits


@@ -2645,10 +2653,14 @@ MCSection 
*TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
 const MCSymbol *Sym, const TargetMachine &TM) const {
   // Use TE storage-mapping class when large code model is enabled so that
   // the chance of needing -bbigtoc is decreased.
+  // The "_$TLSML" symbol for TLS local-dynamic mode requires XMC_TC.

orcguru wrote:

When I change from XMC_TC to XMC_TE in the large code model like following,
```
L..C0:  
.tc _Renamed..5f24__TLSML[TE],_Renamed..5f24__TLSML[TE]@ml
.rename _Renamed..5f24__TLSML[TE],"_$TLSML"
```
The assembler complains like following:
```
Assembler:
tls_ld_te.s: line 62: 1252-215 The ML relocation type is only valid for a 
reference
to a TOC symbol from the symbol itself.
```
Change back to "TC" did not see the message.

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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2023-12-10 Thread Felix via cfe-commits


@@ -2058,6 +2089,10 @@ void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
 }
   }
 
+  // Do not emit the _$TLSML symbol.
+  if (GVSym->getName() == "_Renamed..5f24__TLSML[TC]")

orcguru wrote:

Thank you! I will put some flag check before the string compare.

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


[clang-tools-extra] [compiler-rt] [llvm] [clang] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,97 @@
+// This is a regression test for ThinLTO indirect-call-promotion when candidate
+// callees need to be imported from another IR module.  In the C++ test case,
+// `main` calls `global_func` which is defined in another module. `global_func`
+// has two indirect callees, one has external linkage and one has local 
linkage.
+// All three functions should be imported into the IR module of main.
+
+// What the test does:
+// - Generate raw profiles from executables and convert it to indexed profiles.
+//   During the conversion, a profiled callee address in raw profiles will be
+//   converted to function hash in indexed profiles.
+// - Run IRPGO profile use and ThinTLO prelink pipeline and get LLVM bitcodes
+//   for both cpp files in the C++ test case.
+// - Generate ThinLTO summary file with LLVM bitcodes, and run 
`function-import` pass.
+// - Run `pgo-icall-prom` pass for the IR module which needs to import callees.
+
+// RUN: rm -rf %t && split-file %s %t && cd %t
+
+// Use clang*_{pgogen,pgouse} for IR level instrumentation, and use clangxx* 
for
+// C++.
+//
+// Do setup work for all below tests.
+// Generate raw profiles from real programs and convert it into indexed 
profiles.
+// RUN: %clangxx_pgogen -fuse-ld=lld -O2 lib.cpp main.cpp -o main
+// RUN: env LLVM_PROFILE_FILE=main.profraw %run ./main
+// RUN: llvm-profdata merge main.profraw -o main.profdata
+
+// Use profile on lib and get bitcode, test that local function callee0 has
+// expected !PGOFuncName metadata and external function callee1 doesn't have
+// !PGOFuncName metadata. Explicitly skip ICP pass to test ICP happens as
+// expected in the IR module that imports functions from lib.
+// RUN: %clang -target x86_64-unknown-linux-gnu -mllvm -disable-icp 
-fprofile-use=main.profdata -flto=thin -O2 -c lib.cpp -o lib.bc
+// RUN: llvm-dis lib.bc -o - | FileCheck %s --check-prefix=PGOName
+
+// Use profile on main and get bitcode.
+// RUN: %clang -target x86_64-unknown-linux-gnu -fprofile-use=main.profdata 
-flto=thin -O2 -c main.cpp -o main.bc
+
+// Run llvm-lto to get summary file.
+// RUN: llvm-lto -thinlto -o summary main.bc lib.bc
+
+// Test the imports of functions. Default import thresholds would work but do
+// explicit override to be more futureproof. Note all functions have one basic
+// block with a function-entry-count of one, so they are actually hot functions
+// per default profile summary hotness cutoff.
+// RUN: opt -passes=function-import -import-instr-limit=100 
-import-cold-multiplier=1 -summary-file summary.thinlto.bc main.bc -o 
main.import.bc -print-imports 2>&1 | FileCheck %s --check-prefix=IMPORTS
+// Test that '_Z11global_funcv' has indirect calls annotated with value 
profiles.
+// RUN: llvm-dis main.import.bc -o - | FileCheck %s --check-prefix=IR
+
+// Test that both candidates are ICP'ed and there is no `!VP` in the IR.
+// RUN: opt main.import.bc -icp-lto -passes=pgo-icall-prom -S 
-pass-remarks=pgo-icall-prom 2>&1 | FileCheck %s 
--check-prefixes=ICP-IR,ICP-REMARK --implicit-check-not="!VP"
+
+// IMPORTS: main.cpp: Import _Z7callee1v
+// IMPORTS: main.cpp: Import _ZL7callee0v.llvm.{{[0-9]+}}
+// IMPORTS: main.cpp: Import _Z11global_funcv
+
+// PGOName: define dso_local void @_Z7callee1v() {{.*}} !prof !{{[0-9]+}} {
+// PGOName: define internal void @_ZL7callee0v() {{.*}} !prof !{{[0-9]+}} 
!PGOFuncName ![[MD:[0-9]+]] {
+// PGOName: ![[MD]] = !{!"{{.*}}lib.cpp;_ZL7callee0v"}
+
+// IR-LABEL: define available_externally {{.*}} void @_Z11global_funcv() 
{{.*}} !prof !35 {

MaskRay wrote:

`!35` in `!prof !35`  may make the test too sensitive.

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


[clang] [compiler-rt] [clang-tools-extra] [llvm] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -1,39 +0,0 @@
-; Do setup work for all below tests: generate bitcode and combined index

MaskRay wrote:

Hmm, I think it is still preferred to have a test here as runtime tests are 
more sensitive to the environment and may be skipped by some contributors.

It means we will have to duplicate some file between here and the runtime test. 
Perhaps adding a comment can help connect the two tests.

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


[compiler-rt] [clang] [llvm] [clang-tools-extra] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -41,6 +41,10 @@ namespace Intrinsic {
 typedef unsigned ID;
 } // end namespace Intrinsic
 
+// Choose ';' as the delimiter. ':' was used once but it doesn't work well for
+// Objective-C functions which commonly have :'s in their names

MaskRay wrote:

add a full stop

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


[clang] [llvm] [clang-tools-extra] [compiler-rt] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -147,6 +147,9 @@ def exclude_unsupported_files_for_aix(dirname):
 config.substitutions.append(
 ("%clang_pgouse=", build_invocation(clang_cflags) + " -fprofile-use=")
 )
+config.substitutions.append(
+("%clangxx_pgouse=", build_invocation(clang_cxxflags) + " -fprofile-use=")

MaskRay wrote:

Is this used?

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


[llvm] [compiler-rt] [clang] [clang-tools-extra] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,97 @@
+// This is a regression test for ThinLTO indirect-call-promotion when candidate
+// callees need to be imported from another IR module.  In the C++ test case,
+// `main` calls `global_func` which is defined in another module. `global_func`
+// has two indirect callees, one has external linkage and one has local 
linkage.
+// All three functions should be imported into the IR module of main.
+
+// What the test does:
+// - Generate raw profiles from executables and convert it to indexed profiles.
+//   During the conversion, a profiled callee address in raw profiles will be
+//   converted to function hash in indexed profiles.
+// - Run IRPGO profile use and ThinTLO prelink pipeline and get LLVM bitcodes
+//   for both cpp files in the C++ test case.
+// - Generate ThinLTO summary file with LLVM bitcodes, and run 
`function-import` pass.
+// - Run `pgo-icall-prom` pass for the IR module which needs to import callees.
+
+// RUN: rm -rf %t && split-file %s %t && cd %t
+
+// Use clang*_{pgogen,pgouse} for IR level instrumentation, and use clangxx* 
for
+// C++.
+//
+// Do setup work for all below tests.
+// Generate raw profiles from real programs and convert it into indexed 
profiles.
+// RUN: %clangxx_pgogen -fuse-ld=lld -O2 lib.cpp main.cpp -o main
+// RUN: env LLVM_PROFILE_FILE=main.profraw %run ./main
+// RUN: llvm-profdata merge main.profraw -o main.profdata
+
+// Use profile on lib and get bitcode, test that local function callee0 has
+// expected !PGOFuncName metadata and external function callee1 doesn't have
+// !PGOFuncName metadata. Explicitly skip ICP pass to test ICP happens as
+// expected in the IR module that imports functions from lib.
+// RUN: %clang -target x86_64-unknown-linux-gnu -mllvm -disable-icp 
-fprofile-use=main.profdata -flto=thin -O2 -c lib.cpp -o lib.bc
+// RUN: llvm-dis lib.bc -o - | FileCheck %s --check-prefix=PGOName
+
+// Use profile on main and get bitcode.
+// RUN: %clang -target x86_64-unknown-linux-gnu -fprofile-use=main.profdata 
-flto=thin -O2 -c main.cpp -o main.bc
+
+// Run llvm-lto to get summary file.
+// RUN: llvm-lto -thinlto -o summary main.bc lib.bc
+
+// Test the imports of functions. Default import thresholds would work but do
+// explicit override to be more futureproof. Note all functions have one basic
+// block with a function-entry-count of one, so they are actually hot functions
+// per default profile summary hotness cutoff.
+// RUN: opt -passes=function-import -import-instr-limit=100 
-import-cold-multiplier=1 -summary-file summary.thinlto.bc main.bc -o 
main.import.bc -print-imports 2>&1 | FileCheck %s --check-prefix=IMPORTS
+// Test that '_Z11global_funcv' has indirect calls annotated with value 
profiles.
+// RUN: llvm-dis main.import.bc -o - | FileCheck %s --check-prefix=IR
+
+// Test that both candidates are ICP'ed and there is no `!VP` in the IR.
+// RUN: opt main.import.bc -icp-lto -passes=pgo-icall-prom -S 
-pass-remarks=pgo-icall-prom 2>&1 | FileCheck %s 
--check-prefixes=ICP-IR,ICP-REMARK --implicit-check-not="!VP"
+
+// IMPORTS: main.cpp: Import _Z7callee1v
+// IMPORTS: main.cpp: Import _ZL7callee0v.llvm.{{[0-9]+}}

MaskRay wrote:

`{{[0-9]+}}` can be simplified to `[[#]]`

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


[llvm] [clang-tools-extra] [compiler-rt] [clang] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,97 @@
+// This is a regression test for ThinLTO indirect-call-promotion when candidate
+// callees need to be imported from another IR module.  In the C++ test case,
+// `main` calls `global_func` which is defined in another module. `global_func`
+// has two indirect callees, one has external linkage and one has local 
linkage.
+// All three functions should be imported into the IR module of main.
+
+// What the test does:
+// - Generate raw profiles from executables and convert it to indexed profiles.
+//   During the conversion, a profiled callee address in raw profiles will be
+//   converted to function hash in indexed profiles.
+// - Run IRPGO profile use and ThinTLO prelink pipeline and get LLVM bitcodes
+//   for both cpp files in the C++ test case.
+// - Generate ThinLTO summary file with LLVM bitcodes, and run 
`function-import` pass.
+// - Run `pgo-icall-prom` pass for the IR module which needs to import callees.
+
+// RUN: rm -rf %t && split-file %s %t && cd %t
+
+// Use clang*_{pgogen,pgouse} for IR level instrumentation, and use clangxx* 
for
+// C++.
+//
+// Do setup work for all below tests.
+// Generate raw profiles from real programs and convert it into indexed 
profiles.
+// RUN: %clangxx_pgogen -fuse-ld=lld -O2 lib.cpp main.cpp -o main

MaskRay wrote:

lld requires `// REQUIRES: lld-available`

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


[clang-tools-extra] [llvm] [compiler-rt] [clang] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -0,0 +1,97 @@
+// This is a regression test for ThinLTO indirect-call-promotion when candidate
+// callees need to be imported from another IR module.  In the C++ test case,
+// `main` calls `global_func` which is defined in another module. `global_func`
+// has two indirect callees, one has external linkage and one has local 
linkage.
+// All three functions should be imported into the IR module of main.
+
+// What the test does:
+// - Generate raw profiles from executables and convert it to indexed profiles.
+//   During the conversion, a profiled callee address in raw profiles will be
+//   converted to function hash in indexed profiles.
+// - Run IRPGO profile use and ThinTLO prelink pipeline and get LLVM bitcodes
+//   for both cpp files in the C++ test case.
+// - Generate ThinLTO summary file with LLVM bitcodes, and run 
`function-import` pass.
+// - Run `pgo-icall-prom` pass for the IR module which needs to import callees.
+
+// RUN: rm -rf %t && split-file %s %t && cd %t
+
+// Use clang*_{pgogen,pgouse} for IR level instrumentation, and use clangxx* 
for
+// C++.
+//
+// Do setup work for all below tests.
+// Generate raw profiles from real programs and convert it into indexed 
profiles.
+// RUN: %clangxx_pgogen -fuse-ld=lld -O2 lib.cpp main.cpp -o main
+// RUN: env LLVM_PROFILE_FILE=main.profraw %run ./main
+// RUN: llvm-profdata merge main.profraw -o main.profdata
+
+// Use profile on lib and get bitcode, test that local function callee0 has
+// expected !PGOFuncName metadata and external function callee1 doesn't have
+// !PGOFuncName metadata. Explicitly skip ICP pass to test ICP happens as
+// expected in the IR module that imports functions from lib.
+// RUN: %clang -target x86_64-unknown-linux-gnu -mllvm -disable-icp 
-fprofile-use=main.profdata -flto=thin -O2 -c lib.cpp -o lib.bc

MaskRay wrote:

`-target ` is deprecated. Use `--target=`. Actually, runtime tests don't 
usually set a `--target=`

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


[clang] [llvm] [clang-tools-extra] [compiler-rt] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits

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


[clang] [compiler-rt] [llvm] [clang-tools-extra] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay commented:

Mostly looks good with some nits...

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


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

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

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

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

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

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

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

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

[clang-tools-extra] [llvm] [compiler-rt] [clang] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -144,25 +145,27 @@ void GlobalObject::copyAttributesFrom(const GlobalObject 
*Src) {
 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
  GlobalValue::LinkageTypes Linkage,
  StringRef FileName) {
-
   // Value names may be prefixed with a binary '1' to indicate
   // that the backend should not modify the symbols due to any platform
   // naming convention. Do not include that '1' in the PGO profile name.
   if (Name[0] == '\1')
 Name = Name.substr(1);
 
-  std::string NewName = std::string(Name);
+  SmallString<64> GlobalName;

MaskRay wrote:

If Name is longer than 64, this would cause two head allocations. It might be 
better to stick with `std::string`.

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


[clang] [RISCV] Enable target attribute when invoked through clang driver (PR #74889)

2023-12-10 Thread Fangrui Song via cfe-commits

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


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


[clang] [flang] [flang][driver] Rename `flang-new` as `flang` (PR #74377)

2023-12-10 Thread Fangrui Song via cfe-commits

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


[flang] [clang] [flang][driver] Rename `flang-new` as `flang` (PR #74377)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -1,15 +1,15 @@
-! Test that flang-new OpenMP and OpenMP offload related 
+! Test that flang OpenMP and OpenMP offload related 
 ! commands forward or expand to the appropriate commands 
-! for flang-new -fc1 as expected. Assumes a gfx90a, aarch64,
+! for flang -fc1 as expected. Assumes a gfx90a, aarch64,
 ! and sm_70 architecture, but doesn't require one to be 
 ! installed or compiled for, just testing the appropriate 
 ! generation of jobs are created with the correct 
 ! corresponding arguments.
 
 ! Test regular -fopenmp with no offload
 ! RUN: %flang -### -fopenmp %s 2>&1 | FileCheck --check-prefixes=CHECK-OPENMP 
%s
-! CHECK-OPENMP: "{{[^"]*}}flang-new" "-fc1" {{.*}} "-fopenmp" {{.*}}.f90"
-! CHECK-OPENMP-NOT: "{{[^"]*}}flang-new" "-fc1" {{.*}} "-fopenmp" {{.*}} 
"-fopenmp-is-target-device" {{.*}}.f90"
+! CHECK-OPENMP: "{{[^"]*}}flang{{.*}}" "-fc1" {{.*}} "-fopenmp" {{.*}}.f90"

MaskRay wrote:

For clang driver, new tests are encouraged to just omit the string before 
`"-cc1"`. This makes the test more portable to build systems that make `clang` 
a symlink 

(
`-no-canonical-prefixes` instructs Clang to call `realpath` on the executable 
name and use the dereferenced absolute path for the `-cc1` command.
This path, either canonicalized by `realpath` or not, is used to derived the 
resource directory.
See  for some 
background.

For most tests "-cc1" is sufficient to identify the command line, no need to 
specifically test the "clang" command, and `-no-canonical-prefixes` can be 
removed.
)

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


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

2023-12-10 Thread via cfe-commits

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


[flang] [clang] [flang][driver] Rename `flang-new` as `flang` (PR #74377)

2023-12-10 Thread Fangrui Song via cfe-commits


@@ -27,7 +27,7 @@
 ! FULL-LTO: "-fc1"
 ! FULL-LTO-SAME: "-flto=full"
 
-! THIN-LTO-ALL: flang-new: warning: the option '-flto=thin' is a work in 
progress
+! THIN-LTO-ALL: flang-{{[0-9]+}}: warning: the option '-flto=thin' is a work 
in progress

MaskRay wrote:

For Clang, lld, and LLVM binary utilities, our convention is to omit the part 
before `warning:`/`error:`. People may customize the `\d+` part and sometimes 
symlinks in certain build systems make this more complex.

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


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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits

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

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

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

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

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

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

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

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

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

[clang] [RISCV] Enable target attribute when invoked through clang driver (PR #74889)

2023-12-10 Thread Craig Topper via cfe-commits

topperc wrote:

> > LGTM
> 
> > 
> 
> > Related question. If there is an -mcpu on the command line and target 
> > attribute changes the march, do we keep the original CPU in the -target-cpu 
> > attribute or drop it. The reason for all those negative features from the 
> > driver was to make the backend not infer any features from the CPU that 
> > weren't in the provided march. So I'm wondering if we have that issue with 
> > the target attribute now.
> 
> 
> 
> Compiler will keep target-cpu from command line when target attribute doesn't 
> assign new cpu option.

So that's a bug then. If the command line CPU has vector, but the target 
attribute doesn't. The backend will still use vector instructions.

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


[clang-tools-extra] [llvm] [clang] [compiler-rt] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 0e1a9e3084cd8dffa5d4f2cf6eabf9e7721e1cdd 
3409af09aec7f81af7e6e976a774aa945aa7f6ee -- 
compiler-rt/test/profile/instrprof-thinlto-indirect-call-promotion.cpp 
llvm/include/llvm/IR/GlobalValue.h llvm/include/llvm/ProfileData/InstrProf.h 
llvm/lib/IR/Globals.cpp llvm/lib/ProfileData/InstrProf.cpp 
llvm/lib/ProfileData/InstrProfReader.cpp 
llvm/unittests/ProfileData/InstrProfTest.cpp
``





View the diff from clang-format here.


``diff
diff --git 
a/compiler-rt/test/profile/instrprof-thinlto-indirect-call-promotion.cpp 
b/compiler-rt/test/profile/instrprof-thinlto-indirect-call-promotion.cpp
index 08cbd04611..06a4a8b616 100644
--- a/compiler-rt/test/profile/instrprof-thinlto-indirect-call-promotion.cpp
+++ b/compiler-rt/test/profile/instrprof-thinlto-indirect-call-promotion.cpp
@@ -95,4 +95,3 @@ void global_func() {
 //--- main.cpp
 #include "lib.h"
 int main() { global_func(); }
-

``




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


[compiler-rt] [clang-tools-extra] [llvm] [clang] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread via cfe-commits

github-actions[bot] wrote:




:warning: Python code formatter, darker found issues in your code. :warning:



You can test this locally with the following command:


``bash
darker --check --diff -r 
0e1a9e3084cd8dffa5d4f2cf6eabf9e7721e1cdd...3409af09aec7f81af7e6e976a774aa945aa7f6ee
 compiler-rt/test/profile/lit.cfg.py
``





View the diff from darker here.


``diff
--- lit.cfg.py  2023-12-11 02:48:07.00 +
+++ lit.cfg.py  2023-12-11 04:05:53.192500 +
@@ -146,11 +146,11 @@
 
 config.substitutions.append(
 ("%clang_pgouse=", build_invocation(clang_cflags) + " -fprofile-use=")
 )
 config.substitutions.append(
-   ("%clangxx_pgouse=", build_invocation(clang_cxxflags) + " -fprofile-use=")
+("%clangxx_pgouse=", build_invocation(clang_cxxflags) + " -fprofile-use=")
 )
 config.substitutions.append(
 ("%clangxx_profuse=", build_invocation(clang_cxxflags) + " 
-fprofile-instr-use=")
 )
 

``




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


[compiler-rt] [clang-tools-extra] [llvm] [clang] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Mingming Liu via cfe-commits


@@ -0,0 +1,60 @@
+#!/bin/bash
+
+if [ $# -lt 1 ]; then
+  echo "Path to clang required!"
+  echo "Usage: update_thinlto_indirect_call_promotion_inputs.sh 
/path/to/updated/clang"
+  exit 1
+else
+  CLANG=$1
+fi
+
+# Allows the script to be invoked from other directories.
+OUTDIR=$(dirname $(realpath -s $0))

minglotus-6 wrote:

Using `trap` on EXIT is indeed a more reliable way to clean up, thanks for 
pointing this out!

Now the test uses `rm -rf %t && split-file %s %t` as suggested in another 
comment.

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


[clang-tools-extra] [llvm] [clang] [compiler-rt] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Mingming Liu via cfe-commits


@@ -144,25 +145,27 @@ void GlobalObject::copyAttributesFrom(const GlobalObject 
*Src) {
 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
  GlobalValue::LinkageTypes Linkage,
  StringRef FileName) {
-
   // Value names may be prefixed with a binary '1' to indicate
   // that the backend should not modify the symbols due to any platform
   // naming convention. Do not include that '1' in the PGO profile name.
   if (Name[0] == '\1')
 Name = Name.substr(1);
 
-  std::string NewName = std::string(Name);
+  SmallString<64> GlobalName;
   if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
 // For local symbols, prepend the main file name to distinguish them.
 // Do not include the full path in the file name since there's no guarantee
 // that it will stay the same, e.g., if the files are checked out from
 // version control in different locations.
 if (FileName.empty())
-  NewName = NewName.insert(0, ":");
+  GlobalName.append("");
 else
-  NewName = NewName.insert(0, FileName.str() + ":");
+  GlobalName.append(FileName.str());
+
+GlobalName.append({kGlobalIdentifierDelimiter});

minglotus-6 wrote:

Done, use `+=` for all previous `append` calls since the operator is 
[overloaded](https://github.com/llvm/llvm-project/blob/a52ac7f93a31c664d8943242bdafd719d38f2ffa/llvm/include/llvm/ADT/SmallString.h#L279-L286)
 for `StringRef` and `char`

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


[compiler-rt] [clang-tools-extra] [llvm] [clang] [PGO][GlobalValue][LTO]In GlobalValues::getGlobalIdentifier, use semicolon as delimiter for local-linkage varibles. (PR #74008)

2023-12-10 Thread Mingming Liu via cfe-commits

minglotus-6 wrote:

> Mach-O (and 32-bit Windows) mangle global symbols with a leading `_`.

It's very helpful to know the name differences exist on Mach-O/COFF to 
construct a test case for issue 74565.

https://godbolt.org/z/686Y9vYod shows the name difference (cross comparing IR 
and machine assembly, with and without `--target arm64-apple-macosx`), meaning 
the compiler-rt test (to be added in this pull-request) could be a test case 
for issue 74565.

The summary captures key points of the bug. Just to clarify on one detail, the 
md5 hash is actually computed (or more accurately 
[mapped](https://github.com/llvm/llvm-project/blob/fc715e4cd942612a091097339841733757b53824/llvm/lib/ProfileData/InstrProf.cpp#L876-L885)
 from a profiled address to the [NameRef 
field](https://github.com/llvm/llvm-project/blob/fc715e4cd942612a091097339841733757b53824/compiler-rt/include/profile/InstrProfData.inc#L72)
 of  during `llvm-profdata merge  -o `) and 
[annotated](https://github.com/llvm/llvm-project/blob/fc715e4cd942612a091097339841733757b53824/llvm/lib/Transforms/Instrumentation/PGOInstrumentation.cpp#L1707)
 on an indirect-call instruction by `pgo-instr-use` pass. 
Module-summary-analysis pass makes use of this hash by 
[extracting](https://github.com/llvm/llvm-project/blob/fc715e4cd942612a091097339841733757b53824/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp#L454-L456)
 it from value profile metadata.

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


[clang] [DebugInfo] Fix duplicate DIFile when main file is preprocessed (PR #75022)

2023-12-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Fangrui Song (MaskRay)


Changes

When the main file is preprocessed and we change `MainFileName` to the
original source file name (e.g. `a.i => a.c`), the source manager does
not contain `a.c`, but we incorrectly associate the DIFile(a.c) with
md5(a.i). This causes CGDebugInfo::emitFunctionStart to create a
duplicate DIFile and leads to a spurious "inconsistent use of MD5
checksums" warning.

```
% cat a.c
void f() {}
% clang -c -g a.c  # no warning
% clang -E a.c -o a.i && clang -g -S a.i && clang -g -c a.s
a.s:9:2: warning: inconsistent use of MD5 checksums
.file   1 "a.c"
^
% grep DIFile a.ll
!1 = !DIFile(filename: "a.c", directory: "/tmp/c", checksumkind: CSK_MD5, 
checksum: "c5b2e246df7d5f53e176b097a0641c3d")
!11 = !DIFile(filename: "a.c", directory: "/tmp/c")
% grep 'file.*a.c' a.s
.file   "a.c"
.file   0 "/tmp/c" "a.c" md5 0x2d14ea70fee15102033eb8d899914cce
.file   1 "a.c"
```

Fix #56378 by disassociating md5(a.i) with a.c.


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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+6-4) 
- (modified) clang/test/CodeGen/debug-info-preprocessed-file.i (+4) 


``diff
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 7cf661994a29c7..37d7a6755d3908 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -554,14 +554,16 @@ void CGDebugInfo::CreateCompileUnit() {
 // If the main file name provided is identical to the input file name, and
 // if the input file is a preprocessed source, use the module name for
 // debug info. The module name comes from the name specified in the first
-// linemarker if the input is a preprocessed source.
+// linemarker if the input is a preprocessed source. In this case we don't
+// know the content to compute a checksum.
 if (MainFile->getName() == MainFileName &&
 FrontendOptions::getInputKindForExtension(
 MainFile->getName().rsplit('.').second)
-.isPreprocessed())
+.isPreprocessed()) {
   MainFileName = CGM.getModule().getName().str();
-
-CSKind = computeChecksum(SM.getMainFileID(), Checksum);
+} else {
+  CSKind = computeChecksum(SM.getMainFileID(), Checksum);
+}
   }
 
   llvm::dwarf::SourceLanguage LangTag;
diff --git a/clang/test/CodeGen/debug-info-preprocessed-file.i 
b/clang/test/CodeGen/debug-info-preprocessed-file.i
index 23fd26525e3bf0..c8a2307d46c316 100644
--- a/clang/test/CodeGen/debug-info-preprocessed-file.i
+++ b/clang/test/CodeGen/debug-info-preprocessed-file.i
@@ -6,6 +6,10 @@
 # 1 "" 2
 # 1 "preprocessed-input.c" 2
 
+/// The main file is preprocessed. We change it to preprocessed-input.c. Since
+/// the content is not available, we don't compute a checksum.
 // RUN: %clang -g -c -S -emit-llvm -o - %s | FileCheck %s
 // CHECK: !DICompileUnit(language: DW_LANG_C{{.*}}, file: ![[FILE:[0-9]+]]
 // CHECK: ![[FILE]] = !DIFile(filename: "/foo/bar/preprocessed-input.c"
+// CHECK-NOT: checksumkind:
+// CHECK-NOT: !DIFile(

``




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


[clang] [DebugInfo] Fix duplicate DIFile when main file is preprocessed (PR #75022)

2023-12-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Fangrui Song (MaskRay)


Changes

When the main file is preprocessed and we change `MainFileName` to the
original source file name (e.g. `a.i => a.c`), the source manager does
not contain `a.c`, but we incorrectly associate the DIFile(a.c) with
md5(a.i). This causes CGDebugInfo::emitFunctionStart to create a
duplicate DIFile and leads to a spurious "inconsistent use of MD5
checksums" warning.

```
% cat a.c
void f() {}
% clang -c -g a.c  # no warning
% clang -E a.c -o a.i && clang -g -S a.i && clang -g -c a.s
a.s:9:2: warning: inconsistent use of MD5 checksums
.file   1 "a.c"
^
% grep DIFile a.ll
!1 = !DIFile(filename: "a.c", directory: "/tmp/c", checksumkind: CSK_MD5, 
checksum: "c5b2e246df7d5f53e176b097a0641c3d")
!11 = !DIFile(filename: "a.c", directory: "/tmp/c")
% grep 'file.*a.c' a.s
.file   "a.c"
.file   0 "/tmp/c" "a.c" md5 0x2d14ea70fee15102033eb8d899914cce
.file   1 "a.c"
```

Fix #56378 by disassociating md5(a.i) with a.c.


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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+6-4) 
- (modified) clang/test/CodeGen/debug-info-preprocessed-file.i (+4) 


``diff
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 7cf661994a29c7..37d7a6755d3908 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -554,14 +554,16 @@ void CGDebugInfo::CreateCompileUnit() {
 // If the main file name provided is identical to the input file name, and
 // if the input file is a preprocessed source, use the module name for
 // debug info. The module name comes from the name specified in the first
-// linemarker if the input is a preprocessed source.
+// linemarker if the input is a preprocessed source. In this case we don't
+// know the content to compute a checksum.
 if (MainFile->getName() == MainFileName &&
 FrontendOptions::getInputKindForExtension(
 MainFile->getName().rsplit('.').second)
-.isPreprocessed())
+.isPreprocessed()) {
   MainFileName = CGM.getModule().getName().str();
-
-CSKind = computeChecksum(SM.getMainFileID(), Checksum);
+} else {
+  CSKind = computeChecksum(SM.getMainFileID(), Checksum);
+}
   }
 
   llvm::dwarf::SourceLanguage LangTag;
diff --git a/clang/test/CodeGen/debug-info-preprocessed-file.i 
b/clang/test/CodeGen/debug-info-preprocessed-file.i
index 23fd26525e3bf0..c8a2307d46c316 100644
--- a/clang/test/CodeGen/debug-info-preprocessed-file.i
+++ b/clang/test/CodeGen/debug-info-preprocessed-file.i
@@ -6,6 +6,10 @@
 # 1 "" 2
 # 1 "preprocessed-input.c" 2
 
+/// The main file is preprocessed. We change it to preprocessed-input.c. Since
+/// the content is not available, we don't compute a checksum.
 // RUN: %clang -g -c -S -emit-llvm -o - %s | FileCheck %s
 // CHECK: !DICompileUnit(language: DW_LANG_C{{.*}}, file: ![[FILE:[0-9]+]]
 // CHECK: ![[FILE]] = !DIFile(filename: "/foo/bar/preprocessed-input.c"
+// CHECK-NOT: checksumkind:
+// CHECK-NOT: !DIFile(

``




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


[clang] [DebugInfo] Fix duplicate DIFile when main file is preprocessed (PR #75022)

2023-12-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-debuginfo

Author: Fangrui Song (MaskRay)


Changes

When the main file is preprocessed and we change `MainFileName` to the
original source file name (e.g. `a.i => a.c`), the source manager does
not contain `a.c`, but we incorrectly associate the DIFile(a.c) with
md5(a.i). This causes CGDebugInfo::emitFunctionStart to create a
duplicate DIFile and leads to a spurious "inconsistent use of MD5
checksums" warning.

```
% cat a.c
void f() {}
% clang -c -g a.c  # no warning
% clang -E a.c -o a.i && clang -g -S a.i && clang -g -c a.s
a.s:9:2: warning: inconsistent use of MD5 checksums
.file   1 "a.c"
^
% grep DIFile a.ll
!1 = !DIFile(filename: "a.c", directory: "/tmp/c", checksumkind: CSK_MD5, 
checksum: "c5b2e246df7d5f53e176b097a0641c3d")
!11 = !DIFile(filename: "a.c", directory: "/tmp/c")
% grep 'file.*a.c' a.s
.file   "a.c"
.file   0 "/tmp/c" "a.c" md5 0x2d14ea70fee15102033eb8d899914cce
.file   1 "a.c"
```

Fix #56378 by disassociating md5(a.i) with a.c.


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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+6-4) 
- (modified) clang/test/CodeGen/debug-info-preprocessed-file.i (+4) 


``diff
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 7cf661994a29c7..37d7a6755d3908 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -554,14 +554,16 @@ void CGDebugInfo::CreateCompileUnit() {
 // If the main file name provided is identical to the input file name, and
 // if the input file is a preprocessed source, use the module name for
 // debug info. The module name comes from the name specified in the first
-// linemarker if the input is a preprocessed source.
+// linemarker if the input is a preprocessed source. In this case we don't
+// know the content to compute a checksum.
 if (MainFile->getName() == MainFileName &&
 FrontendOptions::getInputKindForExtension(
 MainFile->getName().rsplit('.').second)
-.isPreprocessed())
+.isPreprocessed()) {
   MainFileName = CGM.getModule().getName().str();
-
-CSKind = computeChecksum(SM.getMainFileID(), Checksum);
+} else {
+  CSKind = computeChecksum(SM.getMainFileID(), Checksum);
+}
   }
 
   llvm::dwarf::SourceLanguage LangTag;
diff --git a/clang/test/CodeGen/debug-info-preprocessed-file.i 
b/clang/test/CodeGen/debug-info-preprocessed-file.i
index 23fd26525e3bf0..c8a2307d46c316 100644
--- a/clang/test/CodeGen/debug-info-preprocessed-file.i
+++ b/clang/test/CodeGen/debug-info-preprocessed-file.i
@@ -6,6 +6,10 @@
 # 1 "" 2
 # 1 "preprocessed-input.c" 2
 
+/// The main file is preprocessed. We change it to preprocessed-input.c. Since
+/// the content is not available, we don't compute a checksum.
 // RUN: %clang -g -c -S -emit-llvm -o - %s | FileCheck %s
 // CHECK: !DICompileUnit(language: DW_LANG_C{{.*}}, file: ![[FILE:[0-9]+]]
 // CHECK: ![[FILE]] = !DIFile(filename: "/foo/bar/preprocessed-input.c"
+// CHECK-NOT: checksumkind:
+// CHECK-NOT: !DIFile(

``




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


[clang] [DebugInfo] Fix duplicate DIFile when main file is preprocessed (PR #75022)

2023-12-10 Thread Fangrui Song via cfe-commits

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

When the main file is preprocessed and we change `MainFileName` to the
original source file name (e.g. `a.i => a.c`), the source manager does
not contain `a.c`, but we incorrectly associate the DIFile(a.c) with
md5(a.i). This causes CGDebugInfo::emitFunctionStart to create a
duplicate DIFile and leads to a spurious "inconsistent use of MD5
checksums" warning.

```
% cat a.c
void f() {}
% clang -c -g a.c  # no warning
% clang -E a.c -o a.i && clang -g -S a.i && clang -g -c a.s
a.s:9:2: warning: inconsistent use of MD5 checksums
.file   1 "a.c"
^
% grep DIFile a.ll
!1 = !DIFile(filename: "a.c", directory: "/tmp/c", checksumkind: CSK_MD5, 
checksum: "c5b2e246df7d5f53e176b097a0641c3d")
!11 = !DIFile(filename: "a.c", directory: "/tmp/c")
% grep 'file.*a.c' a.s
.file   "a.c"
.file   0 "/tmp/c" "a.c" md5 0x2d14ea70fee15102033eb8d899914cce
.file   1 "a.c"
```

Fix #56378 by disassociating md5(a.i) with a.c.


>From ace1e56b3db30466748dc7d8c5ba10ebf4001bd5 Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Sun, 10 Dec 2023 19:18:36 -0800
Subject: [PATCH] [DebugInfo] Fix duplicate DIFile when main file is
 preprocessed

When the main file is preprocessed and we change `MainFileName` to the
original source file name (e.g. `a.i => a.c`), the source manager does
not contain `a.c`, but we incorrectly associate the DIFile(a.c) with
md5(a.i). This causes CGDebugInfo::emitFunctionStart to create a
duplicate DIFile and leads to a spurious "inconsistent use of MD5
checksums" warning.

```
% cat a.c
void f() {}
% clang -c -g a.c  # no warning
% clang -E a.c -o a.i && clang -g -S a.i && clang -g -c a.s
a.s:9:2: warning: inconsistent use of MD5 checksums
.file   1 "a.c"
^
% grep DIFile a.ll
!1 = !DIFile(filename: "a.c", directory: "/tmp/c", checksumkind: CSK_MD5, 
checksum: "c5b2e246df7d5f53e176b097a0641c3d")
!11 = !DIFile(filename: "a.c", directory: "/tmp/c")
% grep 'file.*a.c' a.s
.file   "a.c"
.file   0 "/tmp/c" "a.c" md5 0x2d14ea70fee15102033eb8d899914cce
.file   1 "a.c"
```

Fix #56378 by disassociating md5(a.i) with a.c.
---
 clang/lib/CodeGen/CGDebugInfo.cpp | 10 ++
 clang/test/CodeGen/debug-info-preprocessed-file.i |  4 
 2 files changed, 10 insertions(+), 4 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 7cf661994a29c..37d7a6755d390 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -554,14 +554,16 @@ void CGDebugInfo::CreateCompileUnit() {
 // If the main file name provided is identical to the input file name, and
 // if the input file is a preprocessed source, use the module name for
 // debug info. The module name comes from the name specified in the first
-// linemarker if the input is a preprocessed source.
+// linemarker if the input is a preprocessed source. In this case we don't
+// know the content to compute a checksum.
 if (MainFile->getName() == MainFileName &&
 FrontendOptions::getInputKindForExtension(
 MainFile->getName().rsplit('.').second)
-.isPreprocessed())
+.isPreprocessed()) {
   MainFileName = CGM.getModule().getName().str();
-
-CSKind = computeChecksum(SM.getMainFileID(), Checksum);
+} else {
+  CSKind = computeChecksum(SM.getMainFileID(), Checksum);
+}
   }
 
   llvm::dwarf::SourceLanguage LangTag;
diff --git a/clang/test/CodeGen/debug-info-preprocessed-file.i 
b/clang/test/CodeGen/debug-info-preprocessed-file.i
index 23fd26525e3bf..c8a2307d46c31 100644
--- a/clang/test/CodeGen/debug-info-preprocessed-file.i
+++ b/clang/test/CodeGen/debug-info-preprocessed-file.i
@@ -6,6 +6,10 @@
 # 1 "" 2
 # 1 "preprocessed-input.c" 2
 
+/// The main file is preprocessed. We change it to preprocessed-input.c. Since
+/// the content is not available, we don't compute a checksum.
 // RUN: %clang -g -c -S -emit-llvm -o - %s | FileCheck %s
 // CHECK: !DICompileUnit(language: DW_LANG_C{{.*}}, file: ![[FILE:[0-9]+]]
 // CHECK: ![[FILE]] = !DIFile(filename: "/foo/bar/preprocessed-input.c"
+// CHECK-NOT: checksumkind:
+// CHECK-NOT: !DIFile(

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


[llvm] [clang] [RISCV] Add support for experimental Zimop extension (PR #74824)

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

wangpc-pp wrote:

Please reorginize the patch as @dtcxzyw suggested. :-)

I didn't notice this extension before, so I may not be asking the right 
question here: These MOPs can be redefined, then, are we able to schedule them 
in compiler? Becase we don't know the cost of MOPs if we don't know how MOPs 
are used. For example, MOPs can be redefined as simple ALU instructions, or, it 
can be instructions with large cost like DIV/REM. I don't know how to model it 
now, but I don't think defining Sched resources for MOPs is the right way.

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


[llvm] [clang] [ValueTracking] Add dominating condition support in computeKnownBits() (PR #73662)

2023-12-10 Thread via cfe-commits

yonghong-song wrote:

Hi, @nikic,
This patch caused a bpf verifier regression with one of bpf selftests. The 
details can be found in kernel bpf mailing list.
   https://lore.kernel.org/bpf/0ff5f011-7524-4550-89eb-bb2c89f69...@linux.dev/

Note that bpf verification failure here does not mean that generated code is 
incorrect. It means llvm generates 'more complex' code and the current verifier 
cannot handle that.

I created a unit test like below:
```
 $ cat iters.bpf.o.i
 typedef unsigned long long __u64;
 
 struct bpf_iter_num {
  __u64 __opaque[1];
 } __attribute__((aligned(8)));
 
 extern int bpf_iter_num_new(struct bpf_iter_num *it, int start, int end) 
__attribute__((weak))  __attribute__((section(".ksyms")));
 extern int *bpf_iter_num_next(struct bpf_iter_num *it) __attribute__((weak)) 
__attribute__((section(".ksyms")));
 extern void bpf_iter_num_destroy(struct bpf_iter_num *it) 
__attribute__((weak)) __attribute__((section(".ksyms")));
 
 struct {
  int data[32];
  int n;
 } loop_data;
 
 int iter_arr_with_actual_elem_count(const void *ctx)
 {
  int i, n = loop_data.n, sum = 0;
 
  if (n > (sizeof(loop_data.data) / sizeof((loop_data.data)[0])))
   return 0;
 
  for ( struct bpf_iter_num ___it __attribute__((aligned(8), 
cleanup(bpf_iter_num_destroy))), *___p __attribute__((unused))  = ( 
bpf_iter_num_new(&___it, (0), (n)), (void)bpf_iter_num_destroy, (void *)0); ({ 
int *___t = bpf_iter_num_next(&___it);  (___t && ((i) = *___t, (i) >= (0) && 
(i) < (n))); }); ) {
 
   sum += loop_data.data[i];
  }
 
  return sum;
 }
```

The compilation flag:
  clang -O2 -mcpu=v4 iters.bpf.o.i -c --target=bpf -mllvm -print-after-all

For a llvm whose top commit is the patch, the assembly looks like
```
 :
   0:   b4 07 00 00 00 00 00 00 w7 = 0x0
   1:   18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0x0 ll
   3:   61 16 80 00 00 00 00 00 r6 = *(u32 *)(r1 + 0x80)
   4:   26 06 1b 00 20 00 00 00 if w6 > 0x20 goto +0x1b 
   5:   bf a8 00 00 00 00 00 00 r8 = r10
   6:   07 08 00 00 f8 ff ff ff r8 += -0x8
   7:   bf 81 00 00 00 00 00 00 r1 = r8
   8:   b4 02 00 00 00 00 00 00 w2 = 0x0
   9:   bc 63 00 00 00 00 00 00 w3 = w6
  10:   85 10 00 00 ff ff ff ff call -0x1
  11:   bf 81 00 00 00 00 00 00 r1 = r8
  12:   85 10 00 00 ff ff ff ff call -0x1
  13:   15 00 02 00 00 00 00 00 if r0 == 0x0 goto +0x2 

0070 :
  14:   81 01 00 00 00 00 00 00 r1 = *(s32 *)(r0 + 0x0)  <=== a sign 
extension here, upper 32bit may be 0x
  15:   ae 61 04 00 00 00 00 00 if w1 < w6 goto +0x4   <=== 
refine the value range of r1/w1 depending on which branch is taken.

0080 :
  16:   bf a1 00 00 00 00 00 00 r1 = r10
  17:   07 01 00 00 f8 ff ff ff r1 += -0x8
  18:   85 10 00 00 ff ff ff ff call -0x1
  19:   05 00 0c 00 00 00 00 00 goto +0xc 

00a0 :
  20:   67 01 00 00 02 00 00 00 r1 <<= 0x2 <=== reaching here from insn 
15, the verifier assumes top 32bit is not zero
   
<=== and verification will fail at insn 23.
  21:   18 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r2 = 0x0 ll
  23:   0f 12 00 00 00 00 00 00 r2 += r1
  24:   61 28 00 00 00 00 00 00 r8 = *(u32 *)(r2 + 0x0)
  25:   0c 78 00 00 00 00 00 00 w8 += w7
  26:   bf a1 00 00 00 00 00 00 r1 = r10
  27:   07 01 00 00 f8 ff ff ff r1 += -0x8
  28:   85 10 00 00 ff ff ff ff call -0x1
  29:   bc 87 00 00 00 00 00 00 w7 = w8
  30:   15 00 f1 ff 00 00 00 00 if r0 == 0x0 goto -0xf 
  31:   05 00 ee ff 00 00 00 00 goto -0x12 

0100 :
  32:   bc 70 00 00 00 00 00 00 w0 = w7
  33:   95 00 00 00 00 00 00 00 exit
```
In the above, I added a few comments to show why verification failure. The more 
detail can be found in
  https://lore.kernel.org/bpf/0ff5f011-7524-4550-89eb-bb2c89f69...@linux.dev/
as well.

For a llvm whose top commit is the patch below this commit, the assembly looks 
like
```
 :
   0:   b4 07 00 00 00 00 00 00 w7 = 0x0
   1:   18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0x0 ll
   3:   61 16 80 00 00 00 00 00 r6 = *(u32 *)(r1 + 0x80)
   4:   26 06 1c 00 20 00 00 00 if w6 > 0x20 goto +0x1c 
   5:   bf a8 00 00 00 00 00 00 r8 = r10
   6:   07 08 00 00 f8 ff ff ff r8 += -0x8
   7:   bf 81 00 00 00 00 00 00 r1 = r8
   8:   b4 02 00 00 00 00 00 00 w2 = 0x0
   9:   bc 63 00 00 00 00 00 00 w3 = w6
  10:   85 10 00 00 ff ff ff ff call -0x1
  11:   bf 81 00 00 00 00 00 00 r1 = r8
  12:   85 10 00 00 ff ff ff ff call -0x1
  13:   15 00 03 00 00 00 00 00 if r0 == 0x0 goto +0x3 

0070 :
  14:   61 01 00 00 00 00 00 00 r1 = *(u32 *)(r0 + 0x0)  <=

[flang] [clang] [flang][driver] Rename `flang-new` as `flang` (PR #74377)

2023-12-10 Thread via cfe-commits


@@ -15,17 +15,13 @@ local:
 ```
 
 There are two main drivers in Flang:

h-vetinari wrote:

It might be worth spending a paragraph or section explaining the historical 
role of `flang-new`, if only so that people understand why it's (eventually) 
not available anymore.

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


[flang] [clang] [flang][driver] Rename `flang-new` as `flang` (PR #74377)

2023-12-10 Thread via cfe-commits


@@ -193,26 +190,29 @@ driver, `clang -cc1` and consists of the following 
classes:
 This list is not exhaustive and only covers the main classes that implement the
 driver. The main entry point for the frontend driver, `fc1_main`, is
 implemented in `flang/tools/flang-driver/driver.cpp`. It can be accessed by
-invoking the compiler driver, `flang-new`, with the `-fc1` flag.
+invoking the compiler driver, `flang`, with the `-fc1` flag.
 
 The frontend driver will only run one action at a time. If you specify multiple
 action flags, only the last one will be taken into account. The default action
 is `ParseSyntaxOnlyAction`, which corresponds to `-fsyntax-only`. In other
-words, `flang-new -fc1 ` is equivalent to `flang-new -fc1 
-fsyntax-only
+words, `flang -fc1 ` is equivalent to `flang -fc1 -fsyntax-only
 `.
 
 ## The `flang-to-external-fc` script
-The `flang-to-external-fc` wrapper script for `flang-new` was introduced as a
-development tool and to facilitate testing. The `flang-to-external-fc` wrapper
-script will:
-* use `flang-new` to unparse the input source file (i.e. it will run `flang-new
-  -fc1 -fdebug-unparse `), and then
+The `flang-to-external-fc` wrapper script for `flang` was introduced as a
+development tool and to facilitate testing. While code-generation is not
+available in Flang, you can use it as a drop-in replacement for other Fortran
+compilers in your build scripts.

h-vetinari wrote:

The "While" sentence here is jarring to me. There _is_ code generation now?! 
Perhaps:
```suggestion
The `flang-to-external-fc` wrapper script for `flang` was introduced as a
development tool and to facilitate testing. In particular, it can be used to
delegate code generation to other Fortran compilers. Before Flang gained its
own code generation capabilities, this used to be the only way to create
actual binaries.
```

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


[clang] [flang] [flang][driver] Rename `flang-new` as `flang` (PR #74377)

2023-12-10 Thread via cfe-commits

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


[clang] [flang] [flang][driver] Rename `flang-new` as `flang` (PR #74377)

2023-12-10 Thread via cfe-commits

https://github.com/h-vetinari commented:

Some drive-by comments - very happy to see this happening!

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


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

2023-12-10 Thread via cfe-commits

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 44dc1e0baae7c4b8a02ba06dcf396d3d452aa873 
a14cfc5f15fcddd4b89155c4f3f58a21c27140c4 -- clang/lib/Sema/SemaConcept.cpp 
clang/lib/Sema/SemaTemplateDeduction.cpp clang/lib/Sema/TreeTransform.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index f8556b5d9a..18f038025d 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -932,7 +932,7 @@ bool Sema::CheckInstantiatedFunctionTemplateConstraints(
 
   //   // }
   // }
-  
+
   // Check the number of the Concept template parameters
   // for (auto P : TemplateAC) {
   //   // const TemplateTypeParmDecl *CD = dyn_cast(P);
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 10e93f8555..7c3702e006 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3614,10 +3614,10 @@ Sema::TemplateDeductionResult 
Sema::FinishTemplateArgumentDeduction(
   SFINAETrap Trap(*this);
 
   auto *Method = dyn_cast(FunctionTemplate);
-  for(auto arg: Deduced) {
+  for (auto arg : Deduced) {
 auto ty = arg.getAsType();
-if ( ty->isBuiltinType() ) {
-return TDK_SubstitutionFailure;
+if (ty->isBuiltinType()) {
+  return TDK_SubstitutionFailure;
 }
   }
   // Enter a new template instantiation context while we instantiate the

``




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


[clang] [RISCV] Enable target attribute when invoked through clang driver (PR #74889)

2023-12-10 Thread Piyou Chen via cfe-commits

BeMg wrote:

> LGTM
> 
> Related question. If there is an -mcpu on the command line and target 
> attribute changes the march, do we keep the original CPU in the -target-cpu 
> attribute or drop it. The reason for all those negative features from the 
> driver was to make the backend not infer any features from the CPU that 
> weren't in the provided march. So I'm wondering if we have that issue with 
> the target attribute now.

Compiler will keep target-cpu from command line when target attribute doesn't 
assign new cpu option.

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


[clang] [RISCV] Enable target attribute when invoked through clang driver (PR #74889)

2023-12-10 Thread Piyou Chen via cfe-commits

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

LGTM

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


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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits

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

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

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

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

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

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

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

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

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

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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-llvm-ir

Author: Elvis Wang (ElvisWang123)


Changes

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

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

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

---

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


24 Files Affected:

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


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

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

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

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

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

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

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

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

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

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

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

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

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

2023-12-10 Thread via cfe-commits

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

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

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

Added: 


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

Removed: 




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



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


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

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

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


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

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

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

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

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

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

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


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

2023-12-10 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


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





View the diff from clang-format here.


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

``




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


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

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

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

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

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

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

Added: 


Modified: 
clang/lib/Serialization/ASTWriterDecl.cpp

Removed: 




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



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


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

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

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

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

LOG: [NFC] [Serialization] Packing more bits

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

Added: 


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

Removed: 




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

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

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

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

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


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

2023-12-10 Thread via cfe-commits

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

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

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

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

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

Added: 


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

Removed: 




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

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

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

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

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

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

ChuanqiXu9 wrote:

@sam-mccall ping!

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


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

2023-12-10 Thread via cfe-commits

knightXun wrote:

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

thanks for the hit! 

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


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

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

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

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

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

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

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

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

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


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


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

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


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

mtrofin wrote:

Done, will move it to the cpp next.

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


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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits

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


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

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


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

aaronpuchert wrote:

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

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


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

2023-12-10 Thread via cfe-commits

XDeme wrote:

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

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


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

2023-12-10 Thread via cfe-commits


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

XDeme wrote:

Fixed

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


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

2023-12-10 Thread via cfe-commits


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

XDeme wrote:

Fixed

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


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

2023-12-10 Thread via cfe-commits


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

XDeme wrote:

Fixed

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


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

2023-12-10 Thread via cfe-commits

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

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

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

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

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

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

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

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

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

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

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

2023-12-10 Thread via cfe-commits

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


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

2023-12-10 Thread via cfe-commits


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

XDeme wrote:

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

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

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

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

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


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

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


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

aaronpuchert wrote:

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

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


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

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


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

aaronpuchert wrote:

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

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


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

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

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


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

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


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

aaronpuchert wrote:

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

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

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


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

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


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

aaronpuchert wrote:

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

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


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

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


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

aaronpuchert wrote:

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

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

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

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


  1   2   >