[llvm-branch-commits] [llvm] release/18.x: [InstCombine] Fix miscompilation in PR83947 (#83993) (PR #84021)

2024-03-07 Thread Yingwei Zheng via llvm-branch-commits

dtcxzyw wrote:

@nikic Do you know how to add a commit to this PR?
```
diff --git a/llvm/test/Transforms/InstCombine/masked_intrinsics.ll 
b/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
index 2704905f7a35..c87c1199f727 100644
--- a/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
+++ b/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
@@ -292,7 +292,11 @@ entry:
 define void @scatter_nxv4i16_uniform_vals_uniform_ptrs_all_active_mask(ptr 
%dst, i16 %val) {
 ; CHECK-LABEL: @scatter_nxv4i16_uniform_vals_uniform_ptrs_all_active_mask(
 ; CHECK-NEXT:  entry:
-; CHECK-NEXT:store i16 [[VAL:%.*]], ptr [[DST:%.*]], align 2
+; CHECK-NEXT:[[BROADCAST_SPLATINSERT:%.*]] = insertelement  poison, ptr [[DST:%.*]], i64 0
+; CHECK-NEXT:[[BROADCAST_SPLAT:%.*]] = shufflevector  
[[BROADCAST_SPLATINSERT]],  poison,  
zeroinitializer
+; CHECK-NEXT:[[BROADCAST_VALUE:%.*]] = insertelement  
poison, i16 [[VAL:%.*]], i64 0
+; CHECK-NEXT:[[BROADCAST_SPLATVALUE:%.*]] = shufflevector  [[BROADCAST_VALUE]],  poison,  
zeroinitializer
+; CHECK-NEXT:call void @llvm.masked.scatter.nxv4i16.nxv4p0( [[BROADCAST_SPLATVALUE]],  [[BROADCAST_SPLAT]], i32 2, 
 shufflevector ( insertelement ( zeroinitializer, i1 true, i32 0),  zeroinitializer, 
 zeroinitializer))
 ; CHECK-NEXT:ret void
 ;
 entry:
```

It is a regression. But I think it should be fixed by 
https://github.com/llvm/llvm-project/commit/fd07b8f809eb64af9b29331ff6b94904b3159f84.


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


[llvm-branch-commits] [clang] release/18.x: [clang][fat-lto-objects] Make module flags match non-FatLTO pipelines (#83159) (PR #84290)

2024-03-07 Thread via llvm-branch-commits

https://github.com/llvmbot created 
https://github.com/llvm/llvm-project/pull/84290

Backport 7d8b50aaab8e0f935e3cb1f3f397e98b9e3ee241

Requested by: @stsp

>From 8a46ddd31a82b8911075489666abde234a6833c6 Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Wed, 28 Feb 2024 19:11:55 -0800
Subject: [PATCH] [clang][fat-lto-objects] Make module flags match non-FatLTO
 pipelines (#83159)

In addition to being rather hard to follow, there isn't a good reason
why FatLTO shouldn't just share the same code for setting module flags
for (Thin)LTO. This patch simplifies the logic and makes sure we use set
these flags in a consistent way, independent of FatLTO.

Additionally, we now test that output in the .llvm.lto section actually
matches the output from Full and Thin LTO compilation.

(cherry picked from commit 7d8b50aaab8e0f935e3cb1f3f397e98b9e3ee241)
---
 clang/lib/CodeGen/BackendUtil.cpp| 32 ++--
 clang/test/CodeGen/fat-lto-objects.c | 21 +-
 2 files changed, 36 insertions(+), 17 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 7877e20d77f772..4f22d35f9d3a94 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -186,6 +186,14 @@ class EmitAssemblyHelper {
TargetTriple.getVendor() != llvm::Triple::Apple;
   }
 
+  /// Check whether we should emit a flag for UnifiedLTO.
+  /// The UnifiedLTO module flag should be set when UnifiedLTO is enabled for
+  /// ThinLTO or Full LTO with module summaries.
+  bool shouldEmitUnifiedLTOModueFlag() const {
+return CodeGenOpts.UnifiedLTO &&
+   (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
+  }
+
 public:
   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  const HeaderSearchOptions &HeaderSearchOpts,
@@ -1029,7 +1037,8 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL ||
+  CodeGenOpts.FatLTO) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
@@ -1040,11 +1049,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!ThinLinkOS)
 return;
 }
-if (CodeGenOpts.UnifiedLTO)
-  TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", 
uint32_t(1));
 MPM.addPass(ThinLTOBitcodeWriterPass(
 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
-  } else {
+  } else if (Action == Backend_EmitLL) {
 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
 /*EmitLTOSummary=*/true));
   }
@@ -1058,24 +1065,17 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
   TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
-if (CodeGenOpts.UnifiedLTO)
-  TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", 
uint32_t(1));
   }
-  if (Action == Backend_EmitBC)
+  if (Action == Backend_EmitBC) {
 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
   EmitLTOSummary));
-  else
+  } else if (Action == Backend_EmitLL) {
 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
 EmitLTOSummary));
+  }
 }
-  }
-  if (CodeGenOpts.FatLTO) {
-// Set the EnableSplitLTOUnit and UnifiedLTO module flags, since FatLTO
-// uses a different action than Backend_EmitBC or Backend_EmitLL.
-if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
-  TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
-   uint32_t(CodeGenOpts.EnableSplitLTOUnit));
-if (CodeGenOpts.UnifiedLTO && !TheModule->getModuleFlag("UnifiedLTO"))
+
+if (shouldEmitUnifiedLTOModueFlag())
   TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
   }
 
diff --git a/clang/test/CodeGen/fat-lto-objects.c 
b/clang/test/CodeGen/fat-lto-objects.c
index afce798c5c8194..b50567c024fc8c 100644
--- a/clang/test/CodeGen/fat-lto-objects.c
+++ b/clang/test/CodeGen/fat-lto-objects.c
@@ -11,10 +11,11 @@
 // RUN: llvm-objcopy --dump-section=.llvm.lto=%t.full.split.bc %t.full.split.o
 // RUN: llvm-dis %t.full.split.bc -o - | FileCheck %s 
--check-prefixes=FULL,SPLIT,NOUNIFIED
 
+/// Full LTO always sets EnableSplitLTOUnit when the summary is used.
 // RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=full 
-ffat-lto-objects -emit-obj < %s -o %t.full.nosplit.o
 // RUN: llvm-r

[llvm-branch-commits] [clang] release/18.x: [clang][fat-lto-objects] Make module flags match non-FatLTO pipelines (#83159) (PR #84290)

2024-03-07 Thread via llvm-branch-commits

https://github.com/llvmbot milestoned 
https://github.com/llvm/llvm-project/pull/84290
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] release/18.x: [clang][fat-lto-objects] Make module flags match non-FatLTO pipelines (#83159) (PR #84290)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:

@teresajohnson What do you think about merging this PR to the release branch?

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


[llvm-branch-commits] [clang] release/18.x: [clang][fat-lto-objects] Make module flags match non-FatLTO pipelines (#83159) (PR #84290)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: None (llvmbot)


Changes

Backport 7d8b50aaab8e0f935e3cb1f3f397e98b9e3ee241

Requested by: @stsp

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


2 Files Affected:

- (modified) clang/lib/CodeGen/BackendUtil.cpp (+16-16) 
- (modified) clang/test/CodeGen/fat-lto-objects.c (+20-1) 


``diff
diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 7877e20d77f772..4f22d35f9d3a94 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -186,6 +186,14 @@ class EmitAssemblyHelper {
TargetTriple.getVendor() != llvm::Triple::Apple;
   }
 
+  /// Check whether we should emit a flag for UnifiedLTO.
+  /// The UnifiedLTO module flag should be set when UnifiedLTO is enabled for
+  /// ThinLTO or Full LTO with module summaries.
+  bool shouldEmitUnifiedLTOModueFlag() const {
+return CodeGenOpts.UnifiedLTO &&
+   (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
+  }
+
 public:
   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  const HeaderSearchOptions &HeaderSearchOpts,
@@ -1029,7 +1037,8 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL ||
+  CodeGenOpts.FatLTO) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
@@ -1040,11 +1049,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!ThinLinkOS)
 return;
 }
-if (CodeGenOpts.UnifiedLTO)
-  TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", 
uint32_t(1));
 MPM.addPass(ThinLTOBitcodeWriterPass(
 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
-  } else {
+  } else if (Action == Backend_EmitLL) {
 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
 /*EmitLTOSummary=*/true));
   }
@@ -1058,24 +1065,17 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
   TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
-if (CodeGenOpts.UnifiedLTO)
-  TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", 
uint32_t(1));
   }
-  if (Action == Backend_EmitBC)
+  if (Action == Backend_EmitBC) {
 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
   EmitLTOSummary));
-  else
+  } else if (Action == Backend_EmitLL) {
 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
 EmitLTOSummary));
+  }
 }
-  }
-  if (CodeGenOpts.FatLTO) {
-// Set the EnableSplitLTOUnit and UnifiedLTO module flags, since FatLTO
-// uses a different action than Backend_EmitBC or Backend_EmitLL.
-if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
-  TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
-   uint32_t(CodeGenOpts.EnableSplitLTOUnit));
-if (CodeGenOpts.UnifiedLTO && !TheModule->getModuleFlag("UnifiedLTO"))
+
+if (shouldEmitUnifiedLTOModueFlag())
   TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
   }
 
diff --git a/clang/test/CodeGen/fat-lto-objects.c 
b/clang/test/CodeGen/fat-lto-objects.c
index afce798c5c8194..b50567c024fc8c 100644
--- a/clang/test/CodeGen/fat-lto-objects.c
+++ b/clang/test/CodeGen/fat-lto-objects.c
@@ -11,10 +11,11 @@
 // RUN: llvm-objcopy --dump-section=.llvm.lto=%t.full.split.bc %t.full.split.o
 // RUN: llvm-dis %t.full.split.bc -o - | FileCheck %s 
--check-prefixes=FULL,SPLIT,NOUNIFIED
 
+/// Full LTO always sets EnableSplitLTOUnit when the summary is used.
 // RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=full 
-ffat-lto-objects -emit-obj < %s -o %t.full.nosplit.o
 // RUN: llvm-readelf -S %t.full.nosplit.o | FileCheck %s --check-prefixes=ELF
 // RUN: llvm-objcopy --dump-section=.llvm.lto=%t.full.nosplit.bc 
%t.full.nosplit.o
-// RUN: llvm-dis %t.full.nosplit.bc -o - | FileCheck %s 
--check-prefixes=FULL,NOSPLIT,NOUNIFIED
+// RUN: llvm-dis %t.full.nosplit.bc -o - | FileCheck %s 
--check-prefixes=FULL,SPLIT,NOUNIFIED
 
 // RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=thin 
-fsplit-lto-unit -ffat-lto-objects -emit-obj < %s -o %t.thin.split.o
 // RUN: llvm-readelf -S %t.thin.split.o | FileCheck %s --check-prefixes=ELF
@@ -34,6 +35,21 @@
 // RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -f

