Bug type: crash
Component: VectorCombine
Bug location: llvm/lib/Transforms/Vectorize/VectorCombine.cpp: VectorCombine::run
eraseInstruction
Issue title: [VectorCombine] SIGSEGV at -Os
Labels: crash-on-valid
generated by fuzzer
llvm::vectorcombine
Reported by: dtcxzyw

Crash reproducer: https://godbolt.org/z/nbdfPzcqK
```
; bin/opt -passes=vector-combine reduced.ll -S
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
target triple = "x86_64-unknown-linux-gnu"

define i32 @main() {
entry:
  br label %vector.ph

vector.ph:                                        ; preds = %vector.ph, %entry
  %and48698.lcssa704705.i.i.i = phi i32 [ 0, %entry ], [ %2, %vector.ph ]
  %0 = insertelement <4 x i32> zeroinitializer, i32 %and48698.lcssa704705.i.i.i, i64 0
  %1 = and <4 x i32> %0, zeroinitializer
  %2 = call i32 @llvm.vector.reduce.and.v4i32(<4 x i32> zeroinitializer)
  br label %vector.ph
}
```
```
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace.
Stack dump:
0.	Program arguments: /opt/compiler-explorer/clang-trunk/bin/opt -o /app/output.s -S -passes=vector-combine <source>
1.	Running pass "function(vector-combine)" on module "<source>"
2.	Running pass "vector-combine" on function "main"
 #0 0x00000000052bda88 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/opt/compiler-explorer/clang-trunk/bin/opt+0x52bda88)
 #1 0x00000000052bac54 SignalHandler(int, siginfo_t*, void*) Signals.cpp:0:0
 #2 0x0000766a19042520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #3 0x00000000033c6e33 llvm::VectorCombinePass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-trunk/bin/opt+0x33c6e33)
 #4 0x0000000002bfe56e llvm::detail::PassModel<llvm::Function, llvm::VectorCombinePass, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-trunk/bin/opt+0x2bfe56e)
 #5 0x00000000050aacd7 llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-trunk/bin/opt+0x50aacd7)
 #6 0x0000000000e5e00e llvm::detail::PassModel<llvm::Function, llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-trunk/bin/opt+0xe5e00e)
 #7 0x00000000050ab838 llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/opt/compiler-explorer/clang-trunk/bin/opt+0x50ab838)
 #8 0x0000000000980cee llvm::detail::PassModel<llvm::Module, llvm::ModuleToFunctionPassAdaptor, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/opt/compiler-explorer/clang-trunk/bin/opt+0x980cee)
 #9 0x00000000050ae0c7 llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/opt/compiler-explorer/clang-trunk/bin/opt+0x50ae0c7)
#10 0x000000000098a83a 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) (/opt/compiler-explorer/clang-trunk/bin/opt+0x98a83a)
#11 0x000000000097eef3 optMain (/opt/compiler-explorer/clang-trunk/bin/opt+0x97eef3)
#12 0x0000766a19029d90 (/lib/x86_64-linux-gnu/libc.so.6+0x29d90)
#13 0x0000766a19029e40 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x29e40)
#14 0x0000000000976f05 _start (/opt/compiler-explorer/clang-trunk/bin/opt+0x976f05)
Program terminated with signal: SIGSEGV
Compiler returned: 139
```



