Bug type: crash
Component: SLPVectorizer
Bug location: llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp: BoUpSLP::vectorizeTree
Issue title: [SLPVectorizer] Assertion `(I->use_empty() || all_of(I->uses(), [&](Use &U) { return isDeleted( cast<Instruction>(U.getUser())); })) && "trying to erase instruction with users."' failed.
Labels: llvm:SLPVectorizer
crash
Reported by: ewlu

Testcase:
```llvm ir
target datalayout = "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128"
target triple = "riscv64-unknown-linux-gnu"

@i = internal global i32 47741
@n = external global [0 x i64]

define void @init() {
entry:
  store <4 x i64> splat (i64 1), ptr @n, align 32
  ret void
}

define i32 @main(ptr %a) #0 {
entry:
  tail call void @init()
  %0 = load i32, ptr @i, align 4
  %conv3.i = zext i32 %0 to i64
  %sub.i = add i64 %conv3.i, -47731
  br label %for.body.i

for.cond.for.cond.cleanup_crit_edge.i:            ; preds = %for.body.i
  store i32 %conv507173.i, ptr %a, align 4
  ret i32 0

for.body.i:                                       ; preds = %for.body.i, %entry
  %conv74.i = phi i64 [ %conv.i, %for.body.i ], [ 0, %entry ]
  %conv507173.i = phi i32 [ %conv50.i, %for.body.i ], [ 1, %entry ]
  %arrayidx12.i = getelementptr i64, ptr @n, i64 %conv74.i
  %1 = load i64, ptr %arrayidx12.i, align 8
  %conv13.i = trunc i64 %1 to i32
  %cond.i = tail call i32 @llvm.smin.i32(i32 %conv13.i, i32 1)
  %conv40.i = sext i32 %cond.i to i64
  %cond47.i = tail call i64 @llvm.umin.i64(i64 %conv40.i, i64 17179869184)
  %2 = trunc i64 %cond47.i to i32
  %conv50.i = sub i32 %conv507173.i, %2
  %add.i = shl i64 %conv74.i, 32
  %sext.i = add i64 %add.i, 17179869184
  %conv.i = ashr i64 %sext.i, 32
  %cmp.i = icmp slt i64 %conv74.i, %sub.i
  br i1 %cmp.i, label %for.body.i, label %for.cond.for.cond.cleanup_crit_edge.i
}

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i32 @llvm.smin.i32(i32, i32) #1

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i64 @llvm.umin.i64(i64, i64) #1

attributes #0 = { "target-features"="+v" }
attributes #1 = { nocallback nofree nosync nounwind speculatable willreturn memory(none) }
```

Commands/backtrace:
```
$ /scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt "--passes=lto<O2>" reduced.ll
WARNING: You're attempting to print out a bitcode file.
This is inadvisable as it may cause display problems. If
you REALLY want to taste LLVM bitcode first-hand, you
can force output with the `-f' option.

opt: /scratch/ewlu/daily-upstream-build/llvm/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp:3475: void llvm::slpvectorizer::BoUpSLP::removeInstructionsAndOperands(llvm::ArrayRef<BlockT*>, llvm::ArrayRef<std::tuple<llvm::Value*, unsigned int, bool> >) [with T = llvm::Instruction]: Assertion `(I->use_empty() || all_of(I->uses(), [&](Use &U) { return isDeleted( cast<Instruction>(U.getUser())); })) && "trying to erase instruction with users."' failed.
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace.
Stack dump:
0.      Program arguments: /scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt --passes=lto<O2> reduced.ll
1.      Running pass "function<eager-inv>(loop-mssa(licm<allowspeculation>),gvn<>,memcpyopt,dse,move-auto-init,mldst-motion<no-split-footer-bb>,loop(indvars,loop-deletion,loop-unroll-full),loop-distribute,loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,infer-alignment,loop-unroll<O2>,transform-warning,sroa<preserve-cfg>,instcombine<max-iterations=1;no-verify-fixpoint>,simplifycfg<bonus-inst-threshold=1;forward-switch-cond;switch-range-to-icmp;switch-to-lookup;no-keep-loops;hoist-common-insts;no-hoist-loads-stores-with-cond-faulting;sink-common-insts;speculate-blocks;simplify-cond-branch;no-speculate-unpredictables>,sccp,instcombine<max-iterations=1;no-verify-fixpoint>,bdce,slp-vectorizer,vector-combine,infer-alignment,instcombine<max-iterations=1;no-verify-fixpoint>,loop-mssa(licm<allowspeculation>),alignment-from-assumptions,jump-threading)" on module "reduced.ll"
2.      Running pass "slp-vectorizer" on function "main"
 #0 0x000063d0f06b35a2 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x33c25a2)
 #1 0x000063d0f06b029f llvm::sys::RunSignalHandlers() (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x33bf29f)
 #2 0x000063d0f06b03ec SignalHandler(int, siginfo_t*, void*) Signals.cpp:0:0
 #3 0x00007700fb245330 (/lib/x86_64-linux-gnu/libc.so.6+0x45330)
 #4 0x00007700fb29eb2c __pthread_kill_implementation ./nptl/pthread_kill.c:44:76
 #5 0x00007700fb29eb2c __pthread_kill_internal ./nptl/pthread_kill.c:78:10
 #6 0x00007700fb29eb2c pthread_kill ./nptl/pthread_kill.c:89:10
 #7 0x00007700fb24527e raise ./signal/../sysdeps/posix/raise.c:27:6
 #8 0x00007700fb2288ff abort ./stdlib/abort.c:81:7
 #9 0x00007700fb22881b _nl_load_domain ./intl/loadmsgcat.c:1177:9