[llvm-branch-commits] [llvm] release/18.x: [InstCombine] Fix miscompilation in PR83947 (#83993) (PR #84021)

2024-03-07 Thread Nikita Popov via llvm-branch-commits

nikic wrote:

@dtcxzyw You should be able to push to the branch in the llvmbot repo.

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


[llvm-branch-commits] [llvm] release/18.x: [InstCombine] Fix miscompilation in PR83947 (#83993) (PR #84021)

2024-03-07 Thread Yingwei Zheng via llvm-branch-commits

dtcxzyw wrote:

> @nikic Do you know how to add a commit to this PR?
> 
> ```
> diff --git a/llvm/test/Transforms/InstCombine/masked_intrinsics.ll 
> b/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
> index 2704905f7a35..c87c1199f727 100644
> --- a/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
> +++ b/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
> @@ -292,7 +292,11 @@ entry:
>  define void @scatter_nxv4i16_uniform_vals_uniform_ptrs_all_active_mask(ptr 
> %dst, i16 %val) {
>  ; CHECK-LABEL: @scatter_nxv4i16_uniform_vals_uniform_ptrs_all_active_mask(
>  ; CHECK-NEXT:  entry:
> -; CHECK-NEXT:store i16 [[VAL:%.*]], ptr [[DST:%.*]], align 2
> +; CHECK-NEXT:[[BROADCAST_SPLATINSERT:%.*]] = insertelement  ptr> poison, ptr [[DST:%.*]], i64 0
> +; CHECK-NEXT:[[BROADCAST_SPLAT:%.*]] = shufflevector  
> [[BROADCAST_SPLATINSERT]],  poison,  
> zeroinitializer
> +; CHECK-NEXT:[[BROADCAST_VALUE:%.*]] = insertelement  
> poison, i16 [[VAL:%.*]], i64 0
> +; CHECK-NEXT:[[BROADCAST_SPLATVALUE:%.*]] = shufflevector  i16> [[BROADCAST_VALUE]],  poison,  
> zeroinitializer
> +; CHECK-NEXT:call void @llvm.masked.scatter.nxv4i16.nxv4p0( i16> [[BROADCAST_SPLATVALUE]],  [[BROADCAST_SPLAT]], i32 2, 
>  shufflevector ( insertelement ( x i1> zeroinitializer, i1 true, i32 0),  zeroinitializer, 
>  zeroinitializer))
>  ; CHECK-NEXT:ret void
>  ;
>  entry:
> ```
> 
> It is a regression. But I think it should be fixed by 
> [fd07b8f](https://github.com/llvm/llvm-project/commit/fd07b8f809eb64af9b29331ff6b94904b3159f84).

I am trying to fix it in the GitHub codespace.

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


[llvm-branch-commits] [llvm] release/18.x: [InstCombine] Fix miscompilation in PR83947 (#83993) (PR #84021)

2024-03-07 Thread Yingwei Zheng via llvm-branch-commits

dtcxzyw wrote:

> remote: Permission to llvmbot/llvm-project.git denied to dtcxzyw.
fatal: unable to access 'https://github.com/llvmbot/llvm-project/': The 
requested URL returned error: 403

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


[llvm-branch-commits] [libc] f3ca656 - Revert "[libc] Remove UB specializations of type traits for `BigInt` (#84035)"

2024-03-07 Thread via llvm-branch-commits

Author: Guillaume Chatelet
Date: 2024-03-07T11:05:26+01:00
New Revision: f3ca6565d507bdcd9db5a363d627f6b69cb6f277

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

LOG: Revert "[libc] Remove UB specializations of type traits for `BigInt` 
(#84035)"

This reverts commit 84f483dbeeba5ecadbf3e4a75bfb71525a3fa332.

Added: 


Modified: 
libc/src/__support/CMakeLists.txt
libc/src/__support/CPP/bit.h
libc/src/__support/UInt.h
libc/src/__support/float_to_string.h
libc/src/__support/integer_to_string.h
libc/test/UnitTest/CMakeLists.txt
libc/test/UnitTest/LibcTest.cpp
libc/test/UnitTest/LibcTest.h
libc/test/UnitTest/TestLogger.cpp
libc/test/src/__support/CPP/bit_test.cpp
utils/bazel/llvm-project-overlay/libc/BUILD.bazel
utils/bazel/llvm-project-overlay/libc/test/UnitTest/BUILD.bazel

Removed: 




diff  --git a/libc/src/__support/CMakeLists.txt 
b/libc/src/__support/CMakeLists.txt
index 17c04aa57e6fd6..1a4b3e9a2145c0 100644
--- a/libc/src/__support/CMakeLists.txt
+++ b/libc/src/__support/CMakeLists.txt
@@ -95,7 +95,6 @@ add_header_library(
   HDRS
 integer_to_string.h
   DEPENDS
-.uint
 libc.src.__support.common
 libc.src.__support.CPP.algorithm
 libc.src.__support.CPP.limits

diff  --git a/libc/src/__support/CPP/bit.h b/libc/src/__support/CPP/bit.h
index bc2f595845a95f..7d11e7d5c497e0 100644
--- a/libc/src/__support/CPP/bit.h
+++ b/libc/src/__support/CPP/bit.h
@@ -27,14 +27,13 @@ namespace LIBC_NAMESPACE::cpp {
 
 // This implementation of bit_cast requires trivially-constructible To, to 
avoid
 // UB in the implementation.
-template 
-LIBC_INLINE constexpr cpp::enable_if_t<
-(sizeof(To) == sizeof(From)) &&
-cpp::is_trivially_constructible::value &&
-cpp::is_trivially_copyable::value &&
-cpp::is_trivially_copyable::value,
-To>
-bit_cast(const From &from) {
+template <
+typename To, typename From,
+typename = cpp::enable_if_t::value &&
+cpp::is_trivially_copyable::value &&
+cpp::is_trivially_copyable::value>>
+LIBC_INLINE constexpr To bit_cast(const From &from) {
   MSAN_UNPOISON(&from, sizeof(From));
 #if LIBC_HAS_BUILTIN(__builtin_bit_cast)
   return __builtin_bit_cast(To, from);
@@ -52,10 +51,8 @@ bit_cast(const From &from) {
 #endif // LIBC_HAS_BUILTIN(__builtin_bit_cast)
 }
 
-template 
-[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t,
- bool>
-has_single_bit(T value) {
+template >>
+[[nodiscard]] LIBC_INLINE constexpr bool has_single_bit(T value) {
   return (value != 0) && ((value & (value - 1)) == 0);
 }
 
@@ -73,9 +70,8 @@ has_single_bit(T value) {
 /// Only unsigned integral types are allowed.
 ///
 /// Returns cpp::numeric_limits::digits on an input of 0.
-template 
-[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t, 
int>
-countr_zero(T value) {
+template >>
+[[nodiscard]] LIBC_INLINE constexpr int countr_zero(T value) {
   if (!value)
 return cpp::numeric_limits::digits;
   if (value & 0x1)
@@ -107,9 +103,8 @@ ADD_SPECIALIZATION(countr_zero, unsigned long long, 
__builtin_ctzll)
 /// Only unsigned integral types are allowed.
 ///
 /// Returns cpp::numeric_limits::digits on an input of 0.
-template 
-[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t, 
int>
-countl_zero(T value) {
+template >>
+[[nodiscard]] LIBC_INLINE constexpr int countl_zero(T value) {
   if (!value)
 return cpp::numeric_limits::digits;
   // Bisection method.
@@ -140,9 +135,8 @@ ADD_SPECIALIZATION(countl_zero, unsigned long long, 
__builtin_clzll)
 /// Only unsigned integral types are allowed.
 ///
 /// Returns cpp::numeric_limits::digits on an input of all ones.
-template 
-[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t, 
int>
-countl_one(T value) {
+template >>
+[[nodiscard]] LIBC_INLINE constexpr int countl_one(T value) {
   return cpp::countl_zero(~value);
 }
 
@@ -153,9 +147,8 @@ countl_one(T value) {
 /// Only unsigned integral types are allowed.
 ///
 /// Returns cpp::numeric_limits::digits on an input of all ones.
-template 
-[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t, 
int>
-countr_one(T value) {
+template >>
+[[nodiscard]] LIBC_INLINE constexpr int countr_one(T value) {
   return cpp::countr_zero(~value);
 }
 
@@ -163,9 +156,8 @@ countr_one(T value) {
 /// Returns 0 otherwise.
 ///
 /// Ex. bit_width(5) == 3.
-template 
-[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t, 
int>
-bit_width(T value) {
+template >>
+[[nodiscard]] LIBC_INLINE constexpr int bit_width(T value) {
   return cpp::numeric_limits::digits - cpp::countl_zero(value);
 }
 
@@ -173,9 +165,8 @@ bit_width(T value) {
 /// nonzero.  Returns 0 otherwise.
 ///
 /// Ex. bit_floor(5)

[llvm-branch-commits] [llvm] Backport PR83993 to 18.x (PR #84298)

2024-03-07 Thread Yingwei Zheng via llvm-branch-commits

https://github.com/dtcxzyw milestoned 
https://github.com/llvm/llvm-project/pull/84298
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] Backport PR83993 to 18.x (PR #84298)

2024-03-07 Thread Yingwei Zheng via llvm-branch-commits

https://github.com/dtcxzyw created 
https://github.com/llvm/llvm-project/pull/84298

Backport #83993 

It is an alternative to #84021.


>From 02e9b82d220961bc7a42295f051564a217144d4a Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Tue, 5 Mar 2024 22:34:04 +0800
Subject: [PATCH] [InstCombine] Fix miscompilation in PR83947 (#83993)

https://github.com/llvm/llvm-project/blob/762f762504967efbe159db5c737154b989afc9bb/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp#L394-L407

Comment from @topperc:
> This transforms assumes the mask is a non-zero splat. We only know its
a splat and not provably all 0s. The mask is a constexpr that includes
the address of the global variable. We can't resolve the constant
expression to an exact value.

Fixes #83947.
---
 llvm/include/llvm/Analysis/VectorUtils.h  |  5 ++
 llvm/lib/Analysis/VectorUtils.cpp | 25 +++
 .../InstCombine/InstCombineCalls.cpp  | 13 ++--
 .../InstCombine/masked_intrinsics.ll  |  6 +-
 llvm/test/Transforms/InstCombine/pr83947.ll   | 67 +++
 5 files changed, 110 insertions(+), 6 deletions(-)
 create mode 100644 llvm/test/Transforms/InstCombine/pr83947.ll

diff --git a/llvm/include/llvm/Analysis/VectorUtils.h 
b/llvm/include/llvm/Analysis/VectorUtils.h
index 7a92e62b53c53d..c6eb66cc9660ca 100644
--- a/llvm/include/llvm/Analysis/VectorUtils.h
+++ b/llvm/include/llvm/Analysis/VectorUtils.h
@@ -406,6 +406,11 @@ bool maskIsAllZeroOrUndef(Value *Mask);
 /// lanes can be assumed active.
 bool maskIsAllOneOrUndef(Value *Mask);
 
+/// Given a mask vector of i1, Return true if any of the elements of this
+/// predicate mask are known to be true or undef.  That is, return true if at
+/// least one lane can be assumed active.
+bool maskContainsAllOneOrUndef(Value *Mask);
+
 /// Given a mask vector of the form , return an APInt (of bitwidth Y)
 /// for each lane which may be active.
 APInt possiblyDemandedEltsInMask(Value *Mask);
diff --git a/llvm/lib/Analysis/VectorUtils.cpp 
b/llvm/lib/Analysis/VectorUtils.cpp
index 73facc76a92b2c..bf7bc0ba84a033 100644
--- a/llvm/lib/Analysis/VectorUtils.cpp
+++ b/llvm/lib/Analysis/VectorUtils.cpp
@@ -1012,6 +1012,31 @@ bool llvm::maskIsAllOneOrUndef(Value *Mask) {
   return true;
 }
 
+bool llvm::maskContainsAllOneOrUndef(Value *Mask) {
+  assert(isa(Mask->getType()) &&
+ isa(Mask->getType()->getScalarType()) &&
+ cast(Mask->getType()->getScalarType())->getBitWidth() ==
+ 1 &&
+ "Mask must be a vector of i1");
+
+  auto *ConstMask = dyn_cast(Mask);
+  if (!ConstMask)
+return false;
+  if (ConstMask->isAllOnesValue() || isa(ConstMask))
+return true;
+  if (isa(ConstMask->getType()))
+return false;
+  for (unsigned
+   I = 0,
+   E = cast(ConstMask->getType())->getNumElements();
+   I != E; ++I) {
+if (auto *MaskElt = ConstMask->getAggregateElement(I))
+  if (MaskElt->isAllOnesValue() || isa(MaskElt))
+return true;
+  }
+  return false;
+}
+
 /// TODO: This is a lot like known bits, but for
 /// vectors.  Is there something we can common this with?
 APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index a647be2d26c761..bc43edb5e62065 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -412,11 +412,14 @@ Instruction 
*InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
   if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) {
 // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
 if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) {
-  Align Alignment = 
cast(II.getArgOperand(2))->getAlignValue();
-  StoreInst *S =
-  new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false, Alignment);
-  S->copyMetadata(II);
-  return S;
+  if (maskContainsAllOneOrUndef(ConstMask)) {
+Align Alignment =
+cast(II.getArgOperand(2))->getAlignValue();
+StoreInst *S = new StoreInst(SplatValue, SplatPtr, 
/*IsVolatile=*/false,
+ Alignment);
+S->copyMetadata(II);
+return S;
+  }
 }
 // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
 // lastlane), ptr
diff --git a/llvm/test/Transforms/InstCombine/masked_intrinsics.ll 
b/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
index 2704905f7a358d..c87c1199f727ea 100644
--- a/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
+++ b/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
@@ -292,7 +292,11 @@ entry:
 define void @scatter_nxv4i16_uniform_vals_uniform_ptrs_all_active_mask(ptr 
%dst, i16 %val) {
 ; CHECK-LABEL: @scatter_nxv4i16_uniform_vals_uniform_ptrs_all_active_mask(
 ; CHECK-NEXT:  entry:
-; CHECK-NEXT:store i16 [[VAL:%.*]], ptr [[DST:%.*]], align 2
+; CHECK-NEXT:

[llvm-branch-commits] [llvm] release/18.x: [InstCombine] Fix miscompilation in PR83947 (#83993) (PR #84021)

2024-03-07 Thread Yingwei Zheng via llvm-branch-commits

https://github.com/dtcxzyw closed 
https://github.com/llvm/llvm-project/pull/84021
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] Backport PR83993 to 18.x (PR #84298)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-analysis

Author: Yingwei Zheng (dtcxzyw)


Changes

Backport #83993 

It is an alternative to #84021.


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


5 Files Affected:

- (modified) llvm/include/llvm/Analysis/VectorUtils.h (+5) 
- (modified) llvm/lib/Analysis/VectorUtils.cpp (+25) 
- (modified) llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp (+8-5) 
- (modified) llvm/test/Transforms/InstCombine/masked_intrinsics.ll (+5-1) 
- (added) llvm/test/Transforms/InstCombine/pr83947.ll (+67) 


``diff
diff --git a/llvm/include/llvm/Analysis/VectorUtils.h 
b/llvm/include/llvm/Analysis/VectorUtils.h
index 7a92e62b53c53d..c6eb66cc9660ca 100644
--- a/llvm/include/llvm/Analysis/VectorUtils.h
+++ b/llvm/include/llvm/Analysis/VectorUtils.h
@@ -406,6 +406,11 @@ bool maskIsAllZeroOrUndef(Value *Mask);
 /// lanes can be assumed active.
 bool maskIsAllOneOrUndef(Value *Mask);
 
+/// Given a mask vector of i1, Return true if any of the elements of this
+/// predicate mask are known to be true or undef.  That is, return true if at
+/// least one lane can be assumed active.
+bool maskContainsAllOneOrUndef(Value *Mask);
+
 /// Given a mask vector of the form , return an APInt (of bitwidth Y)
 /// for each lane which may be active.
 APInt possiblyDemandedEltsInMask(Value *Mask);
diff --git a/llvm/lib/Analysis/VectorUtils.cpp 
b/llvm/lib/Analysis/VectorUtils.cpp
index 73facc76a92b2c..bf7bc0ba84a033 100644
--- a/llvm/lib/Analysis/VectorUtils.cpp
+++ b/llvm/lib/Analysis/VectorUtils.cpp
@@ -1012,6 +1012,31 @@ bool llvm::maskIsAllOneOrUndef(Value *Mask) {
   return true;
 }
 
+bool llvm::maskContainsAllOneOrUndef(Value *Mask) {
+  assert(isa(Mask->getType()) &&
+ isa(Mask->getType()->getScalarType()) &&
+ cast(Mask->getType()->getScalarType())->getBitWidth() ==
+ 1 &&
+ "Mask must be a vector of i1");
+
+  auto *ConstMask = dyn_cast(Mask);
+  if (!ConstMask)
+return false;
+  if (ConstMask->isAllOnesValue() || isa(ConstMask))
+return true;
+  if (isa(ConstMask->getType()))
+return false;
+  for (unsigned
+   I = 0,
+   E = cast(ConstMask->getType())->getNumElements();
+   I != E; ++I) {
+if (auto *MaskElt = ConstMask->getAggregateElement(I))
+  if (MaskElt->isAllOnesValue() || isa(MaskElt))
+return true;
+  }
+  return false;
+}
+
 /// TODO: This is a lot like known bits, but for
 /// vectors.  Is there something we can common this with?
 APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index a647be2d26c761..bc43edb5e62065 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -412,11 +412,14 @@ Instruction 
*InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
   if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) {
 // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
 if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) {
-  Align Alignment = 
cast(II.getArgOperand(2))->getAlignValue();
-  StoreInst *S =
-  new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false, Alignment);
-  S->copyMetadata(II);
-  return S;
+  if (maskContainsAllOneOrUndef(ConstMask)) {
+Align Alignment =
+cast(II.getArgOperand(2))->getAlignValue();
+StoreInst *S = new StoreInst(SplatValue, SplatPtr, 
/*IsVolatile=*/false,
+ Alignment);
+S->copyMetadata(II);
+return S;
+  }
 }
 // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
 // lastlane), ptr
diff --git a/llvm/test/Transforms/InstCombine/masked_intrinsics.ll 
b/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
index 2704905f7a358d..c87c1199f727ea 100644
--- a/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
+++ b/llvm/test/Transforms/InstCombine/masked_intrinsics.ll
@@ -292,7 +292,11 @@ entry:
 define void @scatter_nxv4i16_uniform_vals_uniform_ptrs_all_active_mask(ptr 
%dst, i16 %val) {
 ; CHECK-LABEL: @scatter_nxv4i16_uniform_vals_uniform_ptrs_all_active_mask(
 ; CHECK-NEXT:  entry:
-; CHECK-NEXT:store i16 [[VAL:%.*]], ptr [[DST:%.*]], align 2
+; CHECK-NEXT:[[BROADCAST_SPLATINSERT:%.*]] = insertelement  poison, ptr [[DST:%.*]], i64 0
+; CHECK-NEXT:[[BROADCAST_SPLAT:%.*]] = shufflevector  
[[BROADCAST_SPLATINSERT]],  poison,  
zeroinitializer
+; CHECK-NEXT:[[BROADCAST_VALUE:%.*]] = insertelement  
poison, i16 [[VAL:%.*]], i64 0
+; CHECK-NEXT:[[BROADCAST_SPLATVALUE:%.*]] = shufflevector  [[BROADCAST_VALUE]],  poison,  
zeroinitializer
+; CHECK-NEXT:call void @llvm.masked.scatter.nxv4i16.nxv4p0( [[BROADCAST_SPLATVALUE]],  [[BROADCAST_SPLAT]], i32 2, 
 shufflevector ( insertelement ( zeroinitializer, i1 true, i32 0),  zeroinitializer

[llvm-branch-commits] [flang] 7f10219 - [flang] disable failing test

2024-03-07 Thread Alex Zinenko via llvm-branch-commits

Author: Alex Zinenko
Date: 2024-03-07T10:36:58Z
New Revision: 7f102199b862fce58e4b0d94d10f4cf14acb48e1

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

LOG: [flang] disable failing test

This test has been failing on Windows for multiple consecutive days
without any action taken. This prevents our CI from finding other
problematic tests.

Added: 


Modified: 
flang/test/Fir/memory-allocation-opt.fir

Removed: 




diff  --git a/flang/test/Fir/memory-allocation-opt.fir 
b/flang/test/Fir/memory-allocation-opt.fir
index cfbca2f83ef8ec..c89d794ccaf8d0 100644
--- a/flang/test/Fir/memory-allocation-opt.fir
+++ b/flang/test/Fir/memory-allocation-opt.fir
@@ -1,4 +1,5 @@
 // RUN: fir-opt --memory-allocation-opt="dynamic-array-on-heap=true 
maximum-array-alloc-size=1024" %s | FileCheck %s
+// XFAIL: *
 
 // Test for size of array being too big.
 



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


[llvm-branch-commits] [mlir] 20815bc - [mlir][py] better support for arith.constant construction

2024-03-07 Thread Alex Zinenko via llvm-branch-commits

Author: Alex Zinenko
Date: 2024-03-07T10:38:26Z
New Revision: 20815bc3273ad1d63494ba3f6eda8a9671a94693

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

LOG: [mlir][py] better support for arith.constant construction

Arithmetic constants for vector types can be constructed from objects
implementing Python buffer protocol such as `array.array`. Note that
until Python 3.12, there is no typing support for buffer protocol
implementers, so the annotations use array explicitly.

Added: 


Modified: 
mlir/python/mlir/dialects/arith.py
mlir/test/python/dialects/arith_dialect.py

Removed: 




diff  --git a/mlir/python/mlir/dialects/arith.py 
b/mlir/python/mlir/dialects/arith.py
index 61c6917393f1f9..92da5df9bce665 100644
--- a/mlir/python/mlir/dialects/arith.py
+++ b/mlir/python/mlir/dialects/arith.py
@@ -5,6 +5,8 @@
 from ._arith_ops_gen import *
 from ._arith_ops_gen import _Dialect
 from ._arith_enum_gen import *
+from array import array as _array
+from typing import overload
 
 try:
 from ..ir import *
@@ -43,13 +45,37 @@ def _is_float_type(type: Type):
 class ConstantOp(ConstantOp):
 """Specialization for the constant op class."""
 
+@overload
+def __init__(self, value: Attribute, *, loc=None, ip=None):
+...
+
+@overload
 def __init__(
-self, result: Type, value: Union[int, float, Attribute], *, loc=None, 
ip=None
+self, result: Type, value: Union[int, float, _array], *, loc=None, 
ip=None
 ):
+...
+
+def __init__(self, result, value, *, loc=None, ip=None):
+if value is None:
+assert isinstance(result, Attribute)
+super().__init__(result, loc=loc, ip=ip)
+return
+
 if isinstance(value, int):
 super().__init__(IntegerAttr.get(result, value), loc=loc, ip=ip)
 elif isinstance(value, float):
 super().__init__(FloatAttr.get(result, value), loc=loc, ip=ip)
+elif isinstance(value, _array):
+if 8 * value.itemsize != result.element_type.width:
+raise ValueError(
+f"Mismatching array element ({8 * value.itemsize}) and 
type ({result.element_type.width}) width."
+)
+if value.typecode in ["i", "l", "q"]:
+super().__init__(DenseIntElementsAttr.get(value, type=result))
+elif value.typecode in ["f", "d"]:
+super().__init__(DenseFPElementsAttr.get(value, type=result))
+else:
+raise ValueError(f'Unsupported typecode: "{value.typecode}".')
 else:
 super().__init__(value, loc=loc, ip=ip)
 
@@ -79,6 +105,6 @@ def literal_value(self) -> Union[int, float]:
 
 
 def constant(
-result: Type, value: Union[int, float, Attribute], *, loc=None, ip=None
+result: Type, value: Union[int, float, Attribute, _array], *, loc=None, 
ip=None
 ) -> Value:
 return _get_op_result_or_op_results(ConstantOp(result, value, loc=loc, 
ip=ip))

diff  --git a/mlir/test/python/dialects/arith_dialect.py 
b/mlir/test/python/dialects/arith_dialect.py
index 8bb80eed2b8105..c9af5e7b46db84 100644
--- a/mlir/test/python/dialects/arith_dialect.py
+++ b/mlir/test/python/dialects/arith_dialect.py
@@ -4,6 +4,7 @@
 from mlir.ir import *
 import mlir.dialects.arith as arith
 import mlir.dialects.func as func
+from array import array
 
 
 def run(f):
@@ -92,3 +93,42 @@ def __str__(self):
 b = a * a
 # CHECK: ArithValue(%2 = arith.mulf %cst_1, %cst_1 : f64)
 print(b)
+
+
+# CHECK-LABEL: TEST: testArrayConstantConstruction
+@run
+def testArrayConstantConstruction():
+with Context(), Location.unknown():
+module = Module.create()
+with InsertionPoint(module.body):
+i32_array = array("i", [1, 2, 3, 4])
+i32 = IntegerType.get_signless(32)
+vec_i32 = VectorType.get([2, 2], i32)
+arith.constant(vec_i32, i32_array)
+arith.ConstantOp(vec_i32, DenseIntElementsAttr.get(i32_array, 
type=vec_i32))
+
+# "q" is the equivalent of `long long` in C and requires at least
+# 64 bit width integers on both Linux and Windows.
+i64_array = array("q", [5, 6, 7, 8])
+i64 = IntegerType.get_signless(64)
+vec_i64 = VectorType.get([1, 4], i64)
+arith.constant(vec_i64, i64_array)
+arith.ConstantOp(vec_i64, DenseIntElementsAttr.get(i64_array, 
type=vec_i64))
+
+f32_array = array("f", [1.0, 2.0, 3.0, 4.0])
+f32 = F32Type.get()
+vec_f32 = VectorType.get([4, 1], f32)
+arith.constant(vec_f32, f32_array)
+arith.ConstantOp(vec_f32, DenseFPElementsAttr.get(f32_array, 
type=vec_f32))
+
+   

[llvm-branch-commits] [mlir] b246e0d - [mlir][py] better support for arith.constant construction

2024-03-07 Thread Alex Zinenko via llvm-branch-commits

Author: Alex Zinenko
Date: 2024-03-07T10:44:36Z
New Revision: b246e0d0bea735652274000fb73a7b2e46434612

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

LOG: [mlir][py] better support for arith.constant construction

Arithmetic constants for vector types can be constructed from objects
implementing Python buffer protocol such as `array.array`. Note that
until Python 3.12, there is no typing support for buffer protocol
implementers, so the annotations use array explicitly.

Added: 


Modified: 
mlir/python/mlir/dialects/arith.py
mlir/test/python/dialects/arith_dialect.py

Removed: 




diff  --git a/mlir/python/mlir/dialects/arith.py 
b/mlir/python/mlir/dialects/arith.py
index 61c6917393f1f9..92da5df9bce665 100644
--- a/mlir/python/mlir/dialects/arith.py
+++ b/mlir/python/mlir/dialects/arith.py
@@ -5,6 +5,8 @@
 from ._arith_ops_gen import *
 from ._arith_ops_gen import _Dialect
 from ._arith_enum_gen import *
+from array import array as _array
+from typing import overload
 
 try:
 from ..ir import *
@@ -43,13 +45,37 @@ def _is_float_type(type: Type):
 class ConstantOp(ConstantOp):
 """Specialization for the constant op class."""
 
+@overload
+def __init__(self, value: Attribute, *, loc=None, ip=None):
+...
+
+@overload
 def __init__(
-self, result: Type, value: Union[int, float, Attribute], *, loc=None, 
ip=None
+self, result: Type, value: Union[int, float, _array], *, loc=None, 
ip=None
 ):
+...
+
+def __init__(self, result, value, *, loc=None, ip=None):
+if value is None:
+assert isinstance(result, Attribute)
+super().__init__(result, loc=loc, ip=ip)
+return
+
 if isinstance(value, int):
 super().__init__(IntegerAttr.get(result, value), loc=loc, ip=ip)
 elif isinstance(value, float):
 super().__init__(FloatAttr.get(result, value), loc=loc, ip=ip)
+elif isinstance(value, _array):
+if 8 * value.itemsize != result.element_type.width:
+raise ValueError(
+f"Mismatching array element ({8 * value.itemsize}) and 
type ({result.element_type.width}) width."
+)
+if value.typecode in ["i", "l", "q"]:
+super().__init__(DenseIntElementsAttr.get(value, type=result))
+elif value.typecode in ["f", "d"]:
+super().__init__(DenseFPElementsAttr.get(value, type=result))
+else:
+raise ValueError(f'Unsupported typecode: "{value.typecode}".')
 else:
 super().__init__(value, loc=loc, ip=ip)
 
@@ -79,6 +105,6 @@ def literal_value(self) -> Union[int, float]:
 
 
 def constant(
-result: Type, value: Union[int, float, Attribute], *, loc=None, ip=None
+result: Type, value: Union[int, float, Attribute, _array], *, loc=None, 
ip=None
 ) -> Value:
 return _get_op_result_or_op_results(ConstantOp(result, value, loc=loc, 
ip=ip))

diff  --git a/mlir/test/python/dialects/arith_dialect.py 
b/mlir/test/python/dialects/arith_dialect.py
index 8bb80eed2b8105..c9af5e7b46db84 100644
--- a/mlir/test/python/dialects/arith_dialect.py
+++ b/mlir/test/python/dialects/arith_dialect.py
@@ -4,6 +4,7 @@
 from mlir.ir import *
 import mlir.dialects.arith as arith
 import mlir.dialects.func as func
+from array import array
 
 
 def run(f):
@@ -92,3 +93,42 @@ def __str__(self):
 b = a * a
 # CHECK: ArithValue(%2 = arith.mulf %cst_1, %cst_1 : f64)
 print(b)
+
+
+# CHECK-LABEL: TEST: testArrayConstantConstruction
+@run
+def testArrayConstantConstruction():
+with Context(), Location.unknown():
+module = Module.create()
+with InsertionPoint(module.body):
+i32_array = array("i", [1, 2, 3, 4])
+i32 = IntegerType.get_signless(32)
+vec_i32 = VectorType.get([2, 2], i32)
+arith.constant(vec_i32, i32_array)
+arith.ConstantOp(vec_i32, DenseIntElementsAttr.get(i32_array, 
type=vec_i32))
+
+# "q" is the equivalent of `long long` in C and requires at least
+# 64 bit width integers on both Linux and Windows.
+i64_array = array("q", [5, 6, 7, 8])
+i64 = IntegerType.get_signless(64)
+vec_i64 = VectorType.get([1, 4], i64)
+arith.constant(vec_i64, i64_array)
+arith.ConstantOp(vec_i64, DenseIntElementsAttr.get(i64_array, 
type=vec_i64))
+
+f32_array = array("f", [1.0, 2.0, 3.0, 4.0])
+f32 = F32Type.get()
+vec_f32 = VectorType.get([4, 1], f32)
+arith.constant(vec_f32, f32_array)
+arith.ConstantOp(vec_f32, DenseFPElementsAttr.get(f32_array, 
type=vec_f32))
+
+   

[llvm-branch-commits] [clang] c4eae28 - Revert "[dataflow][nfc] Fix u8 string usage with c++20 (#84291)"

2024-03-07 Thread via llvm-branch-commits

Author: martinboehme
Date: 2024-03-07T11:48:25+01:00
New Revision: c4eae28f1eb14bb8a588d866aa561d676c6bdd67

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

LOG: Revert "[dataflow][nfc] Fix u8 string usage with c++20 (#84291)"

This reverts commit 6e79f77adbbd338848ea770f2f2b110bc57a3990.

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index d9f40d28859f5e..ff4e18de2c70f1 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -500,7 +500,7 @@ class HTMLLogger : public Logger {
 for (unsigned I = 0; I < CFG.getNumBlockIDs(); ++I) {
   std::string Name = blockID(I);
   // Rightwards arrow, vertical line
-  char ConvergenceMarker[] = "\\n\u2192\u007c";
+  char ConvergenceMarker[] = u8"\\n\u2192\u007c";
   if (BlockConverged[I])
 Name += ConvergenceMarker;
   GraphS << "  " << blockID(I) << " [id=" << blockID(I) << " label=\""



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


[llvm-branch-commits] [flang] [llvm] [mlir] [flang][OpenMP][OMPIRBuilder][mlir] Optionally pass reduction vars by ref (PR #84304)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-flang-fir-hlfir

Author: Tom Eccles (tblah)


Changes

Previously reduction variables were always passed by value into and out of the 
initialization and combiner regions of the OpenMP reduction declare operation.

This worked well for reductions of primitive types (and might perform better 
than passing by reference). But passing by reference will be useful for array 
and derived type reductions (e.g. to move allocation inside of the init region).

Passing reductions by reference requires different LLVM-IR generation when 
lowering from MLIR because some of the loads/stores/allocations will now be 
moved inside of the init and combiner regions. This alternate code generation 
is requested using a new attribute to omp.wsloop and omp.parallel.

Existing lowerings from mlir are unaffected (these will continue to use the 
by-value argument passing.

Flang will continue to pass by-value argument passing for trivial types unless 
a (hidden) command line argument is supplied. Non-trivial types will always use 
the by-ref lowering.

Array reductions are not ready yet (but are coming very soon). In the meantime, 
this is tested by forcing existing reductions to use by-ref.

Commit series for by-ref OpenMP reductions 3/3

---

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


37 Files Affected:

- (modified) flang/lib/Lower/OpenMP/OpenMP.cpp (+13-5) 
- (modified) flang/lib/Lower/OpenMP/ReductionProcessor.cpp (+93-27) 
- (modified) flang/lib/Lower/OpenMP/ReductionProcessor.h (+13-5) 
- (added) flang/test/Lower/OpenMP/FIR/parallel-reduction-add-byref.f90 (+117) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-add-byref.f90 (+392) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-iand-byref.f90 (+46) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-ieor-byref.f90 (+45) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-ior-byref.f90 (+45) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-logical-eqv-byref.f90 
(+187) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-logical-neqv-byref.f90 
(+189) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-max-byref.f90 (+90) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-min-byref.f90 (+91) 
- (added) flang/test/Lower/OpenMP/default-clause-byref.f90 (+385) 
- (added) flang/test/Lower/OpenMP/delayed-privatization-reduction-byref.f90 
(+30) 
- (added) flang/test/Lower/OpenMP/parallel-reduction-add-byref.f90 (+125) 
- (added) flang/test/Lower/OpenMP/parallel-reduction-byref.f90 (+44) 
- (added) flang/test/Lower/OpenMP/parallel-wsloop-reduction-byref.f90 (+16) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-add-byref.f90 (+433) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-add-hlfir-byref.f90 (+58) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-iand-byref.f90 (+64) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-ieor-byref.f90 (+55) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-ior-byref.f90 (+64) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-logical-and-byref.f90 (+206) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-logical-eqv-byref.f90 (+202) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-logical-neqv-byref.f90 
(+207) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-logical-or-byref.f90 (+204) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-max-2-byref.f90 (+20) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-max-byref.f90 (+152) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-max-hlfir-byref.f90 (+62) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-min-byref.f90 (+154) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-mul-byref.f90 (+414) 
- (modified) llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h (+3-1) 
- (modified) llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp (+22-8) 
- (modified) mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td (+11-1) 
- (modified) mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp (+3-2) 
- (modified) 
mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp (+72-27) 
- (added) mlir/test/Target/LLVMIR/openmp-reduction-byref.mlir (+66) 


``diff
diff --git a/flang/lib/Lower/OpenMP/OpenMP.cpp 
b/flang/lib/Lower/OpenMP/OpenMP.cpp
index 185e0316870e94..d9648f3d692cc6 100644
--- a/flang/lib/Lower/OpenMP/OpenMP.cpp
+++ b/flang/lib/Lower/OpenMP/OpenMP.cpp
@@ -600,6 +600,10 @@ genParallelOp(Fortran::lower::AbstractConverter &converter,
 return reductionSymbols;
   };
 
+  mlir::UnitAttr byrefAttr;
+  if (ReductionProcessor::doReductionByRef(reductionVars))
+byrefAttr = converter.getFirOpBuilder().getUnitAttr();
+
   OpWithBodyGenInfo genInfo =
   OpWithBodyGenInfo(converter, semaCtx, currentLocation, eval)
   .setGenNested(genNested)
@@ -619,7 +623,7 @@ genParallelOp(Fortran::lower::AbstractConverter &converter,
 : mlir::ArrayAttr::get(converter.getFirOpBuilder().getContext(),
  

[llvm-branch-commits] [flang] [llvm] [mlir] [flang][OpenMP][OMPIRBuilder][mlir] Optionally pass reduction vars by ref (PR #84304)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-mlir

Author: Tom Eccles (tblah)


Changes

Previously reduction variables were always passed by value into and out of the 
initialization and combiner regions of the OpenMP reduction declare operation.

This worked well for reductions of primitive types (and might perform better 
than passing by reference). But passing by reference will be useful for array 
and derived type reductions (e.g. to move allocation inside of the init region).

Passing reductions by reference requires different LLVM-IR generation when 
lowering from MLIR because some of the loads/stores/allocations will now be 
moved inside of the init and combiner regions. This alternate code generation 
is requested using a new attribute to omp.wsloop and omp.parallel.

Existing lowerings from mlir are unaffected (these will continue to use the 
by-value argument passing.

Flang will continue to pass by-value argument passing for trivial types unless 
a (hidden) command line argument is supplied. Non-trivial types will always use 
the by-ref lowering.

Array reductions are not ready yet (but are coming very soon). In the meantime, 
this is tested by forcing existing reductions to use by-ref.

Commit series for by-ref OpenMP reductions 3/3

---

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


37 Files Affected:

- (modified) flang/lib/Lower/OpenMP/OpenMP.cpp (+13-5) 
- (modified) flang/lib/Lower/OpenMP/ReductionProcessor.cpp (+93-27) 
- (modified) flang/lib/Lower/OpenMP/ReductionProcessor.h (+13-5) 
- (added) flang/test/Lower/OpenMP/FIR/parallel-reduction-add-byref.f90 (+117) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-add-byref.f90 (+392) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-iand-byref.f90 (+46) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-ieor-byref.f90 (+45) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-ior-byref.f90 (+45) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-logical-eqv-byref.f90 
(+187) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-logical-neqv-byref.f90 
(+189) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-max-byref.f90 (+90) 
- (added) flang/test/Lower/OpenMP/FIR/wsloop-reduction-min-byref.f90 (+91) 
- (added) flang/test/Lower/OpenMP/default-clause-byref.f90 (+385) 
- (added) flang/test/Lower/OpenMP/delayed-privatization-reduction-byref.f90 
(+30) 
- (added) flang/test/Lower/OpenMP/parallel-reduction-add-byref.f90 (+125) 
- (added) flang/test/Lower/OpenMP/parallel-reduction-byref.f90 (+44) 
- (added) flang/test/Lower/OpenMP/parallel-wsloop-reduction-byref.f90 (+16) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-add-byref.f90 (+433) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-add-hlfir-byref.f90 (+58) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-iand-byref.f90 (+64) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-ieor-byref.f90 (+55) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-ior-byref.f90 (+64) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-logical-and-byref.f90 (+206) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-logical-eqv-byref.f90 (+202) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-logical-neqv-byref.f90 
(+207) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-logical-or-byref.f90 (+204) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-max-2-byref.f90 (+20) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-max-byref.f90 (+152) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-max-hlfir-byref.f90 (+62) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-min-byref.f90 (+154) 
- (added) flang/test/Lower/OpenMP/wsloop-reduction-mul-byref.f90 (+414) 
- (modified) llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h (+3-1) 
- (modified) llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp (+22-8) 
- (modified) mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td (+11-1) 
- (modified) mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp (+3-2) 
- (modified) 
mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp (+72-27) 
- (added) mlir/test/Target/LLVMIR/openmp-reduction-byref.mlir (+66) 


``diff
diff --git a/flang/lib/Lower/OpenMP/OpenMP.cpp 
b/flang/lib/Lower/OpenMP/OpenMP.cpp
index 185e0316870e94..d9648f3d692cc6 100644
--- a/flang/lib/Lower/OpenMP/OpenMP.cpp
+++ b/flang/lib/Lower/OpenMP/OpenMP.cpp
@@ -600,6 +600,10 @@ genParallelOp(Fortran::lower::AbstractConverter &converter,
 return reductionSymbols;
   };
 
+  mlir::UnitAttr byrefAttr;
+  if (ReductionProcessor::doReductionByRef(reductionVars))
+byrefAttr = converter.getFirOpBuilder().getUnitAttr();
+
   OpWithBodyGenInfo genInfo =
   OpWithBodyGenInfo(converter, semaCtx, currentLocation, eval)
   .setGenNested(genNested)
@@ -619,7 +623,7 @@ genParallelOp(Fortran::lower::AbstractConverter &converter,
 : mlir::ArrayAttr::get(converter.getFirOpBuilder().getContext(),
 

[llvm-branch-commits] [flang] [llvm] [mlir] [flang][OpenMP][OMPIRBuilder][mlir] Optionally pass reduction vars by ref (PR #84304)

2024-03-07 Thread Tom Eccles via llvm-branch-commits

tblah wrote:

co-authored with @Leporacanthicus  (github seems to have taken the tag out of 
the commit message but shows it in the UI)

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


[llvm-branch-commits] [flang] [flang][TBAABuilder] not all loads and stores are inside of functions (PR #84305)

2024-03-07 Thread Tom Eccles via llvm-branch-commits

https://github.com/tblah created https://github.com/llvm/llvm-project/pull/84305

TBAA builder assumed that all loads/stores are inside of functions and hit an 
assertion once it found loads and stores inside of an omp::ReductionDeclareOp.

For now just don't add TBAA tags to those loads and stores. They would end up 
in a different TBAA tree to the host function after OpenMPIRBuilder inlines 
them anyway so there isn't an easy way of making this work.

Commit series for by-ref OpenMP reductions: 2/3

>From ba0182b73b1c6f8b91efa8d74b185b3bfc0f1cb6 Mon Sep 17 00:00:00 2001
From: Tom Eccles 
Date: Thu, 15 Feb 2024 13:29:00 +
Subject: [PATCH] [flang][TBAABuilder] not all loads and stores are inside of
 functions

TBAA builder assumed that all loads/stores are inside of functions and
hit an assertion once it found loads and stores inside of an
omp::ReductionDeclareOp.

For now just don't add TBAA tags to those loads and stores. They would
end up in a different TBAA tree to the host function after
OpenMPIRBuilder inlines them anyway so there isn't an easy way of making
this work.

Commit series for by-ref OpenMP reductions: 2/3
---
 flang/lib/Optimizer/CodeGen/TBAABuilder.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/flang/lib/Optimizer/CodeGen/TBAABuilder.cpp 
b/flang/lib/Optimizer/CodeGen/TBAABuilder.cpp
index 8e7f59f76383c9..b1b0e9b766a625 100644
--- a/flang/lib/Optimizer/CodeGen/TBAABuilder.cpp
+++ b/flang/lib/Optimizer/CodeGen/TBAABuilder.cpp
@@ -102,7 +102,8 @@ void TBAABuilder::attachTBAATag(AliasAnalysisOpInterface 
op, Type baseFIRType,
 return;
 
   mlir::LLVM::LLVMFuncOp func = op->getParentOfType();
-  assert(func && "func.func should have already been converted to llvm.func");
+  if (!func)
+return;
 
   ++tagAttachmentCounter;
   if (tagAttachmentLimit != kTagAttachmentUnlimited &&

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


[llvm-branch-commits] [flang] [flang][TBAABuilder] not all loads and stores are inside of functions (PR #84305)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-flang-fir-hlfir

Author: Tom Eccles (tblah)


Changes

TBAA builder assumed that all loads/stores are inside of functions and hit an 
assertion once it found loads and stores inside of an omp::ReductionDeclareOp.

For now just don't add TBAA tags to those loads and stores. They would end up 
in a different TBAA tree to the host function after OpenMPIRBuilder inlines 
them anyway so there isn't an easy way of making this work.

Commit series for by-ref OpenMP reductions: 2/3

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


1 Files Affected:

- (modified) flang/lib/Optimizer/CodeGen/TBAABuilder.cpp (+2-1) 


``diff
diff --git a/flang/lib/Optimizer/CodeGen/TBAABuilder.cpp 
b/flang/lib/Optimizer/CodeGen/TBAABuilder.cpp
index 8e7f59f76383c9..b1b0e9b766a625 100644
--- a/flang/lib/Optimizer/CodeGen/TBAABuilder.cpp
+++ b/flang/lib/Optimizer/CodeGen/TBAABuilder.cpp
@@ -102,7 +102,8 @@ void TBAABuilder::attachTBAATag(AliasAnalysisOpInterface 
op, Type baseFIRType,
 return;
 
   mlir::LLVM::LLVMFuncOp func = op->getParentOfType();
-  assert(func && "func.func should have already been converted to llvm.func");
+  if (!func)
+return;
 
   ++tagAttachmentCounter;
   if (tagAttachmentLimit != kTagAttachmentUnlimited &&

``




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


[llvm-branch-commits] [flang] [flang][TBAABuilder] not all loads and stores are inside of functions (PR #84305)

2024-03-07 Thread Tom Eccles via llvm-branch-commits

tblah wrote:

Next PR in the series https://github.com/llvm/llvm-project/pull/84304

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


[llvm-branch-commits] [clang] release/18.x: [clang][fat-lto-objects] Make module flags match non-FatLTO pipelines (#83159) (PR #84290)

2024-03-07 Thread Teresa Johnson via llvm-branch-commits

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


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


[llvm-branch-commits] [mlir] d39cb79 - [mlir][py] better support for arith.constant construction

2024-03-07 Thread Alex Zinenko via llvm-branch-commits

Author: Alex Zinenko
Date: 2024-03-07T15:02:35Z
New Revision: d39cb79cddadbb6dc6914a8c9f0a54e0f8ce1329

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

LOG: [mlir][py] better support for arith.constant construction

Arithmetic constants for vector types can be constructed from objects
implementing Python buffer protocol such as `array.array`. Note that
until Python 3.12, there is no typing support for buffer protocol
implementers, so the annotations use array explicitly.

Added: 


Modified: 
mlir/python/mlir/dialects/arith.py
mlir/test/python/dialects/arith_dialect.py

Removed: 




diff  --git a/mlir/python/mlir/dialects/arith.py 
b/mlir/python/mlir/dialects/arith.py
index 61c6917393f1f9..92da5df9bce665 100644
--- a/mlir/python/mlir/dialects/arith.py
+++ b/mlir/python/mlir/dialects/arith.py
@@ -5,6 +5,8 @@
 from ._arith_ops_gen import *
 from ._arith_ops_gen import _Dialect
 from ._arith_enum_gen import *
+from array import array as _array
+from typing import overload
 
 try:
 from ..ir import *
@@ -43,13 +45,37 @@ def _is_float_type(type: Type):
 class ConstantOp(ConstantOp):
 """Specialization for the constant op class."""
 
+@overload
+def __init__(self, value: Attribute, *, loc=None, ip=None):
+...
+
+@overload
 def __init__(
-self, result: Type, value: Union[int, float, Attribute], *, loc=None, 
ip=None
+self, result: Type, value: Union[int, float, _array], *, loc=None, 
ip=None
 ):
+...
+
+def __init__(self, result, value, *, loc=None, ip=None):
+if value is None:
+assert isinstance(result, Attribute)
+super().__init__(result, loc=loc, ip=ip)
+return
+
 if isinstance(value, int):
 super().__init__(IntegerAttr.get(result, value), loc=loc, ip=ip)
 elif isinstance(value, float):
 super().__init__(FloatAttr.get(result, value), loc=loc, ip=ip)
+elif isinstance(value, _array):
+if 8 * value.itemsize != result.element_type.width:
+raise ValueError(
+f"Mismatching array element ({8 * value.itemsize}) and 
type ({result.element_type.width}) width."
+)
+if value.typecode in ["i", "l", "q"]:
+super().__init__(DenseIntElementsAttr.get(value, type=result))
+elif value.typecode in ["f", "d"]:
+super().__init__(DenseFPElementsAttr.get(value, type=result))
+else:
+raise ValueError(f'Unsupported typecode: "{value.typecode}".')
 else:
 super().__init__(value, loc=loc, ip=ip)
 
@@ -79,6 +105,6 @@ def literal_value(self) -> Union[int, float]:
 
 
 def constant(
-result: Type, value: Union[int, float, Attribute], *, loc=None, ip=None
+result: Type, value: Union[int, float, Attribute, _array], *, loc=None, 
ip=None
 ) -> Value:
 return _get_op_result_or_op_results(ConstantOp(result, value, loc=loc, 
ip=ip))

diff  --git a/mlir/test/python/dialects/arith_dialect.py 
b/mlir/test/python/dialects/arith_dialect.py
index 8bb80eed2b8105..c9af5e7b46db84 100644
--- a/mlir/test/python/dialects/arith_dialect.py
+++ b/mlir/test/python/dialects/arith_dialect.py
@@ -4,6 +4,7 @@
 from mlir.ir import *
 import mlir.dialects.arith as arith
 import mlir.dialects.func as func
+from array import array
 
 
 def run(f):
@@ -92,3 +93,42 @@ def __str__(self):
 b = a * a
 # CHECK: ArithValue(%2 = arith.mulf %cst_1, %cst_1 : f64)
 print(b)
+
+
+# CHECK-LABEL: TEST: testArrayConstantConstruction
+@run
+def testArrayConstantConstruction():
+with Context(), Location.unknown():
+module = Module.create()
+with InsertionPoint(module.body):
+i32_array = array("i", [1, 2, 3, 4])
+i32 = IntegerType.get_signless(32)
+vec_i32 = VectorType.get([2, 2], i32)
+arith.constant(vec_i32, i32_array)
+arith.ConstantOp(vec_i32, DenseIntElementsAttr.get(i32_array, 
type=vec_i32))
+
+# "q" is the equivalent of `long long` in C and requires at least
+# 64 bit width integers on both Linux and Windows.
+i64_array = array("q", [5, 6, 7, 8])
+i64 = IntegerType.get_signless(64)
+vec_i64 = VectorType.get([1, 4], i64)
+arith.constant(vec_i64, i64_array)
+arith.ConstantOp(vec_i64, DenseIntElementsAttr.get(i64_array, 
type=vec_i64))
+
+f32_array = array("f", [1.0, 2.0, 3.0, 4.0])
+f32 = F32Type.get()
+vec_f32 = VectorType.get([4, 1], f32)
+arith.constant(vec_f32, f32_array)
+arith.ConstantOp(vec_f32, DenseFPElementsAttr.get(f32_array, 
type=vec_f32))
+
+   

[llvm-branch-commits] [flang] [flang][TBAABuilder] not all loads and stores are inside of functions (PR #84305)

2024-03-07 Thread Slava Zakharin via llvm-branch-commits

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

LGTM

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


[llvm-branch-commits] [llvm] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits (PR #84118)

2024-03-07 Thread via llvm-branch-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/84118

>From 05ec7ace33927a07cff7613399bc927b6640578d Mon Sep 17 00:00:00 2001
From: Rose 
Date: Tue, 5 Mar 2024 17:35:23 -0500
Subject: [PATCH] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits

This only converts the instances where all that is needed is to change the 
variable type name.

Basically, anything that involves a function that LiveRegUnits does not 
directly have was skipped to play it safe. This is a subset of what was 
approved for main.

Revert "release/18.x: Convert many LivePhysRegs uses to LiveRegUnits"

This reverts commit e4a52e80aecfc3c0b79cac0a852e07ef0335c949.

Reapply "Convert many LivePhysRegs uses to LiveRegUnits"

This only converts the instances where all that is needed is to change the 
variable type name.

Basically, anything that involves a function that LiveRegUnits does not 
directly have was skipped to play it safe.

Reverts 
https://github.com/llvm/llvm-project/commit/7a0e222a17058a311b69153d0b6f1b4459414778
---
 llvm/lib/CodeGen/ReachingDefAnalysis.cpp  | 27 ++-
 .../Target/AMDGPU/SIOptimizeExecMasking.cpp   |  8 +++---
 llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp |  6 ++---
 llvm/lib/Target/ARM/Thumb1FrameLowering.cpp   |  6 ++---
 llvm/test/CodeGen/Thumb/PR35481.ll| 14 +-
 5 files changed, 31 insertions(+), 30 deletions(-)

diff --git a/llvm/lib/CodeGen/ReachingDefAnalysis.cpp 
b/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
index 61a668907be77d..9f9103f6244799 100644
--- a/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
+++ b/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
@@ -6,10 +6,10 @@
 //
 
//===--===//
 
-#include "llvm/ADT/SmallSet.h"
-#include "llvm/ADT/SetOperations.h"
-#include "llvm/CodeGen/LivePhysRegs.h"
 #include "llvm/CodeGen/ReachingDefAnalysis.h"
+#include "llvm/ADT/SetOperations.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/CodeGen/LiveRegUnits.h"
 #include "llvm/CodeGen/TargetRegisterInfo.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/Support/Debug.h"
@@ -421,9 +421,9 @@ void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock 
*MBB,
 return;
 
   VisitedBBs.insert(MBB);
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return;
 
   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
@@ -469,11 +469,11 @@ MachineInstr 
*ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
 bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
  MCRegister PhysReg) const {
   MachineBasicBlock *MBB = MI->getParent();
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
 
   // Yes if the register is live out of the basic block.
-  if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (!LiveRegs.available(PhysReg))
 return true;
 
   // Walk backwards through the block to see if the register is live at some
@@ -481,7 +481,7 @@ bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
   for (MachineInstr &Last :
instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
 LiveRegs.stepBackward(Last);
-if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+if (!LiveRegs.available(PhysReg))
   return InstIds.lookup(&Last) > InstIds.lookup(MI);
   }
   return false;
@@ -504,9 +504,9 @@ bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr 
*MI,
 bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI,
MCRegister PhysReg) const {
   MachineBasicBlock *MBB = MI->getParent();
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return false;
 
   auto Last = MBB->getLastNonDebugInstr();
@@ -525,9 +525,9 @@ bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr 
*MI,
 MachineInstr *
 ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
   MCRegister PhysReg) const {
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return nullptr;
 
   auto Last = MBB->getLastNonDebugInstr();
@@ -685,6 +685,9 @@ bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI,
 
 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI, MCRegister 
PhysReg,
InstSet &Ignore) const {
+  if (MI->getParent()->getParent()->getRegInfo().isReserved(PhysReg))
+return false;
+
   // Check for any uses of the register after MI.
  

[llvm-branch-commits] [llvm] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits (PR #84118)

2024-03-07 Thread via llvm-branch-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/84118

>From 8c818b75ee02b4e9759b2e6c9aadac9b3fd356d6 Mon Sep 17 00:00:00 2001
From: Rose 
Date: Tue, 5 Mar 2024 17:35:23 -0500
Subject: [PATCH] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits

This only converts the instances where all that is needed is to change the 
variable type name.

Basically, anything that involves a function that LiveRegUnits does not 
directly have was skipped to play it safe. This is a subset of what was 
approved for main.
---
 llvm/lib/CodeGen/ReachingDefAnalysis.cpp  | 28 +++
 .../Target/AMDGPU/SIOptimizeExecMasking.cpp   |  8 +++---
 llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp |  6 ++--
 llvm/lib/Target/ARM/Thumb1FrameLowering.cpp   |  6 ++--
 llvm/test/CodeGen/Thumb/PR35481.ll| 14 --
 5 files changed, 32 insertions(+), 30 deletions(-)

diff --git a/llvm/lib/CodeGen/ReachingDefAnalysis.cpp 
b/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
index 61a668907be77d..c7547ef61b6afb 100644
--- a/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
+++ b/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
@@ -6,10 +6,10 @@
 //
 
//===--===//
 
-#include "llvm/ADT/SmallSet.h"
-#include "llvm/ADT/SetOperations.h"
-#include "llvm/CodeGen/LivePhysRegs.h"
 #include "llvm/CodeGen/ReachingDefAnalysis.h"
+#include "llvm/ADT/SetOperations.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/CodeGen/LiveRegUnits.h"
 #include "llvm/CodeGen/TargetRegisterInfo.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/Support/Debug.h"
@@ -421,9 +421,9 @@ void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock 
*MBB,
 return;
 
   VisitedBBs.insert(MBB);
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return;
 
   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
@@ -469,11 +469,11 @@ MachineInstr 
*ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
 bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
  MCRegister PhysReg) const {
   MachineBasicBlock *MBB = MI->getParent();
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
 
   // Yes if the register is live out of the basic block.
-  if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (!LiveRegs.available(PhysReg))
 return true;
 
   // Walk backwards through the block to see if the register is live at some
@@ -481,7 +481,7 @@ bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
   for (MachineInstr &Last :
instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
 LiveRegs.stepBackward(Last);
-if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+if (!LiveRegs.available(PhysReg))
   return InstIds.lookup(&Last) > InstIds.lookup(MI);
   }
   return false;
@@ -504,9 +504,9 @@ bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr 
*MI,
 bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI,
MCRegister PhysReg) const {
   MachineBasicBlock *MBB = MI->getParent();
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return false;
 
   auto Last = MBB->getLastNonDebugInstr();
@@ -525,9 +525,9 @@ bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr 
*MI,
 MachineInstr *
 ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
   MCRegister PhysReg) const {
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return nullptr;
 
   auto Last = MBB->getLastNonDebugInstr();
@@ -685,6 +685,10 @@ bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr 
*MI,
 
 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI, MCRegister 
PhysReg,
InstSet &Ignore) const {
+  MachineBasicBlock *MBB = MI->getParent();
+  if (MBB->getParent()->getRegInfo().isReserved(PhysReg))
+return false;
+
   // Check for any uses of the register after MI.
   if (isRegUsedAfter(MI, PhysReg)) {
 if (auto *Def = getReachingLocalMIDef(MI, PhysReg)) {
diff --git a/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp 
b/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp
index e3f54d01eb22a2..f6d904e752bf44 100644
--- a/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp
+++ b/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp
@@ -11,7 +11,7 @@
 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
 #include "SIRegisterInfo.h"
 #include "l

[llvm-branch-commits] [llvm] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits (PR #84118)

2024-03-07 Thread via llvm-branch-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/84118

>From 37cf3fd905abce4fa5f69fd3d92303af38bcd299 Mon Sep 17 00:00:00 2001
From: Rose 
Date: Tue, 5 Mar 2024 17:35:23 -0500
Subject: [PATCH] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits

This only converts the instances where all that is needed is to change the 
variable type name.

Basically, anything that involves a function that LiveRegUnits does not 
directly have was skipped to play it safe. This is a subset of what was 
approved for main.
---
 llvm/lib/CodeGen/ReachingDefAnalysis.cpp  | 24 +--
 .../Target/AMDGPU/SIOptimizeExecMasking.cpp   |  8 +++
 llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp |  6 ++---
 llvm/lib/Target/ARM/Thumb1FrameLowering.cpp   |  6 ++---
 llvm/test/CodeGen/Thumb/PR35481.ll| 14 +--
 5 files changed, 28 insertions(+), 30 deletions(-)

diff --git a/llvm/lib/CodeGen/ReachingDefAnalysis.cpp 
b/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
index 61a668907be77d..07fa92889d8853 100644
--- a/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
+++ b/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
@@ -6,10 +6,10 @@
 //
 
//===--===//
 
-#include "llvm/ADT/SmallSet.h"
-#include "llvm/ADT/SetOperations.h"
-#include "llvm/CodeGen/LivePhysRegs.h"
 #include "llvm/CodeGen/ReachingDefAnalysis.h"
+#include "llvm/ADT/SetOperations.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/CodeGen/LiveRegUnits.h"
 #include "llvm/CodeGen/TargetRegisterInfo.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/Support/Debug.h"
@@ -421,9 +421,9 @@ void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock 
*MBB,
 return;
 
   VisitedBBs.insert(MBB);
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return;
 
   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
@@ -469,11 +469,11 @@ MachineInstr 
*ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
 bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
  MCRegister PhysReg) const {
   MachineBasicBlock *MBB = MI->getParent();
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
 
   // Yes if the register is live out of the basic block.
-  if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (!LiveRegs.available(PhysReg))
 return true;
 
   // Walk backwards through the block to see if the register is live at some
@@ -481,7 +481,7 @@ bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
   for (MachineInstr &Last :
instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
 LiveRegs.stepBackward(Last);
-if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+if (!LiveRegs.available(PhysReg))
   return InstIds.lookup(&Last) > InstIds.lookup(MI);
   }
   return false;
@@ -504,9 +504,9 @@ bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr 
*MI,
 bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI,
MCRegister PhysReg) const {
   MachineBasicBlock *MBB = MI->getParent();
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return false;
 
   auto Last = MBB->getLastNonDebugInstr();
@@ -525,9 +525,9 @@ bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr 
*MI,
 MachineInstr *
 ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
   MCRegister PhysReg) const {
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return nullptr;
 
   auto Last = MBB->getLastNonDebugInstr();
diff --git a/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp 
b/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp
index e3f54d01eb22a2..f6d904e752bf44 100644
--- a/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp
+++ b/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp
@@ -11,7 +11,7 @@
 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
 #include "SIRegisterInfo.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/CodeGen/LivePhysRegs.h"
+#include "llvm/CodeGen/LiveRegUnits.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineOperand.h"
 #include "llvm/CodeGen/TargetRegisterInfo.h"
@@ -313,7 +313,7 @@ MachineBasicBlock::reverse_iterator 
SIOptimizeExecMasking::findExecCopy(
   return E;
 }
 
-// XXX - Seems LivePhysRegs doesn't work correctly since it will incorrectly
+// XXX - Seems LiveRegUnits doesn't work correctly since it will incorrectly

[llvm-branch-commits] [llvm] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits (PR #84118)

2024-03-07 Thread via llvm-branch-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/84118

>From 9adec28584b421aa4dad3a4af8e2d077ac76301c Mon Sep 17 00:00:00 2001
From: Rose 
Date: Tue, 5 Mar 2024 17:35:23 -0500
Subject: [PATCH] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits

This only converts the instances where all that is needed is to change the 
variable type name.

Basically, anything that involves a function that LiveRegUnits does not 
directly have was skipped to play it safe. This is a subset of what was 
approved for main.
---
 llvm/lib/CodeGen/ReachingDefAnalysis.cpp  | 24 +--
 .../Target/AMDGPU/SIOptimizeExecMasking.cpp   |  8 +++
 llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp |  6 ++---
 llvm/lib/Target/ARM/Thumb1FrameLowering.cpp   |  6 ++---
 llvm/test/CodeGen/Thumb/PR35481.ll| 14 +--
 5 files changed, 28 insertions(+), 30 deletions(-)

diff --git a/llvm/lib/CodeGen/ReachingDefAnalysis.cpp 
b/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
index 61a668907be77d..07fa92889d8853 100644
--- a/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
+++ b/llvm/lib/CodeGen/ReachingDefAnalysis.cpp
@@ -6,10 +6,10 @@
 //
 
//===--===//
 
-#include "llvm/ADT/SmallSet.h"
-#include "llvm/ADT/SetOperations.h"
-#include "llvm/CodeGen/LivePhysRegs.h"
 #include "llvm/CodeGen/ReachingDefAnalysis.h"
+#include "llvm/ADT/SetOperations.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/CodeGen/LiveRegUnits.h"
 #include "llvm/CodeGen/TargetRegisterInfo.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/Support/Debug.h"
@@ -421,9 +421,9 @@ void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock 
*MBB,
 return;
 
   VisitedBBs.insert(MBB);
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return;
 
   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
@@ -469,11 +469,11 @@ MachineInstr 
*ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
 bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
  MCRegister PhysReg) const {
   MachineBasicBlock *MBB = MI->getParent();
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
 
   // Yes if the register is live out of the basic block.
-  if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (!LiveRegs.available(PhysReg))
 return true;
 
   // Walk backwards through the block to see if the register is live at some
@@ -481,7 +481,7 @@ bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
   for (MachineInstr &Last :
instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
 LiveRegs.stepBackward(Last);
-if (!LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+if (!LiveRegs.available(PhysReg))
   return InstIds.lookup(&Last) > InstIds.lookup(MI);
   }
   return false;
@@ -504,9 +504,9 @@ bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr 
*MI,
 bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI,
MCRegister PhysReg) const {
   MachineBasicBlock *MBB = MI->getParent();
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return false;
 
   auto Last = MBB->getLastNonDebugInstr();
@@ -525,9 +525,9 @@ bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr 
*MI,
 MachineInstr *
 ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
   MCRegister PhysReg) const {
-  LivePhysRegs LiveRegs(*TRI);
+  LiveRegUnits LiveRegs(*TRI);
   LiveRegs.addLiveOuts(*MBB);
-  if (LiveRegs.available(MBB->getParent()->getRegInfo(), PhysReg))
+  if (LiveRegs.available(PhysReg))
 return nullptr;
 
   auto Last = MBB->getLastNonDebugInstr();
diff --git a/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp 
b/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp
index e3f54d01eb22a2..3c60459e54e8fa 100644
--- a/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp
+++ b/llvm/lib/Target/AMDGPU/SIOptimizeExecMasking.cpp
@@ -11,7 +11,7 @@
 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
 #include "SIRegisterInfo.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/CodeGen/LivePhysRegs.h"
+#include "llvm/CodeGen/LiveRegUnits.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineOperand.h"
 #include "llvm/CodeGen/TargetRegisterInfo.h"
@@ -313,7 +313,7 @@ MachineBasicBlock::reverse_iterator 
SIOptimizeExecMasking::findExecCopy(
   return E;
 }
 
-// XXX - Seems LivePhysRegs doesn't work correctly since it will incorrectly
+// XXX - Seems LiveRegUnits doesn't work correctly since it will incorrectly

[llvm-branch-commits] [llvm] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits (PR #84118)

2024-03-07 Thread Jay Foad via llvm-branch-commits

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

> this isn't fixing any known correctness issue

Exactly. I don't think there is any reason to backport this.

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


[llvm-branch-commits] [llvm] release/18.x: Convert many LivePhysRegs uses to LiveRegUnits (PR #84118)

2024-03-07 Thread via llvm-branch-commits

https://github.com/AtariDreams closed 
https://github.com/llvm/llvm-project/pull/84118
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [libcxx] release/18.x: [libc++] Enable availability based on the compiler instead of __has_extension (#84065) (PR #84374)

2024-03-07 Thread via llvm-branch-commits

https://github.com/llvmbot created 
https://github.com/llvm/llvm-project/pull/84374

Backport 292a28df6c55679fad0589dea35278a8c66b2ae1

Requested by: @ldionne

>From 68fc36a1e40b498c6103cbec0f5614bfce0fa3e7 Mon Sep 17 00:00:00 2001
From: Louis Dionne 
Date: Thu, 7 Mar 2024 15:12:21 -0500
Subject: [PATCH] [libc++] Enable availability based on the compiler instead of
 __has_extension (#84065)

__has_extension(...) doesn't work as intended when -pedantic-errors is
used with Clang. With that flag, __has_extension(...) is equivalent to
__has_feature(...), which means that checks like

__has_extension(pragma_clang_attribute_external_declaration)

will return 0. In turn, this has the effect of disabling availability
markup in libc++, which is undesirable.

rdar://124078119
(cherry picked from commit 292a28df6c55679fad0589dea35278a8c66b2ae1)
---
 libcxx/include/__availability |  7 +++---
 ...lity-with-pedantic-errors.compile.pass.cpp | 22 +++
 2 files changed, 25 insertions(+), 4 deletions(-)
 create mode 100644 
libcxx/test/libcxx/vendor/apple/availability-with-pedantic-errors.compile.pass.cpp

diff --git a/libcxx/include/__availability b/libcxx/include/__availability
index c5069a027750ec..b8b2da9bb12265 100644
--- a/libcxx/include/__availability
+++ b/libcxx/include/__availability
@@ -72,11 +72,10 @@
 #  endif
 #endif
 
-// Availability markup is disabled when building the library, or when the 
compiler
+// Availability markup is disabled when building the library, or when a 
non-Clang
+// compiler is used because only Clang supports the necessary attributes.
 // doesn't support the proper attributes.
-#if defined(_LIBCPP_BUILDING_LIBRARY) || defined(_LIBCXXABI_BUILDING_LIBRARY) 
||   \
-!__has_feature(attribute_availability_with_strict) || 
!__has_feature(attribute_availability_in_templates) ||   \
-!__has_extension(pragma_clang_attribute_external_declaration)
+#if defined(_LIBCPP_BUILDING_LIBRARY) || defined(_LIBCXXABI_BUILDING_LIBRARY) 
|| !defined(_LIBCPP_COMPILER_CLANG_BASED)
 #  if !defined(_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS)
 #define _LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS
 #  endif
diff --git 
a/libcxx/test/libcxx/vendor/apple/availability-with-pedantic-errors.compile.pass.cpp
 
b/libcxx/test/libcxx/vendor/apple/availability-with-pedantic-errors.compile.pass.cpp
new file mode 100644
index 00..c55a0a4d6e5d1b
--- /dev/null
+++ 
b/libcxx/test/libcxx/vendor/apple/availability-with-pedantic-errors.compile.pass.cpp
@@ -0,0 +1,22 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// REQUIRES: stdlib=apple-libc++
+
+// Test that using -pedantic-errors doesn't turn off availability annotations.
+// This used to be the case because we used __has_extension(...) to enable the
+// availability annotations, and -pedantic-errors changes the behavior of
+// __has_extension(...) in an incompatible way.
+
+// ADDITIONAL_COMPILE_FLAGS: -pedantic-errors
+
+#include <__availability>
+
+#if defined(_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS)
+#  error Availability annotations should be enabled on Apple platforms in the 
system configuration!
+#endif

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


[llvm-branch-commits] [libcxx] release/18.x: [libc++] Enable availability based on the compiler instead of __has_extension (#84065) (PR #84374)

2024-03-07 Thread via llvm-branch-commits

https://github.com/llvmbot milestoned 
https://github.com/llvm/llvm-project/pull/84374
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [libcxx] release/18.x: [libc++] Enable availability based on the compiler instead of __has_extension (#84065) (PR #84374)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-libcxx

Author: None (llvmbot)


Changes

Backport 292a28df6c55679fad0589dea35278a8c66b2ae1

Requested by: @ldionne

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


2 Files Affected:

- (modified) libcxx/include/__availability (+3-4) 
- (added) 
libcxx/test/libcxx/vendor/apple/availability-with-pedantic-errors.compile.pass.cpp
 (+22) 


``diff
diff --git a/libcxx/include/__availability b/libcxx/include/__availability
index c5069a027750ec..b8b2da9bb12265 100644
--- a/libcxx/include/__availability
+++ b/libcxx/include/__availability
@@ -72,11 +72,10 @@
 #  endif
 #endif
 
-// Availability markup is disabled when building the library, or when the 
compiler
+// Availability markup is disabled when building the library, or when a 
non-Clang
+// compiler is used because only Clang supports the necessary attributes.
 // doesn't support the proper attributes.
-#if defined(_LIBCPP_BUILDING_LIBRARY) || defined(_LIBCXXABI_BUILDING_LIBRARY) 
||   \
-!__has_feature(attribute_availability_with_strict) || 
!__has_feature(attribute_availability_in_templates) ||   \
-!__has_extension(pragma_clang_attribute_external_declaration)
+#if defined(_LIBCPP_BUILDING_LIBRARY) || defined(_LIBCXXABI_BUILDING_LIBRARY) 
|| !defined(_LIBCPP_COMPILER_CLANG_BASED)
 #  if !defined(_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS)
 #define _LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS
 #  endif
diff --git 
a/libcxx/test/libcxx/vendor/apple/availability-with-pedantic-errors.compile.pass.cpp
 
b/libcxx/test/libcxx/vendor/apple/availability-with-pedantic-errors.compile.pass.cpp
new file mode 100644
index 00..c55a0a4d6e5d1b
--- /dev/null
+++ 
b/libcxx/test/libcxx/vendor/apple/availability-with-pedantic-errors.compile.pass.cpp
@@ -0,0 +1,22 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// REQUIRES: stdlib=apple-libc++
+
+// Test that using -pedantic-errors doesn't turn off availability annotations.
+// This used to be the case because we used __has_extension(...) to enable the
+// availability annotations, and -pedantic-errors changes the behavior of
+// __has_extension(...) in an incompatible way.
+
+// ADDITIONAL_COMPILE_FLAGS: -pedantic-errors
+
+#include <__availability>
+
+#if defined(_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS)
+#  error Availability annotations should be enabled on Apple platforms in the 
system configuration!
+#endif

``




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


[llvm-branch-commits] [flang] [flang][CodeGen] Fix use-after-free in BoxedProcedurePass (PR #84376)

2024-03-07 Thread Krzysztof Parzyszek via llvm-branch-commits

https://github.com/kparzysz created 
https://github.com/llvm/llvm-project/pull/84376

Replacing an element of an operation range while traversing the range can make 
the range invalid. Store the operations in a separate list, and traverse the 
list instead.
Additionally, avoid inspecting an operation that has been replaced.

This was detected by address sanitizer.

>From 58cda6db7030e178fbd861312dcee372e1558611 Mon Sep 17 00:00:00 2001
From: Krzysztof Parzyszek 
Date: Thu, 7 Mar 2024 14:21:45 -0600
Subject: [PATCH] [flang][CodeGen] Fix use-after-free in BoxedProcedurePass

Replacing an element of an operation range while traversing the range
can make the range invalid. Store the operations in a separate list,
and traverse the list instead.
Additionally, avoid inspecting an operation that has been replaced.

This was detected by address sanitizer.
---
 .../lib/Optimizer/CodeGen/BoxedProcedure.cpp  | 19 ---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp 
b/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
index 4cf39716a73755..2e34b0a1b492b1 100644
--- a/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
+++ b/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
@@ -208,7 +208,12 @@ class BoxedProcedurePass
   mlir::IRRewriter rewriter(context);
   BoxprocTypeRewriter typeConverter(mlir::UnknownLoc::get(context));
   mlir::Dialect *firDialect = context->getLoadedDialect("fir");
-  getModule().walk([&](mlir::Operation *op) {
+  llvm::SmallVector operations;
+
+  getModule().walk([&](mlir::Operation *op) { operations.push_back(op); });
+
+  for (mlir::Operation *op : operations) {
+bool opIsValid = true;
 typeConverter.setLocation(op->getLoc());
 if (auto addr = mlir::dyn_cast(op)) {
   mlir::Type ty = addr.getVal().getType();
@@ -220,6 +225,7 @@ class BoxedProcedurePass
 rewriter.setInsertionPoint(addr);
 rewriter.replaceOpWithNewOp(
 addr, typeConverter.convertType(addr.getType()), 
addr.getVal());
+opIsValid = false;
   } else if (typeConverter.needsConversion(resTy)) {
 rewriter.startOpModification(op);
 op->getResult(0).setType(typeConverter.convertType(resTy));
@@ -271,10 +277,12 @@ class BoxedProcedurePass
 llvm::ArrayRef{tramp});
 rewriter.replaceOpWithNewOp(embox, toTy,
adjustCall.getResult(0));
+opIsValid = false;
   } else {
 // Just forward the function as a pointer.
 rewriter.replaceOpWithNewOp(embox, toTy,
embox.getFunc());
+opIsValid = false;
   }
 } else if (auto global = mlir::dyn_cast(op)) {
   auto ty = global.getType();
@@ -297,6 +305,7 @@ class BoxedProcedurePass
 rewriter.replaceOpWithNewOp(
 mem, toTy, uniqName, bindcName, isPinned, mem.getTypeparams(),
 mem.getShape());
+opIsValid = false;
   }
 } else if (auto mem = mlir::dyn_cast(op)) {
   auto ty = mem.getType();
@@ -310,6 +319,7 @@ class BoxedProcedurePass
 rewriter.replaceOpWithNewOp(
 mem, toTy, uniqName, bindcName, mem.getTypeparams(),
 mem.getShape());
+opIsValid = false;
   }
 } else if (auto coor = mlir::dyn_cast(op)) {
   auto ty = coor.getType();
@@ -321,6 +331,7 @@ class BoxedProcedurePass
 auto toBaseTy = typeConverter.convertType(baseTy);
 rewriter.replaceOpWithNewOp(coor, toTy, 
coor.getRef(),
   coor.getCoor(), 
toBaseTy);
+opIsValid = false;
   }
 } else if (auto index = mlir::dyn_cast(op)) {
   auto ty = index.getType();
@@ -332,6 +343,7 @@ class BoxedProcedurePass
 auto toOnTy = typeConverter.convertType(onTy);
 rewriter.replaceOpWithNewOp(
 index, toTy, index.getFieldId(), toOnTy, 
index.getTypeparams());
+opIsValid = false;
   }
 } else if (auto index = mlir::dyn_cast(op)) {
   auto ty = index.getType();
@@ -343,6 +355,7 @@ class BoxedProcedurePass
 auto toOnTy = typeConverter.convertType(onTy);
 rewriter.replaceOpWithNewOp(
 index, toTy, index.getFieldId(), toOnTy, 
index.getTypeparams());
+opIsValid = false;
   }
 } else if (op->getDialect() == firDialect) {
   rewriter.startOpModification(op);
@@ -354,7 +367,7 @@ class BoxedProcedurePass
   rewriter.finalizeOpModification(op);
 }
 // Ensure block arguments are updated if needed.
-if (op->getNumRegions() != 0) {
+if (opIsValid && op->getNumRegions() != 0) {
   rewriter.startOpModifica

[llvm-branch-commits] [flang] [flang][CodeGen] Fix use-after-free in BoxedProcedurePass (PR #84376)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-flang-codegen

Author: Krzysztof Parzyszek (kparzysz)


Changes

Replacing an element of an operation range while traversing the range can make 
the range invalid. Store the operations in a separate list, and traverse the 
list instead.
Additionally, avoid inspecting an operation that has been replaced.

This was detected by address sanitizer.

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


1 Files Affected:

- (modified) flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp (+16-3) 


``diff
diff --git a/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp 
b/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
index 4cf39716a73755..2e34b0a1b492b1 100644
--- a/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
+++ b/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
@@ -208,7 +208,12 @@ class BoxedProcedurePass
   mlir::IRRewriter rewriter(context);
   BoxprocTypeRewriter typeConverter(mlir::UnknownLoc::get(context));
   mlir::Dialect *firDialect = context->getLoadedDialect("fir");
-  getModule().walk([&](mlir::Operation *op) {
+  llvm::SmallVector operations;
+
+  getModule().walk([&](mlir::Operation *op) { operations.push_back(op); });
+
+  for (mlir::Operation *op : operations) {
+bool opIsValid = true;
 typeConverter.setLocation(op->getLoc());
 if (auto addr = mlir::dyn_cast(op)) {
   mlir::Type ty = addr.getVal().getType();
@@ -220,6 +225,7 @@ class BoxedProcedurePass
 rewriter.setInsertionPoint(addr);
 rewriter.replaceOpWithNewOp(
 addr, typeConverter.convertType(addr.getType()), 
addr.getVal());
+opIsValid = false;
   } else if (typeConverter.needsConversion(resTy)) {
 rewriter.startOpModification(op);
 op->getResult(0).setType(typeConverter.convertType(resTy));
@@ -271,10 +277,12 @@ class BoxedProcedurePass
 llvm::ArrayRef{tramp});
 rewriter.replaceOpWithNewOp(embox, toTy,
adjustCall.getResult(0));
+opIsValid = false;
   } else {
 // Just forward the function as a pointer.
 rewriter.replaceOpWithNewOp(embox, toTy,
embox.getFunc());
+opIsValid = false;
   }
 } else if (auto global = mlir::dyn_cast(op)) {
   auto ty = global.getType();
@@ -297,6 +305,7 @@ class BoxedProcedurePass
 rewriter.replaceOpWithNewOp(
 mem, toTy, uniqName, bindcName, isPinned, mem.getTypeparams(),
 mem.getShape());
+opIsValid = false;
   }
 } else if (auto mem = mlir::dyn_cast(op)) {
   auto ty = mem.getType();
@@ -310,6 +319,7 @@ class BoxedProcedurePass
 rewriter.replaceOpWithNewOp(
 mem, toTy, uniqName, bindcName, mem.getTypeparams(),
 mem.getShape());
+opIsValid = false;
   }
 } else if (auto coor = mlir::dyn_cast(op)) {
   auto ty = coor.getType();
@@ -321,6 +331,7 @@ class BoxedProcedurePass
 auto toBaseTy = typeConverter.convertType(baseTy);
 rewriter.replaceOpWithNewOp(coor, toTy, 
coor.getRef(),
   coor.getCoor(), 
toBaseTy);
+opIsValid = false;
   }
 } else if (auto index = mlir::dyn_cast(op)) {
   auto ty = index.getType();
@@ -332,6 +343,7 @@ class BoxedProcedurePass
 auto toOnTy = typeConverter.convertType(onTy);
 rewriter.replaceOpWithNewOp(
 index, toTy, index.getFieldId(), toOnTy, 
index.getTypeparams());
+opIsValid = false;
   }
 } else if (auto index = mlir::dyn_cast(op)) {
   auto ty = index.getType();
@@ -343,6 +355,7 @@ class BoxedProcedurePass
 auto toOnTy = typeConverter.convertType(onTy);
 rewriter.replaceOpWithNewOp(
 index, toTy, index.getFieldId(), toOnTy, 
index.getTypeparams());
+opIsValid = false;
   }
 } else if (op->getDialect() == firDialect) {
   rewriter.startOpModification(op);
@@ -354,7 +367,7 @@ class BoxedProcedurePass
   rewriter.finalizeOpModification(op);
 }
 // Ensure block arguments are updated if needed.
-if (op->getNumRegions() != 0) {
+if (opIsValid && op->getNumRegions() != 0) {
   rewriter.startOpModification(op);
   for (mlir::Region ®ion : op->getRegions())
 for (mlir::Block &block : region.getBlocks())
@@ -366,7 +379,7 @@ class BoxedProcedurePass
 }
   rewriter.finalizeOpModification(op);
 }
-  });
+  }
 }
   }
 

``




https://github.com/llvm/llvm-project/pull/84376
___
llvm-branch-commits mailing list

[llvm-branch-commits] [compiler-rt] release/18.x: [test] Make two sanitize-coverage tests pass with glibc 2.39+ (PR #84239)

2024-03-07 Thread Vitaly Buka via llvm-branch-commits

vitalybuka wrote:

This is test only,
it passes LGTM

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


[llvm-branch-commits] [compiler-rt] release/18.x: [test] Make two sanitize-coverage tests pass with glibc 2.39+ (PR #84239)

2024-03-07 Thread Vitaly Buka via llvm-branch-commits

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


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


[llvm-branch-commits] [libcxx] release/18.x: [libc++] Enable availability based on the compiler instead of __has_extension (#84065) (PR #84374)

2024-03-07 Thread Louis Dionne via llvm-branch-commits

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


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


[llvm-branch-commits] [llvm] b67fec3 - Revert "[Orc] Add NotifyCreated callback for LLJITBuilder (#84175)"

2024-03-07 Thread via llvm-branch-commits

Author: Mehdi Amini
Date: 2024-03-07T15:15:56-08:00
New Revision: b67fec3d6f1f1c87cd3d8037701d4681b96bfd85

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

LOG: Revert "[Orc] Add NotifyCreated callback for LLJITBuilder (#84175)"

This reverts commit f78129e2bbafdd04a71bc09fc44e0797dd08db05.

Added: 


Modified: 
llvm/include/llvm/ExecutionEngine/Orc/LLJIT.h

Removed: 




diff  --git a/llvm/include/llvm/ExecutionEngine/Orc/LLJIT.h 
b/llvm/include/llvm/ExecutionEngine/Orc/LLJIT.h
index d5682fcaa28b79..76d16e63df2815 100644
--- a/llvm/include/llvm/ExecutionEngine/Orc/LLJIT.h
+++ b/llvm/include/llvm/ExecutionEngine/Orc/LLJIT.h
@@ -311,8 +311,6 @@ class LLJITBuilderState {
 
   using PlatformSetupFunction = unique_function(LLJIT 
&J)>;
 
-  using NotifyCreatedFunction = std::function;
-
   std::unique_ptr EPC;
   std::unique_ptr ES;
   std::optional JTMB;
@@ -323,7 +321,6 @@ class LLJITBuilderState {
   CompileFunctionCreator CreateCompileFunction;
   unique_function PrePlatformSetup;
   PlatformSetupFunction SetUpPlatform;
-  NotifyCreatedFunction NotifyCreated;
   unsigned NumCompileThreads = 0;
 
   /// Called prior to JIT class construcion to fix up defaults.
@@ -444,16 +441,6 @@ class LLJITBuilderSetters {
 return impl();
   }
 
-  /// Set up a callback after successful construction of the JIT.
-  ///
-  /// This is useful to attach generators to JITDylibs or inject initial symbol
-  /// definitions.
-  SetterImpl &
-  setNotifyCreatedCallback(LLJITBuilderState::NotifyCreatedFunction Callback) {
-impl().NotifyCreated = std::move(Callback);
-return impl();
-  }
-
   /// Set the number of compile threads to use.
   ///
   /// If set to zero, compilation will be performed on the execution thread 
when
@@ -487,11 +474,6 @@ class LLJITBuilderSetters {
 std::unique_ptr J(new JITType(impl(), Err));
 if (Err)
   return std::move(Err);
-
-if (impl().NotifyCreated)
-  if (Error Err = impl().NotifyCreated(*J))
-return Err;
-
 return std::move(J);
   }
 



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


[llvm-branch-commits] [NFC] [hwasan] also be more consistent when getting pointer types (PR #84399)

2024-03-07 Thread Florian Mayer via llvm-branch-commits

https://github.com/fmayer created 
https://github.com/llvm/llvm-project/pull/84399

None


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


[llvm-branch-commits] [NFC] [hwasan] also be more consistent when getting pointer types (PR #84399)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-transforms

Author: Florian Mayer (fmayer)


Changes



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


1 Files Affected:

- (modified) llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp (+2-6) 


``diff
diff --git a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
index 289183ecf0f286..61d54b850374e1 100644
--- a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -410,8 +410,8 @@ class HWAddressSanitizer {
   ShadowMapping Mapping;
 
   Type *VoidTy = Type::getVoidTy(M.getContext());
-  Type *IntptrTy;
-  PointerType *PtrTy;
+  Type *IntptrTy = M.getDataLayout().getIntPtrType(M.getContext());
+  PointerType *PtrTy = PointerType::get(M.getContext(), /* AddressSpace= */0);
   Type *Int8Ty = Type::getInt8Ty(M.getContext());
   Type *Int32Ty = Type::getInt32Ty(M.getContext());
   Type *Int64Ty = Type::getInt64Ty(M.getContext());
@@ -594,8 +594,6 @@ void HWAddressSanitizer::createHwasanCtorComdat() {
 /// inserts a call to __hwasan_init to the module's constructor list.
 void HWAddressSanitizer::initializeModule() {
   LLVM_DEBUG(dbgs() << "Init " << M.getName() << "\n");
-  auto &DL = M.getDataLayout();
-
   TargetTriple = Triple(M.getTargetTriple());
 
   // x86_64 currently has two modes:
@@ -613,8 +611,6 @@ void HWAddressSanitizer::initializeModule() {
 
   C = &(M.getContext());
   IRBuilder<> IRB(*C);
-  IntptrTy = IRB.getIntPtrTy(DL);
-  PtrTy = IRB.getPtrTy();
 
   HwasanCtorFunction = nullptr;
 

``




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


[llvm-branch-commits] [clang] [InstallAPI] Capture C++ Decls (PR #83953)

2024-03-07 Thread Zixu Wang via llvm-branch-commits

https://github.com/zixu-w approved this pull request.


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


[llvm-branch-commits] [clang] [InstallAPI] Capture C++ Decls (PR #83953)

2024-03-07 Thread Juergen Ributzka via llvm-branch-commits


@@ -13,6 +13,7 @@
 #ifndef LLVM_CLANG_INSTALLAPI_VISITOR_H
 #define LLVM_CLANG_INSTALLAPI_VISITOR_H
 
+#include "clang/AST/Availability.h"

ributzka wrote:

Could `AvailabilityInfo` be forward declared instead?

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


[llvm-branch-commits] [clang] [InstallAPI] Capture C++ Decls (PR #83953)

2024-03-07 Thread Cyndy Ishida via llvm-branch-commits

https://github.com/cyndyishida closed 
https://github.com/llvm/llvm-project/pull/83953
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [NFC] [hwasan] factor get[PC|FP] out of HWASan class (PR #84404)

2024-03-07 Thread Florian Mayer via llvm-branch-commits

https://github.com/fmayer created 
https://github.com/llvm/llvm-project/pull/84404

Also be consistent about naming SP / FP.

This is to prepare for stack history buffer for memtag-stack



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


[llvm-branch-commits] [NFC] [hwasan] factor get[PC|FP] out of HWASan class (PR #84404)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-compiler-rt-sanitizer

Author: Florian Mayer (fmayer)


Changes

Also be consistent about naming SP / FP.

This is to prepare for stack history buffer for memtag-stack


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


3 Files Affected:

- (modified) llvm/include/llvm/Transforms/Utils/MemoryTaggingSupport.h (+5) 
- (modified) llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp 
(+10-37) 
- (modified) llvm/lib/Transforms/Utils/MemoryTaggingSupport.cpp (+34) 


``diff
diff --git a/llvm/include/llvm/Transforms/Utils/MemoryTaggingSupport.h 
b/llvm/include/llvm/Transforms/Utils/MemoryTaggingSupport.h
index eb00e6c4e856df..cbbb8ff34a59e6 100644
--- a/llvm/include/llvm/Transforms/Utils/MemoryTaggingSupport.h
+++ b/llvm/include/llvm/Transforms/Utils/MemoryTaggingSupport.h
@@ -17,6 +17,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Analysis/StackSafetyAnalysis.h"
+#include "llvm/IR/IRBuilder.h"
 #include "llvm/Support/Alignment.h"
 
 namespace llvm {
@@ -79,6 +80,10 @@ class StackInfoBuilder {
 uint64_t getAllocaSizeInBytes(const AllocaInst &AI);
 void alignAndPadAlloca(memtag::AllocaInfo &Info, llvm::Align Align);
 
+Value *readRegister(IRBuilder<> &IRB, StringRef Name);
+Value *getSP(IRBuilder<> &IRB);
+Value *getPC(const Triple &TargetTriple, IRBuilder<> &IRB);
+
 } // namespace memtag
 } // namespace llvm
 
diff --git a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
index 61d54b850374e1..e2cdca5b71f404 100644
--- a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -357,7 +357,6 @@ class HWAddressSanitizer {
   bool instrumentStack(memtag::StackInfo &Info, Value *StackTag, Value *UARTag,
const DominatorTree &DT, const PostDominatorTree &PDT,
const LoopInfo &LI);
-  Value *readRegister(IRBuilder<> &IRB, StringRef Name);
   bool instrumentLandingPads(SmallVectorImpl &RetVec);
   Value *getNextTagWithCall(IRBuilder<> &IRB);
   Value *getStackBaseTag(IRBuilder<> &IRB);
@@ -373,8 +372,7 @@ class HWAddressSanitizer {
   void instrumentGlobal(GlobalVariable *GV, uint8_t Tag);
   void instrumentGlobals();
 
-  Value *getPC(IRBuilder<> &IRB);
-  Value *getFP(IRBuilder<> &IRB);
+  Value *getCachedSP(IRBuilder<> &IRB);
   Value *getFrameRecordInfo(IRBuilder<> &IRB);
 
   void instrumentPersonalityFunctions();
@@ -1169,7 +1167,7 @@ Value *HWAddressSanitizer::getStackBaseTag(IRBuilder<> 
&IRB) {
   // Extract some entropy from the stack pointer for the tags.
   // Take bits 20..28 (ASLR entropy) and xor with bits 0..8 (these differ
   // between functions).
-  Value *StackPointerLong = getFP(IRB);
+  Value *StackPointerLong = getCachedSP(IRB);
   Value *StackTag =
   applyTagMask(IRB, IRB.CreateXor(StackPointerLong,
   IRB.CreateLShr(StackPointerLong, 20)));
@@ -1186,7 +1184,7 @@ Value *HWAddressSanitizer::getAllocaTag(IRBuilder<> &IRB, 
Value *StackTag,
 }
 
 Value *HWAddressSanitizer::getUARTag(IRBuilder<> &IRB) {
-  Value *StackPointerLong = getFP(IRB);
+  Value *StackPointerLong = getCachedSP(IRB);
   Value *UARTag =
   applyTagMask(IRB, IRB.CreateLShr(StackPointerLong, PointerTagShift));
 
@@ -1247,32 +1245,16 @@ Value 
*HWAddressSanitizer::getHwasanThreadSlotPtr(IRBuilder<> &IRB, Type *Ty) {
   return nullptr;
 }
 
-Value *HWAddressSanitizer::getPC(IRBuilder<> &IRB) {
-  if (TargetTriple.getArch() == Triple::aarch64)
-return readRegister(IRB, "pc");
-  return IRB.CreatePtrToInt(IRB.GetInsertBlock()->getParent(), IntptrTy);
-}
-
-Value *HWAddressSanitizer::getFP(IRBuilder<> &IRB) {
-  if (!CachedSP) {
-// FIXME: use addressofreturnaddress (but implement it in aarch64 backend
-// first).
-Function *F = IRB.GetInsertBlock()->getParent();
-Module *M = F->getParent();
-auto *GetStackPointerFn = Intrinsic::getDeclaration(
-M, Intrinsic::frameaddress,
-IRB.getPtrTy(M->getDataLayout().getAllocaAddrSpace()));
-CachedSP = IRB.CreatePtrToInt(
-IRB.CreateCall(GetStackPointerFn, {Constant::getNullValue(Int32Ty)}),
-IntptrTy);
-  }
+Value *HWAddressSanitizer::getCachedSP(IRBuilder<> &IRB) {
+  if (!CachedSP)
+CachedSP = memtag::getSP(IRB);
   return CachedSP;
 }
 
 Value *HWAddressSanitizer::getFrameRecordInfo(IRBuilder<> &IRB) {
   // Prepare ring buffer data.
-  Value *PC = getPC(IRB);
-  Value *SP = getFP(IRB);
+  Value *PC = memtag::getPC(TargetTriple, IRB);
+  Value *SP = getCachedSP(IRB);
 
   // Mix SP and PC.
   // Assumptions:
@@ -1366,23 +1348,14 @@ void HWAddressSanitizer::emitPrologue(IRBuilder<> &IRB, 
bool WithFrameRecord) {
   }
 }
 
-Value *HWAddressSanitizer::readRegister(IRBuilder<> &IRB, StringRef Name) {
-  Module *M = IRB.GetInsertBlock()->getParent()->getParent();
-  Function *ReadRegister

[llvm-branch-commits] [NFC] [hwasan] factor get[PC|FP] out of HWASan class (PR #84404)

2024-03-07 Thread Florian Mayer via llvm-branch-commits

https://github.com/fmayer updated 
https://github.com/llvm/llvm-project/pull/84404


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


[llvm-branch-commits] [NFC] [hwasan] factor get[PC|FP] out of HWASan class (PR #84404)

2024-03-07 Thread Florian Mayer via llvm-branch-commits

https://github.com/fmayer updated 
https://github.com/llvm/llvm-project/pull/84404


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


[llvm-branch-commits] [NFC] [hwasan] factor get[PC|FP] out of HWASan class (PR #84404)

2024-03-07 Thread Florian Mayer via llvm-branch-commits

https://github.com/fmayer updated 
https://github.com/llvm/llvm-project/pull/84404


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


[llvm-branch-commits] [NFC] [hwasan] factor get[PC|FP] out of HWASan class (PR #84404)

2024-03-07 Thread Florian Mayer via llvm-branch-commits

https://github.com/fmayer updated 
https://github.com/llvm/llvm-project/pull/84404


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


[llvm-branch-commits] [llvm] release/18.x: [X86] Resolve FIXME: Enable PC relative calls on Windows (PR #84185)

2024-03-07 Thread via llvm-branch-commits

https://github.com/AtariDreams closed 
https://github.com/llvm/llvm-project/pull/84185
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer updated 
https://github.com/llvm/llvm-project/pull/84131

>From 407c7f7c24a87f409a921328605cc93637386d19 Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 8 Mar 2024 02:01:50 +
Subject: [PATCH] [mlir][IR] Add listener notifications for pattern begin/end

---
 mlir/include/mlir/IR/PatternMatch.h   | 30 +--
 .../Transforms/Utils/DialectConversion.cpp| 29 +++---
 .../Utils/GreedyPatternRewriteDriver.cpp  | 53 +++
 3 files changed, 77 insertions(+), 35 deletions(-)

diff --git a/mlir/include/mlir/IR/PatternMatch.h 
b/mlir/include/mlir/IR/PatternMatch.h
index e3500b3f9446d8..49544c42790d4d 100644
--- a/mlir/include/mlir/IR/PatternMatch.h
+++ b/mlir/include/mlir/IR/PatternMatch.h
@@ -432,11 +432,22 @@ class RewriterBase : public OpBuilder {
 /// Note: This notification is not triggered when unlinking an operation.
 virtual void notifyOperationErased(Operation *op) {}
 
-/// Notify the listener that the pattern failed to match the given
-/// operation, and provide a callback to populate a diagnostic with the
-/// reason why the failure occurred. This method allows for derived
-/// listeners to optionally hook into the reason why a rewrite failed, and
-/// display it to users.
+/// Notify the listener that the specified pattern is about to be applied
+/// at the specified root operation.
+virtual void notifyPatternBegin(const Pattern &pattern, Operation *op) {}
+
+/// Notify the listener that a pattern application finished with the
+/// specified status. "success" indicates that the pattern was applied
+/// successfully. "failure" indicates that the pattern could not be
+/// applied. The pattern may have communicated the reason for the failure
+/// with `notifyMatchFailure`.
+virtual void notifyPatternEnd(const Pattern &pattern,
+  LogicalResult status) {}
+
+/// Notify the listener that the pattern failed to match, and provide a
+/// callback to populate a diagnostic with the reason why the failure
+/// occurred. This method allows for derived listeners to optionally hook
+/// into the reason why a rewrite failed, and display it to users.
 virtual void
 notifyMatchFailure(Location loc,
function_ref reasonCallback) {}
@@ -478,6 +489,15 @@ class RewriterBase : public OpBuilder {
   if (auto *rewriteListener = dyn_cast(listener))
 rewriteListener->notifyOperationErased(op);
 }
+void notifyPatternBegin(const Pattern &pattern, Operation *op) override {
+  if (auto *rewriteListener = dyn_cast(listener))
+rewriteListener->notifyPatternBegin(pattern, op);
+}
+void notifyPatternEnd(const Pattern &pattern,
+  LogicalResult status) override {
+  if (auto *rewriteListener = dyn_cast(listener))
+rewriteListener->notifyPatternEnd(pattern, status);
+}
 void notifyMatchFailure(
 Location loc,
 function_ref reasonCallback) override {
diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index c1a261eab8487d..cd49bd121a62e5 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -1856,7 +1856,8 @@ class OperationLegalizer {
   using LegalizationAction = ConversionTarget::LegalizationAction;
 
   OperationLegalizer(const ConversionTarget &targetInfo,
- const FrozenRewritePatternSet &patterns);
+ const FrozenRewritePatternSet &patterns,
+ const ConversionConfig &config);
 
   /// Returns true if the given operation is known to be illegal on the target.
   bool isIllegal(Operation *op) const;
@@ -1948,12 +1949,16 @@ class OperationLegalizer {
 
   /// The pattern applicator to use for conversions.
   PatternApplicator applicator;
+
+  /// Dialect conversion configuration.
+  const ConversionConfig &config;
 };
 } // namespace
 
 OperationLegalizer::OperationLegalizer(const ConversionTarget &targetInfo,
-   const FrozenRewritePatternSet &patterns)
-: target(targetInfo), applicator(patterns) {
+   const FrozenRewritePatternSet &patterns,
+   const ConversionConfig &config)
+: target(targetInfo), applicator(patterns), config(config) {
   // The set of patterns that can be applied to illegal operations to transform
   // them into legal ones.
   DenseMap legalizerPatterns;
@@ -2098,7 +2103,10 @@ OperationLegalizer::legalizeWithPattern(Operation *op,
 
   // Functor that returns if the given pattern may be applied.
   auto canApply = [&](const Pattern &pattern) {
-return canApplyPattern(op, pattern, rewriter);
+bool canApply = canApplyPattern(op, pattern, rewriter);
+if (canApply && config.listener)
+ 

[llvm-branch-commits] [mlir] [mlir][Transform] Remove `notifyOperationErased` workaround (PR #84134)

2024-03-07 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer updated 
https://github.com/llvm/llvm-project/pull/84134

>From 9f25fbb0bc012e8710242af0901a6416ce57e5ba Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 8 Mar 2024 02:06:22 +
Subject: [PATCH] [mlir][Transform] Remove `notifyOperationErased` workaround

D144193 (#66771) has been merged.
---
 .../Dialect/Transform/IR/TransformInterfaces.cpp| 13 +
 1 file changed, 5 insertions(+), 8 deletions(-)

diff --git a/mlir/lib/Dialect/Transform/IR/TransformInterfaces.cpp 
b/mlir/lib/Dialect/Transform/IR/TransformInterfaces.cpp
index 71a9d61198e3fb..fe2eea535ffdcf 100644
--- a/mlir/lib/Dialect/Transform/IR/TransformInterfaces.cpp
+++ b/mlir/lib/Dialect/Transform/IR/TransformInterfaces.cpp
@@ -1278,14 +1278,11 @@ void transform::TrackingListener::notifyMatchFailure(
 }
 
 void transform::TrackingListener::notifyOperationErased(Operation *op) {
-  // TODO: Walk can be removed when D144193 has landed.
-  op->walk([&](Operation *op) {
-// Remove mappings for result values.
-for (OpResult value : op->getResults())
-  (void)replacePayloadValue(value, nullptr);
-// Remove mapping for op.
-(void)replacePayloadOp(op, nullptr);
-  });
+  // Remove mappings for result values.
+  for (OpResult value : op->getResults())
+(void)replacePayloadValue(value, nullptr);
+  // Remove mapping for op.
+  (void)replacePayloadOp(op, nullptr);
 }
 
 void transform::TrackingListener::notifyOperationReplaced(

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


[llvm-branch-commits] [mlir] [mlir][Transform] Mapping update rules for `apply_conversion_patterns` (PR #84140)

2024-03-07 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer updated 
https://github.com/llvm/llvm-project/pull/84140

>From 515d86af51fdb10c957222f20f56bd3fa4e2c4d3 Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 8 Mar 2024 02:09:29 +
Subject: [PATCH] [mlir][Transform] Specify mapping update rules for
 `apply_conversion_patterns`

---
 .../Transform/IR/TransformInterfaces.h|  51 +--
 .../mlir/Dialect/Transform/IR/TransformOps.td |  11 ++
 .../Transform/IR/TransformInterfaces.cpp  |  46 +-
 .../lib/Dialect/Transform/IR/TransformOps.cpp | 142 +-
 mlir/test/Dialect/Transform/ops-invalid.mlir  |  22 +++
 .../Transform/test-pattern-application.mlir   |  39 +
 6 files changed, 256 insertions(+), 55 deletions(-)

diff --git a/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h 
b/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h
index 32724ff4b98e8e..5db1a2c28fd414 100644
--- a/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h
+++ b/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h
@@ -1026,7 +1026,7 @@ class TrackingListener : public RewriterBase::Listener,
   /// Return the transform op in which this TrackingListener is used.
   TransformOpInterface getTransformOp() const { return transformOp; }
 
-private:
+protected:
   friend class TransformRewriter;
 
   void notifyOperationErased(Operation *op) override;
@@ -1034,6 +1034,7 @@ class TrackingListener : public RewriterBase::Listener,
   void notifyOperationReplaced(Operation *op, ValueRange newValues) override;
   using Listener::notifyOperationReplaced;
 
+private:
   /// The transform op in which this TrackingListener is used.
   TransformOpInterface transformOp;
 
@@ -1047,23 +1048,48 @@ class TrackingListener : public RewriterBase::Listener,
 /// A specialized listener that keeps track of cases in which no replacement
 /// payload could be found. The error state of this listener must be checked
 /// before the end of its lifetime.
-class ErrorCheckingTrackingListener : public TrackingListener {
+template 
+class ErrorCheckingTrackingListener : public TrackingListenerTy {
 public:
-  using transform::TrackingListener::TrackingListener;
+  using TrackingListenerTy::TrackingListenerTy;
 
-  ~ErrorCheckingTrackingListener() override;
+  ~ErrorCheckingTrackingListener() override {
+// The state of the ErrorCheckingTrackingListener must be checked and reset
+// if there was an error. This is to prevent errors from accidentally being
+// missed.
+assert(status.succeeded() && "listener state was not checked");
+  }
 
   /// Check and return the current error state of this listener. Afterwards,
   /// resets the error state to "success".
-  DiagnosedSilenceableFailure checkAndResetError();
+  DiagnosedSilenceableFailure checkAndResetError() {
+DiagnosedSilenceableFailure s = std::move(status);
+status = DiagnosedSilenceableFailure::success();
+errorCounter = 0;
+return s;
+  }
 
   /// Return "true" if this tracking listener had a failure.
-  bool failed() const;
+  bool failed() const { return !status.succeeded(); }
 
 protected:
-  void
-  notifyPayloadReplacementNotFound(Operation *op, ValueRange values,
-   DiagnosedSilenceableFailure &&diag) 
override;
+  void notifyPayloadReplacementNotFound(
+  Operation *op, ValueRange values,
+  DiagnosedSilenceableFailure &&diag) override {
+// Merge potentially existing diags and store the result in the listener.
+SmallVector diags;
+diag.takeDiagnostics(diags);
+if (!status.succeeded())
+  status.takeDiagnostics(diags);
+status = DiagnosedSilenceableFailure::silenceableFailure(std::move(diags));
+
+// Report more details.
+status.attachNote(op->getLoc()) << "[" << errorCounter << "] replaced op";
+for (auto &&[index, value] : llvm::enumerate(values))
+  status.attachNote(value.getLoc())
+  << "[" << errorCounter << "] replacement value " << index;
+++errorCounter;
+  }
 
 private:
   /// The error state of this listener. "Success" indicates that no error
@@ -1082,8 +1108,9 @@ class TransformRewriter : public RewriterBase {
   friend class TransformState;
 
   /// Create a new TransformRewriter.
-  explicit TransformRewriter(MLIRContext *ctx,
- ErrorCheckingTrackingListener *listener);
+  explicit TransformRewriter(
+  MLIRContext *ctx,
+  ErrorCheckingTrackingListener *listener);
 
 public:
   /// Return "true" if the tracking listener had failures.
@@ -1106,7 +1133,7 @@ class TransformRewriter : public RewriterBase {
Operation *replacement);
 
 private:
-  ErrorCheckingTrackingListener *const listener;
+  ErrorCheckingTrackingListener *const listener;
 };
 
 /// This trait is supposed to be attached to Transform dialect operations that
diff --git a/mlir/include/mlir/Dialect/Transform/IR/TransformOps.td 
b/mlir/include/mlir/Dialect/Transfo

[llvm-branch-commits] [llvm] ReleaseNotes for LLVM binary utilities (PR #83751)

2024-03-07 Thread Fangrui Song via llvm-branch-commits

MaskRay wrote:

@tstellar ready for merge!

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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer updated 
https://github.com/llvm/llvm-project/pull/84131

>From 0aef4b91f6aad0335e7eae2849edffd4338f4c40 Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 8 Mar 2024 03:42:15 +
Subject: [PATCH] [mlir][IR] Add listener notifications for pattern begin/end

---
 mlir/include/mlir/IR/PatternMatch.h   | 30 --
 mlir/include/mlir/Rewrite/PatternApplicator.h |  6 +-
 mlir/lib/Rewrite/PatternApplicator.cpp|  6 +-
 .../Transforms/Utils/DialectConversion.cpp| 29 +++---
 .../Utils/GreedyPatternRewriteDriver.cpp  | 57 +++
 5 files changed, 85 insertions(+), 43 deletions(-)

diff --git a/mlir/include/mlir/IR/PatternMatch.h 
b/mlir/include/mlir/IR/PatternMatch.h
index e3500b3f9446d8..49544c42790d4d 100644
--- a/mlir/include/mlir/IR/PatternMatch.h
+++ b/mlir/include/mlir/IR/PatternMatch.h
@@ -432,11 +432,22 @@ class RewriterBase : public OpBuilder {
 /// Note: This notification is not triggered when unlinking an operation.
 virtual void notifyOperationErased(Operation *op) {}
 
-/// Notify the listener that the pattern failed to match the given
-/// operation, and provide a callback to populate a diagnostic with the
-/// reason why the failure occurred. This method allows for derived
-/// listeners to optionally hook into the reason why a rewrite failed, and
-/// display it to users.
+/// Notify the listener that the specified pattern is about to be applied
+/// at the specified root operation.
+virtual void notifyPatternBegin(const Pattern &pattern, Operation *op) {}
+
+/// Notify the listener that a pattern application finished with the
+/// specified status. "success" indicates that the pattern was applied
+/// successfully. "failure" indicates that the pattern could not be
+/// applied. The pattern may have communicated the reason for the failure
+/// with `notifyMatchFailure`.
+virtual void notifyPatternEnd(const Pattern &pattern,
+  LogicalResult status) {}
+
+/// Notify the listener that the pattern failed to match, and provide a
+/// callback to populate a diagnostic with the reason why the failure
+/// occurred. This method allows for derived listeners to optionally hook
+/// into the reason why a rewrite failed, and display it to users.
 virtual void
 notifyMatchFailure(Location loc,
function_ref reasonCallback) {}
@@ -478,6 +489,15 @@ class RewriterBase : public OpBuilder {
   if (auto *rewriteListener = dyn_cast(listener))
 rewriteListener->notifyOperationErased(op);
 }
+void notifyPatternBegin(const Pattern &pattern, Operation *op) override {
+  if (auto *rewriteListener = dyn_cast(listener))
+rewriteListener->notifyPatternBegin(pattern, op);
+}
+void notifyPatternEnd(const Pattern &pattern,
+  LogicalResult status) override {
+  if (auto *rewriteListener = dyn_cast(listener))
+rewriteListener->notifyPatternEnd(pattern, status);
+}
 void notifyMatchFailure(
 Location loc,
 function_ref reasonCallback) override {
diff --git a/mlir/include/mlir/Rewrite/PatternApplicator.h 
b/mlir/include/mlir/Rewrite/PatternApplicator.h
index f7871f819a273b..c767bf8fee9073 100644
--- a/mlir/include/mlir/Rewrite/PatternApplicator.h
+++ b/mlir/include/mlir/Rewrite/PatternApplicator.h
@@ -68,9 +68,9 @@ class PatternApplicator {
   ///invalidate the match and try another pattern.
   LogicalResult
   matchAndRewrite(Operation *op, PatternRewriter &rewriter,
-  function_ref canApply = {},
-  function_ref onFailure = {},
-  function_ref onSuccess = {});
+  std::function canApply = {},
+  std::function onFailure = {},
+  std::function onSuccess = 
{});
 
   /// Apply a cost model to the patterns within this applicator.
   void applyCostModel(CostModel model);
diff --git a/mlir/lib/Rewrite/PatternApplicator.cpp 
b/mlir/lib/Rewrite/PatternApplicator.cpp
index ea43f8a147d479..fecfb030a77fbf 100644
--- a/mlir/lib/Rewrite/PatternApplicator.cpp
+++ b/mlir/lib/Rewrite/PatternApplicator.cpp
@@ -129,9 +129,9 @@ void PatternApplicator::walkAllPatterns(
 
 LogicalResult PatternApplicator::matchAndRewrite(
 Operation *op, PatternRewriter &rewriter,
-function_ref canApply,
-function_ref onFailure,
-function_ref onSuccess) {
+std::function canApply,
+std::function onFailure,
+std::function onSuccess) {
   // Before checking native patterns, first match against the bytecode. This
   // won't automatically perform any rewrites so there is no need to worry 
about
   // conflicts.
diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index c1a261eab8487d..cd49bd121a62e5 100644
--- a/mlir/lib/Transforms/Utils/DialectConve

[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Mehdi Amini via llvm-branch-commits


@@ -68,9 +68,9 @@ class PatternApplicator {
   ///invalidate the match and try another pattern.
   LogicalResult
   matchAndRewrite(Operation *op, PatternRewriter &rewriter,
-  function_ref canApply = {},
-  function_ref onFailure = {},
-  function_ref onSuccess = {});
+  std::function canApply = {},
+  std::function onFailure = {},
+  std::function onSuccess = 
{});

joker-eph wrote:

Why this change?

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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Mehdi Amini via llvm-branch-commits


@@ -562,30 +562,39 @@ bool GreedyPatternRewriteDriver::processWorklist() {
 // Try to match one of the patterns. The rewriter is automatically
 // notified of any necessary changes, so there is nothing else to do
 // here.
+std::function canApply = nullptr;
+std::function onFailure = nullptr;
+std::function onSuccess = nullptr;
+bool debugBuild = false;
 #ifndef NDEBUG
-auto canApply = [&](const Pattern &pattern) {
-  LLVM_DEBUG({
-logger.getOStream() << "\n";
-logger.startLine() << "* Pattern " << pattern.getDebugName() << " : '"
-   << op->getName() << " -> (";
-llvm::interleaveComma(pattern.getGeneratedOps(), logger.getOStream());
-logger.getOStream() << ")' {\n";
-logger.indent();
-  });
-  return true;
-};
-auto onFailure = [&](const Pattern &pattern) {
-  LLVM_DEBUG(logResult("failure", "pattern failed to match"));
-};
-auto onSuccess = [&](const Pattern &pattern) {
-  LLVM_DEBUG(logResult("success", "pattern applied successfully"));
-  return success();
-};
-#else
-function_ref canApply = {};
-function_ref onFailure = {};
-function_ref onSuccess = {};
-#endif
+debugBuild = true;

joker-eph wrote:

Why changing the structure of the code with this variable?

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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Mehdi Amini via llvm-branch-commits


@@ -562,30 +562,39 @@ bool GreedyPatternRewriteDriver::processWorklist() {
 // Try to match one of the patterns. The rewriter is automatically
 // notified of any necessary changes, so there is nothing else to do
 // here.
+std::function canApply = nullptr;
+std::function onFailure = nullptr;
+std::function onSuccess = nullptr;
+bool debugBuild = false;
 #ifndef NDEBUG
-auto canApply = [&](const Pattern &pattern) {
-  LLVM_DEBUG({
-logger.getOStream() << "\n";
-logger.startLine() << "* Pattern " << pattern.getDebugName() << " : '"
-   << op->getName() << " -> (";
-llvm::interleaveComma(pattern.getGeneratedOps(), logger.getOStream());
-logger.getOStream() << ")' {\n";
-logger.indent();
-  });
-  return true;
-};
-auto onFailure = [&](const Pattern &pattern) {
-  LLVM_DEBUG(logResult("failure", "pattern failed to match"));
-};
-auto onSuccess = [&](const Pattern &pattern) {
-  LLVM_DEBUG(logResult("success", "pattern applied successfully"));
-  return success();
-};
-#else
-function_ref canApply = {};
-function_ref onFailure = {};
-function_ref onSuccess = {};
-#endif
+debugBuild = true;

joker-eph wrote:

Oh never mind I see!

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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits


@@ -68,9 +68,9 @@ class PatternApplicator {
   ///invalidate the match and try another pattern.
   LogicalResult
   matchAndRewrite(Operation *op, PatternRewriter &rewriter,
-  function_ref canApply = {},
-  function_ref onFailure = {},
-  function_ref onSuccess = {});
+  std::function canApply = {},
+  std::function onFailure = {},
+  std::function onSuccess = 
{});

matthias-springer wrote:

There is a `stack-use-after-scope` (reported by ASAN, also crashes in opt mode) 
with `function_ref`. The callback in the greedy pattern rewriter is defined 
inside of an `if` check:
```c++
function_ref canApply = {};
function_ref onFailure = {};
function_ref onSuccess = {};
bool debugBuild = false;
#ifdef NDEBUG
debugBuild = true;
#endif // NDEBUG
if (debugBuild || config.listener) {
  canApply = [&](const Pattern &pattern) {
if (this->config.listener) { /* ... */ }
// ...
  }
  // ...
}

// `canApply` points to a lambda that is out of scope.
LogicalResult matchResult =
matcher.matchAndRewrite(op, *this, canApply, onFailure, onSuccess);
```

`function_ref` is a "non-owning function wrapper", but the lambda captures 
`this`.

Changing to `std::function` is one way to fix it. I could also just always pass 
a lambda. That would actually be my preferred solution, but there is a slight 
overhead when running in opt mode and without listener because the callback 
would always be called (even if it does not do anything):
```c++
LogicalResult matchResult = matcher.matchAndRewrite(
op, *this,
/*canApply=*/[&](const Pattern &pattern) {
  if (this->listener) { /* ... */ }
  // ...
},
/*onFailure=*/[&](const Pattern &pattern) { /* ... */},
/*onSuccess=*/[&](const Pattern &pattern) { /* ... */});
```

What do you think?


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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer edited 
https://github.com/llvm/llvm-project/pull/84131
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer edited 
https://github.com/llvm/llvm-project/pull/84131
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits


@@ -68,9 +68,9 @@ class PatternApplicator {
   ///invalidate the match and try another pattern.
   LogicalResult
   matchAndRewrite(Operation *op, PatternRewriter &rewriter,
-  function_ref canApply = {},
-  function_ref onFailure = {},
-  function_ref onSuccess = {});
+  std::function canApply = {},
+  std::function onFailure = {},
+  std::function onSuccess = 
{});

matthias-springer wrote:

(The existing code seemed to care about performance here; There were different 
`canApply` etc. depending on `NDEBUG`.)


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


[llvm-branch-commits] [llvm] Remove RC suffix (PR #84430)

2024-03-07 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar created 
https://github.com/llvm/llvm-project/pull/84430

None

>From b92012c777e602d557124583651313a0afa33484 Mon Sep 17 00:00:00 2001
From: Tobias Hieta 
Date: Tue, 19 Sep 2023 09:44:33 +0200
Subject: [PATCH] Remove RC suffix

---
 llvm/CMakeLists.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index 44f2850b92d522..389bd8b6422da4 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -25,7 +25,7 @@ if(NOT DEFINED LLVM_VERSION_PATCH)
   set(LLVM_VERSION_PATCH 0)
 endif()
 if(NOT DEFINED LLVM_VERSION_SUFFIX)
-  set(LLVM_VERSION_SUFFIX rc)
+  set(LLVM_VERSION_SUFFIX)
 endif()
 
 if (NOT PACKAGE_VERSION)

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


[llvm-branch-commits] [llvm] Remove RC suffix (PR #84430)

2024-03-07 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar updated 
https://github.com/llvm/llvm-project/pull/84430

>From b92012c777e602d557124583651313a0afa33484 Mon Sep 17 00:00:00 2001
From: Tobias Hieta 
Date: Tue, 19 Sep 2023 09:44:33 +0200
Subject: [PATCH 1/2] Remove RC suffix

---
 llvm/CMakeLists.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index 44f2850b92d522..389bd8b6422da4 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -25,7 +25,7 @@ if(NOT DEFINED LLVM_VERSION_PATCH)
   set(LLVM_VERSION_PATCH 0)
 endif()
 if(NOT DEFINED LLVM_VERSION_SUFFIX)
-  set(LLVM_VERSION_SUFFIX rc)
+  set(LLVM_VERSION_SUFFIX)
 endif()
 
 if (NOT PACKAGE_VERSION)

>From dba2a75e9c7ef81fe84774ba5eee5e67e01d801a Mon Sep 17 00:00:00 2001
From: Tom Stellard 
Date: Thu, 7 Mar 2024 21:27:31 -0800
Subject: [PATCH 2/2] Bump version to 18.1.1

---
 llvm/CMakeLists.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index 389bd8b6422da4..ddf95cbc6c5175 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -22,7 +22,7 @@ if(NOT DEFINED LLVM_VERSION_MINOR)
   set(LLVM_VERSION_MINOR 1)
 endif()
 if(NOT DEFINED LLVM_VERSION_PATCH)
-  set(LLVM_VERSION_PATCH 0)
+  set(LLVM_VERSION_PATCH 1)
 endif()
 if(NOT DEFINED LLVM_VERSION_SUFFIX)
   set(LLVM_VERSION_SUFFIX)

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


[llvm-branch-commits] [llvm] release/18.x: [llvm][LoongArch] Improve loongarch_lasx_xvpermi_q instrinsic (#82984) (PR #83540)

2024-03-07 Thread Lu Weining via llvm-branch-commits

SixWeining wrote:

> I have some doubt about this change.
> 
> To me if the user requests `xvpermi.q` via the `loongarch_lasx_xvpermi_q` 
> intrinsic, we should give her/him the `xvpermi.q` instruction. If (s)he is 
> passing an invalid operand then (s)he is invoking the undefined behavior 
> herself/himself and we don't need to guarantee a thing.
> 
> So to me we should not merge this and we should revert this change for main. 
> Or am I missing something? @xen0n @heiher @SixWeining @MaskRay

Yes, it can be argued. But I know gcc has similar change.

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


[llvm-branch-commits] [llvm] release/18.x: [llvm][LoongArch] Improve loongarch_lasx_xvpermi_q instrinsic (#82984) (PR #83540)

2024-03-07 Thread WÁNG Xuěruì via llvm-branch-commits

xen0n wrote:

For the record, based on the principle of "explicit is better than implicit" 
that generally holds, I'd favor an approach where such compile-time-verifiable 
out-of-range operands are given compile-time errors, or we should just pass 
through the value unmodified. Otherwise the intrinsic would have to carry the 
workaround effectively forever, and we could find ourselves trapped if later 
micro-architectures actually start to make use of the currently cleared bits.

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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Mehdi Amini via llvm-branch-commits


@@ -68,9 +68,9 @@ class PatternApplicator {
   ///invalidate the match and try another pattern.
   LogicalResult
   matchAndRewrite(Operation *op, PatternRewriter &rewriter,
-  function_ref canApply = {},
-  function_ref onFailure = {},
-  function_ref onSuccess = {});
+  std::function canApply = {},
+  std::function onFailure = {},
+  std::function onSuccess = 
{});

joker-eph wrote:

That can explain why you changed it at the call-site, but I'm puzzled about 
this function: it does not capture the callback as far as I can tell.

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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits


@@ -68,9 +68,9 @@ class PatternApplicator {
   ///invalidate the match and try another pattern.
   LogicalResult
   matchAndRewrite(Operation *op, PatternRewriter &rewriter,
-  function_ref canApply = {},
-  function_ref onFailure = {},
-  function_ref onSuccess = {});
+  std::function canApply = {},
+  std::function onFailure = {},
+  std::function onSuccess = 
{});

matthias-springer wrote:

What are you referring to with `this function`?

The problem here is really just caused by the fact that the `canApply =` 
assignment is inside of a nested scope. And the lambda object is dead by the 
time `matcher.matchAndRewrite` is called. I.e., the `canApply` function_ref 
points to an already free'd lambda. At least that's my understanding.

What's the C++ guidelines wrt. to `function` vs. `function_ref`. This is the 
first time I ran into such an issue, and assigning lambdas to `function_ref` 
feels "dangerous" to me now. When using `function`, I don't have to think about 
the lifetime of an object.


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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer edited 
https://github.com/llvm/llvm-project/pull/84131
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang-tools-extra] [clangd] Add clangd 18 release notes (PR #84436)

2024-03-07 Thread Nathan Ridge via llvm-branch-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/84436

None

>From 41cdc4a095d3082a3d6764c8950e626156c7bb07 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Fri, 8 Mar 2024 02:00:08 -0500
Subject: [PATCH] [clangd] Add clangd 18 release notes

---
 clang-tools-extra/docs/ReleaseNotes.rst | 33 +++--
 1 file changed, 31 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 5758b5acbc0b56..d963642b812fbf 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -51,21 +51,40 @@ Improvements to clangd
 Inlay hints
 ^^^
 
+- Type hints
+* Improved heuristics for showing sugared vs. desguared types
+* Some hints which provide no information (e.g. ) are 
now omitted
+- Parameter hints
+* Parameter hints are now shown for calls through function pointers
+* Parameter hints are now shown for calls to a class's ``operator()``
+* No longer show bogus parameter hints for some builtins like 
``__builtin_dump_struct``
+
 Diagnostics
 ^^^
 
-Semantic Highlighting
-^
+- Improved quality of include-cleaner diagnostics (missing and unused includes)
 
 Compile flags
 ^
 
+- System include extractor (``--query-driver``) improvements
+* The directory containing builtin headers is now excluded from extracted 
system includes
+* Various flags which can affect the system includes (``--target``, 
``--stdlib``, ``-specs``) are now forwarded to the driver
+* Fixed a bug where clangd would sometimes try to call a driver that 
didn't have obj-c support with ``-x objective-c++-header``
+* The driver path is now dot-normalized before being compared to the 
``--query-driver`` pattern
+* ``--query-driver`` is now supported by ``clangd-indexer``
+- Fixed a regression in clangd 17 where response files would not be expanded
+
 Hover
 ^
 
+- Hover now shows alignment info for fields and records
+
 Code completion
 ^^^
 
+- Refined heuristics for determining whether the use of a function can be a 
call or not
+
 Code actions
 
 
@@ -75,15 +94,25 @@ Code actions
 Signature help
 ^^
 
+- Improved support for calls through function pointer types
+
 Cross-references
 
 
+- Improved support for C++20 concepts
+- Find-references now works for labels
+- Improvements to template heuristics
+
 Objective-C
 ^^^
 
 Miscellaneous
 ^
 
+- Various stability improvements, e.g. crash fixes
+- Improved error recovery on invalid code
+- Clangd now bails gracefully on assembly and IR source files
+
 Improvements to clang-doc
 -
 

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


[llvm-branch-commits] [clang-tools-extra] [clangd] Add clangd 18 release notes (PR #84436)

2024-03-07 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: Nathan Ridge (HighCommander4)


Changes



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


1 Files Affected:

- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+31-2) 


``diff
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 5758b5acbc0b56..d963642b812fbf 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -51,21 +51,40 @@ Improvements to clangd
 Inlay hints
 ^^^
 
+- Type hints
+* Improved heuristics for showing sugared vs. desguared types
+* Some hints which provide no information (e.g. ) are 
now omitted
+- Parameter hints
+* Parameter hints are now shown for calls through function pointers
+* Parameter hints are now shown for calls to a class's ``operator()``
+* No longer show bogus parameter hints for some builtins like 
``__builtin_dump_struct``
+
 Diagnostics
 ^^^
 
-Semantic Highlighting
-^
+- Improved quality of include-cleaner diagnostics (missing and unused includes)
 
 Compile flags
 ^
 
+- System include extractor (``--query-driver``) improvements
+* The directory containing builtin headers is now excluded from extracted 
system includes
+* Various flags which can affect the system includes (``--target``, 
``--stdlib``, ``-specs``) are now forwarded to the driver
+* Fixed a bug where clangd would sometimes try to call a driver that 
didn't have obj-c support with ``-x objective-c++-header``
+* The driver path is now dot-normalized before being compared to the 
``--query-driver`` pattern
+* ``--query-driver`` is now supported by ``clangd-indexer``
+- Fixed a regression in clangd 17 where response files would not be expanded
+
 Hover
 ^
 
+- Hover now shows alignment info for fields and records
+
 Code completion
 ^^^
 
+- Refined heuristics for determining whether the use of a function can be a 
call or not
+
 Code actions
 
 
@@ -75,15 +94,25 @@ Code actions
 Signature help
 ^^
 
+- Improved support for calls through function pointer types
+
 Cross-references
 
 
+- Improved support for C++20 concepts
+- Find-references now works for labels
+- Improvements to template heuristics
+
 Objective-C
 ^^^
 
 Miscellaneous
 ^
 
+- Various stability improvements, e.g. crash fixes
+- Improved error recovery on invalid code
+- Clangd now bails gracefully on assembly and IR source files
+
 Improvements to clang-doc
 -
 

``




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


[llvm-branch-commits] [clang-tools-extra] [clangd] Add clangd 18 release notes (PR #84436)

2024-03-07 Thread Nathan Ridge via llvm-branch-commits

HighCommander4 wrote:

To prepare these, I went through the clangd commits in clangd 18 and made note 
of what seemed notable to me.

In some areas of the code that I'm less familiar with, I was somewhat vague 
(e.g. under "Diagnostics" I added "Improved quality of include-cleaner 
diagnostics (missing and unused includes)"; if someone more familiar with 
include-cleaner would like to expand on that with more specific improvements, 
that would be welcome).

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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Mehdi Amini via llvm-branch-commits


@@ -68,9 +68,9 @@ class PatternApplicator {
   ///invalidate the match and try another pattern.
   LogicalResult
   matchAndRewrite(Operation *op, PatternRewriter &rewriter,
-  function_ref canApply = {},
-  function_ref onFailure = {},
-  function_ref onSuccess = {});
+  std::function canApply = {},
+  std::function onFailure = {},
+  std::function onSuccess = 
{});

joker-eph wrote:

> What are you referring to with this function?

Where this comment thread is anchored: `matchAndRewrite`

> The problem here is really just caused by the fact that the canApply = 
> assignment is inside of a nested scope. And the lambda object is dead by the 
> time matcher.matchAndRewrite is called. I.e., the canApply function_ref 
> points to an already free'd lambda. At least that's my understanding.

Yes, but that's a problem for the call-site, I don't quite see where you make 
the connection to the signature of `matchAndRewrite`?


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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Mehdi Amini via llvm-branch-commits

https://github.com/joker-eph edited 
https://github.com/llvm/llvm-project/pull/84131
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Mehdi Amini via llvm-branch-commits

https://github.com/joker-eph edited 
https://github.com/llvm/llvm-project/pull/84131
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer updated 
https://github.com/llvm/llvm-project/pull/84131

>From 24a56caffaa23f6da73b129ca96f28e9a9bbf388 Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 8 Mar 2024 07:19:33 +
Subject: [PATCH] [mlir][IR] Add listener notifications for pattern begin/end

---
 mlir/include/mlir/IR/PatternMatch.h   | 30 ++---
 .../Transforms/Utils/DialectConversion.cpp| 29 +
 .../Utils/GreedyPatternRewriteDriver.cpp  | 42 ---
 3 files changed, 73 insertions(+), 28 deletions(-)

diff --git a/mlir/include/mlir/IR/PatternMatch.h 
b/mlir/include/mlir/IR/PatternMatch.h
index e3500b3f9446d8..49544c42790d4d 100644
--- a/mlir/include/mlir/IR/PatternMatch.h
+++ b/mlir/include/mlir/IR/PatternMatch.h
@@ -432,11 +432,22 @@ class RewriterBase : public OpBuilder {
 /// Note: This notification is not triggered when unlinking an operation.
 virtual void notifyOperationErased(Operation *op) {}
 
-/// Notify the listener that the pattern failed to match the given
-/// operation, and provide a callback to populate a diagnostic with the
-/// reason why the failure occurred. This method allows for derived
-/// listeners to optionally hook into the reason why a rewrite failed, and
-/// display it to users.
+/// Notify the listener that the specified pattern is about to be applied
+/// at the specified root operation.
+virtual void notifyPatternBegin(const Pattern &pattern, Operation *op) {}
+
+/// Notify the listener that a pattern application finished with the
+/// specified status. "success" indicates that the pattern was applied
+/// successfully. "failure" indicates that the pattern could not be
+/// applied. The pattern may have communicated the reason for the failure
+/// with `notifyMatchFailure`.
+virtual void notifyPatternEnd(const Pattern &pattern,
+  LogicalResult status) {}
+
+/// Notify the listener that the pattern failed to match, and provide a
+/// callback to populate a diagnostic with the reason why the failure
+/// occurred. This method allows for derived listeners to optionally hook
+/// into the reason why a rewrite failed, and display it to users.
 virtual void
 notifyMatchFailure(Location loc,
function_ref reasonCallback) {}
@@ -478,6 +489,15 @@ class RewriterBase : public OpBuilder {
   if (auto *rewriteListener = dyn_cast(listener))
 rewriteListener->notifyOperationErased(op);
 }
+void notifyPatternBegin(const Pattern &pattern, Operation *op) override {
+  if (auto *rewriteListener = dyn_cast(listener))
+rewriteListener->notifyPatternBegin(pattern, op);
+}
+void notifyPatternEnd(const Pattern &pattern,
+  LogicalResult status) override {
+  if (auto *rewriteListener = dyn_cast(listener))
+rewriteListener->notifyPatternEnd(pattern, status);
+}
 void notifyMatchFailure(
 Location loc,
 function_ref reasonCallback) override {
diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index c1a261eab8487d..cd49bd121a62e5 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -1856,7 +1856,8 @@ class OperationLegalizer {
   using LegalizationAction = ConversionTarget::LegalizationAction;
 
   OperationLegalizer(const ConversionTarget &targetInfo,
- const FrozenRewritePatternSet &patterns);
+ const FrozenRewritePatternSet &patterns,
+ const ConversionConfig &config);
 
   /// Returns true if the given operation is known to be illegal on the target.
   bool isIllegal(Operation *op) const;
@@ -1948,12 +1949,16 @@ class OperationLegalizer {
 
   /// The pattern applicator to use for conversions.
   PatternApplicator applicator;
+
+  /// Dialect conversion configuration.
+  const ConversionConfig &config;
 };
 } // namespace
 
 OperationLegalizer::OperationLegalizer(const ConversionTarget &targetInfo,
-   const FrozenRewritePatternSet &patterns)
-: target(targetInfo), applicator(patterns) {
+   const FrozenRewritePatternSet &patterns,
+   const ConversionConfig &config)
+: target(targetInfo), applicator(patterns), config(config) {
   // The set of patterns that can be applied to illegal operations to transform
   // them into legal ones.
   DenseMap legalizerPatterns;
@@ -2098,7 +2103,10 @@ OperationLegalizer::legalizeWithPattern(Operation *op,
 
   // Functor that returns if the given pattern may be applied.
   auto canApply = [&](const Pattern &pattern) {
-return canApplyPattern(op, pattern, rewriter);
+bool canApply = canApplyPattern(op, pattern, rewriter);
+if (canApply && config.listene

[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits


@@ -68,9 +68,9 @@ class PatternApplicator {
   ///invalidate the match and try another pattern.
   LogicalResult
   matchAndRewrite(Operation *op, PatternRewriter &rewriter,
-  function_ref canApply = {},
-  function_ref onFailure = {},
-  function_ref onSuccess = {});
+  std::function canApply = {},
+  std::function onFailure = {},
+  std::function onSuccess = 
{});

matthias-springer wrote:

That's a good way to think about it.


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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Mehdi Amini via llvm-branch-commits


@@ -572,20 +571,33 @@ bool GreedyPatternRewriteDriver::processWorklist() {
 logger.getOStream() << ")' {\n";
 logger.indent();
   });
+  if (config.listener)
+config.listener->notifyPatternBegin(pattern, op);
   return true;
 };
-auto onFailure = [&](const Pattern &pattern) {
-  LLVM_DEBUG(logResult("failure", "pattern failed to match"));
-};
-auto onSuccess = [&](const Pattern &pattern) {
-  LLVM_DEBUG(logResult("success", "pattern applied successfully"));
-  return success();
-};
-#else
-function_ref canApply = {};
-function_ref onFailure = {};
-function_ref onSuccess = {};
-#endif
+function_ref onFailure =
+[&](const Pattern &pattern) {
+  LLVM_DEBUG(logResult("failure", "pattern failed to match"));
+  if (config.listener)
+config.listener->notifyPatternEnd(pattern, failure());
+};
+function_ref onSuccess =
+[&](const Pattern &pattern) {
+  LLVM_DEBUG(logResult("success", "pattern applied successfully"));
+  if (config.listener)
+config.listener->notifyPatternEnd(pattern, success());
+  return success();
+};
+
+#ifdef NDEBUG
+// Optimization: PatternApplicator callbacks are not needed when running in
+// optimized mode and without a listener.
+if (!config.listener) {
+  canApply = nullptr;
+  onFailure = nullptr;
+  onSuccess = nullptr;
+}
+#endif // NDEBUG

joker-eph wrote:

Note: I didn't suggest changing this, what you had here was reasonable!

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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Mehdi Amini via llvm-branch-commits

https://github.com/joker-eph approved this pull request.


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


[llvm-branch-commits] [mlir] [mlir][IR] Add listener notifications for pattern begin/end (PR #84131)

2024-03-07 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer updated 
https://github.com/llvm/llvm-project/pull/84131

>From a65d640a0ca2c6810da0878ed42db39f27cebfe1 Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 8 Mar 2024 07:19:33 +
Subject: [PATCH] [mlir][IR] Add listener notifications for pattern begin/end

---
 mlir/include/mlir/IR/PatternMatch.h   | 30 ++---
 .../Transforms/Utils/DialectConversion.cpp| 29 +++-
 .../Utils/GreedyPatternRewriteDriver.cpp  | 33 +--
 3 files changed, 69 insertions(+), 23 deletions(-)

diff --git a/mlir/include/mlir/IR/PatternMatch.h 
b/mlir/include/mlir/IR/PatternMatch.h
index e3500b3f9446d8..49544c42790d4d 100644
--- a/mlir/include/mlir/IR/PatternMatch.h
+++ b/mlir/include/mlir/IR/PatternMatch.h
@@ -432,11 +432,22 @@ class RewriterBase : public OpBuilder {
 /// Note: This notification is not triggered when unlinking an operation.
 virtual void notifyOperationErased(Operation *op) {}
 
-/// Notify the listener that the pattern failed to match the given
-/// operation, and provide a callback to populate a diagnostic with the
-/// reason why the failure occurred. This method allows for derived
-/// listeners to optionally hook into the reason why a rewrite failed, and
-/// display it to users.
+/// Notify the listener that the specified pattern is about to be applied
+/// at the specified root operation.
+virtual void notifyPatternBegin(const Pattern &pattern, Operation *op) {}
+
+/// Notify the listener that a pattern application finished with the
+/// specified status. "success" indicates that the pattern was applied
+/// successfully. "failure" indicates that the pattern could not be
+/// applied. The pattern may have communicated the reason for the failure
+/// with `notifyMatchFailure`.
+virtual void notifyPatternEnd(const Pattern &pattern,
+  LogicalResult status) {}
+
+/// Notify the listener that the pattern failed to match, and provide a
+/// callback to populate a diagnostic with the reason why the failure
+/// occurred. This method allows for derived listeners to optionally hook
+/// into the reason why a rewrite failed, and display it to users.
 virtual void
 notifyMatchFailure(Location loc,
function_ref reasonCallback) {}
@@ -478,6 +489,15 @@ class RewriterBase : public OpBuilder {
   if (auto *rewriteListener = dyn_cast(listener))
 rewriteListener->notifyOperationErased(op);
 }
+void notifyPatternBegin(const Pattern &pattern, Operation *op) override {
+  if (auto *rewriteListener = dyn_cast(listener))
+rewriteListener->notifyPatternBegin(pattern, op);
+}
+void notifyPatternEnd(const Pattern &pattern,
+  LogicalResult status) override {
+  if (auto *rewriteListener = dyn_cast(listener))
+rewriteListener->notifyPatternEnd(pattern, status);
+}
 void notifyMatchFailure(
 Location loc,
 function_ref reasonCallback) override {
diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index c1a261eab8487d..cd49bd121a62e5 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -1856,7 +1856,8 @@ class OperationLegalizer {
   using LegalizationAction = ConversionTarget::LegalizationAction;
 
   OperationLegalizer(const ConversionTarget &targetInfo,
- const FrozenRewritePatternSet &patterns);
+ const FrozenRewritePatternSet &patterns,
+ const ConversionConfig &config);
 
   /// Returns true if the given operation is known to be illegal on the target.
   bool isIllegal(Operation *op) const;
@@ -1948,12 +1949,16 @@ class OperationLegalizer {
 
   /// The pattern applicator to use for conversions.
   PatternApplicator applicator;
+
+  /// Dialect conversion configuration.
+  const ConversionConfig &config;
 };
 } // namespace
 
 OperationLegalizer::OperationLegalizer(const ConversionTarget &targetInfo,
-   const FrozenRewritePatternSet &patterns)
-: target(targetInfo), applicator(patterns) {
+   const FrozenRewritePatternSet &patterns,
+   const ConversionConfig &config)
+: target(targetInfo), applicator(patterns), config(config) {
   // The set of patterns that can be applied to illegal operations to transform
   // them into legal ones.
   DenseMap legalizerPatterns;
@@ -2098,7 +2103,10 @@ OperationLegalizer::legalizeWithPattern(Operation *op,
 
   // Functor that returns if the given pattern may be applied.
   auto canApply = [&](const Pattern &pattern) {
-return canApplyPattern(op, pattern, rewriter);
+bool canApply = canApplyPattern(op, pattern, rewriter);
+if (canApply && config.