Fix patch:
commit db6a8f10096762d292f135a7b16ac23b39553380
Author: Yingwei Zheng <dtcxzyw2333@gmail.com>
Date:   Tue Aug 26 00:22:53 2025 +0800

    [VectorCombine] Avoid crash when the next node is deleted. (#155115)
    
    `RecursivelyDeleteTriviallyDeadInstructions` is introduced by
    https://github.com/llvm/llvm-project/pull/149047 to immediately drop
    dead instructions. However, it may invalidate the next iterator in
    `make_early_inc_range` in some edge cases, which leads to a crash. This
    patch manually maintains the next iterator and updates it when the next
    instruction is about to be deleted.
    
    Closes https://github.com/llvm/llvm-project/issues/155110.

diff --git a/llvm/lib/Transforms/Vectorize/VectorCombine.cpp b/llvm/lib/Transforms/Vectorize/VectorCombine.cpp
index 092a3a87954f..56a08b843871 100644
--- a/llvm/lib/Transforms/Vectorize/VectorCombine.cpp
+++ b/llvm/lib/Transforms/Vectorize/VectorCombine.cpp
@@ -99,6 +99,10 @@ private:
 
   InstructionWorklist Worklist;
 
+  /// Next instruction to iterate. It will be updated when it is erased by
+  /// RecursivelyDeleteTriviallyDeadInstructions.
+  Instruction *NextInst;
+
   // TODO: Direct calls from the top-level "run" loop use a plain "Instruction"
   //       parameter. That should be updated to specific sub-classes because the
   //       run loop was changed to dispatch on opcode.
@@ -173,9 +177,11 @@ private:
         if (auto *OpI = dyn_cast<Instruction>(Op)) {
           if (RecursivelyDeleteTriviallyDeadInstructions(
                   OpI, nullptr, nullptr, [this](Value *V) {
-                    if (auto I = dyn_cast<Instruction>(V)) {
+                    if (auto *I = dyn_cast<Instruction>(V)) {
                       LLVM_DEBUG(dbgs() << "VC: Erased: " << *I << '\n');
                       Worklist.remove(I);
+                      if (I == NextInst)
+                        NextInst = NextInst->getNextNode();
                     }
                   }))
             continue;
@@ -4519,13 +4525,21 @@ bool VectorCombine::run() {
     if (!DT.isReachableFromEntry(&BB))
       continue;
     // Use early increment range so that we can erase instructions in loop.
-    for (Instruction &I : make_early_inc_range(BB)) {
-      if (I.isDebugOrPseudoInst())
-        continue;
-      MadeChange |= FoldInst(I);
+    // make_early_inc_range is not applicable here, as the next iterator may
+    // be invalidated by RecursivelyDeleteTriviallyDeadInstructions.
+    // We manually maintain the next instruction and update it when it is about
+    // to be deleted.
+    Instruction *I = &BB.front();
+    while (I) {
+      NextInst = I->getNextNode();
+      if (!I->isDebugOrPseudoInst())
+        MadeChange |= FoldInst(*I);
+      I = NextInst;
     }
   }
 
+  NextInst = nullptr;
+
   while (!Worklist.isEmpty()) {
     Instruction *I = Worklist.removeOne();
     if (!I)


Regression tests:
file: llvm/test/Transforms/VectorCombine/X86/insert-binop-inseltpoison.ll
commands: opt < %s -passes=vector-combine -S -mtriple=x86_64-- -mattr=SSE2
opt < %s -passes=vector-combine -S -mtriple=x86_64-- -mattr=AVX2
tests: test_name: pr155110
test_body: define i32 @pr155110(i32 %x) {
entry:
  br label %vector.ph

vector.ph:                                        ; preds = %vector.ph, %entry
  %phi = phi i32 [ 0, %entry ], [ %reduce, %vector.ph ]
  %inselt = insertelement <4 x i32> poison, i32 %phi, i64 0
  %and = and <4 x i32> %inselt, zeroinitializer
  %reduce = call i32 @llvm.vector.reduce.and.v4i32(<4 x i32> zeroinitializer)
  br label %vector.ph
}

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i32 @llvm.vector.reduce.and.v4i32(<4 x i32>) #0

attributes #0 = { nocallback nofree nosync nounwind speculatable willreturn memory(none) }

test_name: ins3_ins3_fdiv
test_body: declare void @usef(<4 x float>)

define <4 x float> @ins3_ins3_fdiv(float %x, float %y) {
  %i0 = insertelement <4 x float> poison, float %x, i32 3
  call void @usef(<4 x float> %i0)
  %i1 = insertelement <4 x float> poison, float %y, i32 3
  call void @usef(<4 x float> %i1)
  %r = fdiv <4 x float> %i0, %i1
  ret <4 x float> %r
}