#10 0x00007700fb23b517 (/lib/x86_64-linux-gnu/libc.so.6+0x3b517)
#11 0x000063d0ee3b4201 void llvm::slpvectorizer::BoUpSLP::removeInstructionsAndOperands<llvm::Instruction>(llvm::ArrayRef<llvm::Instruction*>, llvm::ArrayRef<std::tuple<llvm::Value*, unsigned int, bool>>) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x10c3201)
#12 0x000063d0ee410617 llvm::slpvectorizer::BoUpSLP::vectorizeTree(llvm::SmallDenseSet<llvm::Value*, 4u, llvm::DenseMapInfo<llvm::Value*, void>> const&, llvm::Instruction*, llvm::ArrayRef<std::tuple<llvm::Value*, unsigned int, bool>>) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x111f617)
#13 0x000063d0ee41dcc4 (anonymous namespace)::HorizontalReduction::tryToReduce(llvm::slpvectorizer::BoUpSLP&, llvm::DataLayout const&, llvm::TargetTransformInfo*, llvm::TargetLibraryInfo const&, llvm::AssumptionCache*) SLPVectorizer.cpp:0:0
#14 0x000063d0ee42222d llvm::SLPVectorizerPass::tryToVectorize(llvm::Instruction*, llvm::slpvectorizer::BoUpSLP&)::'lambda'(llvm::Instruction*, llvm::ArrayRef<llvm::Value*>)::operator()(llvm::Instruction*, llvm::ArrayRef<llvm::Value*>) const (.constprop.0) SLPVectorizer.cpp:0:0
#15 0x000063d0ee426296 llvm::SLPVectorizerPass::tryToVectorize(llvm::Instruction*, llvm::slpvectorizer::BoUpSLP&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x1135296)
#16 0x000063d0ee4264e8 llvm::SLPVectorizerPass::tryToVectorize(llvm::ArrayRef<llvm::WeakTrackingVH>, llvm::slpvectorizer::BoUpSLP&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x11354e8)
#17 0x000063d0ee426bb6 llvm::SLPVectorizerPass::vectorizeRootInstruction(llvm::PHINode*, llvm::Instruction*, llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x1135bb6)
#18 0x000063d0ee42b040 llvm::SLPVectorizerPass::vectorizeChainsInBlock(llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x113a040)
#19 0x000063d0ee433648 llvm::SLPVectorizerPass::runImpl(llvm::Function&, llvm::ScalarEvolution*, llvm::TargetTransformInfo*, llvm::TargetLibraryInfo*, llvm::AAResults*, llvm::LoopInfo*, llvm::DominatorTree*, llvm::AssumptionCache*, llvm::DemandedBits*, llvm::OptimizationRemarkEmitter*) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x1142648)
#20 0x000063d0ee434326 llvm::SLPVectorizerPass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/scratch/ewlu/daily-upstream-buil
d/build-gcv/build-llvm-linux/bin/opt+0x1143326)
#21 0x000063d0edb8f905 llvm::detail::PassModel<llvm::Function, llvm::SLPVectorizerPass, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x89e905)
#22 0x000063d0f0495b75 llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x31a4b75)
#23 0x000063d0edb91705 llvm::detail::PassModel<llvm::Function, llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x8a0705)
#24 0x000063d0f0494881 llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x31a3881)
#25 0x000063d0ed823205 llvm::detail::PassModel<llvm::Module, llvm::ModuleToFunctionPassAdaptor, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x532205)
#26 0x000063d0f04928dd llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x31a18dd)
#27 0x000063d0ed82f2f1 llvm::runPassPipeline(llvm::StringRef, llvm::Module&, llvm::TargetMachine*, llvm::TargetLibraryInfoImpl*, llvm::ToolOutputFile*, llvm::ToolOutputFile*, llvm::ToolOutputFile*, llvm::StringRef, llvm::ArrayRef<llvm::PassPlugin>, llvm::ArrayRef<std::function<void (llvm::PassBuilder&)>>, llvm::opt_tool::OutputKind, llvm::opt_tool::VerifierKind, bool, bool, bool, bool, bool, bool, bool, bool) (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x53e2f1)
#28 0x000063d0ed8213dd optMain (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x5303dd)
#29 0x00007700fb22a1ca __libc_start_call_main ./csu/../sysdeps/nptl/libc_start_call_main.h:74:3
#30 0x00007700fb22a28b call_init ./csu/../csu/libc-start.c:128:20
#31 0x00007700fb22a28b __libc_start_main ./csu/../csu/libc-start.c:347:5
#32 0x000063d0ed817325 _start (/scratch/ewlu/daily-upstream-build/build-gcv/build-llvm-linux/bin/opt+0x526325)
Aborted (core dumped)
```

Godbolt: https://godbolt.org/z/EnWsq6vsK

Found via fuzzer (C program before reduction)


Fix patch:
commit e5a4ea20c5b6b37f7fd944b5ef7395d0623d4bdb
Author: Alexey Bataev <a.bataev@outlook.com>
Date:   Sun Aug 31 08:48:34 2025 -0700

    [SLP]Do not remove reduced value, if it is a copyable
    
    If the value is checked for the reduction and it is a copyable element
    in a root node, it should not be deleted, since it may still be used
    after vectorization.
    
    Fixes #155512

diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index 33418d86d51d..ebdd1c81da69 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -20529,7 +20529,9 @@ Value *BoUpSLP::vectorizeTree(
           !(GatheredLoadsEntriesFirst.has_value() &&
             IE->Idx >= *GatheredLoadsEntriesFirst &&
             VectorizableTree.front()->isGather() &&
-            is_contained(VectorizableTree.front()->Scalars, I)))
+            is_contained(VectorizableTree.front()->Scalars, I)) &&
+          !(!VectorizableTree.front()->isGather() &&
+            VectorizableTree.front()->isCopyableElement(I)))
         continue;
       SmallVector<SelectInst *> LogicalOpSelects;
       I->replaceUsesWithIf(PoisonValue::get(I->getType()), [&](Use &U) {


Regression tests:
file: llvm/test/Transforms/SLPVectorizer/RISCV/reduced-copyable-element.ll
commands: opt -S --passes=slp-vectorizer -mtriple=riscv64-unknown-linux-gnu -mattr=+v < %s
tests: test_name: <module>
test_body: 
@n = external global [0 x i64]

define i32 @main() {
;
entry:
  %0 = load i64, ptr getelementptr (i8, ptr @n, i64 32), align 8
  %conv13.i.1 = trunc i64 %0 to i32
  %cond.i.1 = tail call i32 @llvm.smin.i32(i32 %conv13.i.1, i32 0)
  %conv40.i.1 = sext i32 %cond.i.1 to i64
  %cond47.i.1 = tail call i64 @llvm.umin.i64(i64 %conv40.i.1, i64 17179869184)
  %1 = trunc i64 %cond47.i.1 to i32
  %2 = add i32 %1, 1
  %3 = load i64, ptr @n, align 8
  %conv13.i.2 = trunc i64 %3 to i32
  %cond.i.2 = tail call i32 @llvm.smin.i32(i32 %conv13.i.2, i32 0)
  %conv40.i.2 = sext i32 %cond.i.2 to i64
  %cond47.i.2 = tail call i64 @llvm.umin.i64(i64 %conv40.i.2, i64 17179869184)
  %4 = trunc i64 %cond47.i.2 to i32
  %5 = or i32 %2, %4
  ret i32 %5
}

declare i32 @llvm.smin.i32(i32, i32)
declare i64 @llvm.umin.i64(i64, i64)