Bug type: crash
Component: SLPVectorizer
Bug location: llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp: BoUpSLP::getEntryCost
Issue title: clang crashes on valid code at -O{2,3} on x86_64-linux-gnu: Assertion `valid() && "InstructionsState is invalid."' failed
Labels: llvm:SLPVectorizer
crash
Reported by: zhendongsu

It appears to be a recent regression as it doesn't reproduce with 19.1.0 and earlier.

Compiler Explorer: https://godbolt.org/z/8KTq9hGv9

```
[516] % clangtk -v
clang version 21.0.0git (https://github.com/llvm/llvm-project.git d0edd931bcc328b9502289d346f2b2219341f853)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /local/suz-local/software/local/clang-trunk/bin
Build config: +assertions
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/10
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/11
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Selected GCC installation: /usr/lib/gcc/x86_64-linux-gnu/11
Candidate multilib: .;@m64
Selected multilib: .;@m64
[517] % 
[517] % clangtk -O2 -w small.c
clang-21: /local/suz-local/software/clangbuild/llvm-project/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp:821: llvm::Instruction* {anonymous}::InstructionsState::getMainOp() const: Assertion `valid() && "InstructionsState is invalid."' failed.
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace, preprocessed source, and associated run script.
Stack dump:
0.	Program arguments: /local/suz-local/software/local/clang-trunk/bin/clang-21 -cc1 -triple x86_64-unknown-linux-gnu -emit-obj -dumpdir a- -disable-free -clear-ast-before-backend -main-file-name small.c -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/local/suz-local/software/emitesting/bugs/20250227-clangtk-m64-O3-build-235136/delta -fcoverage-compilation-dir=/local/suz-local/software/emitesting/bugs/20250227-clangtk-m64-O3-build-235136/delta -resource-dir /local/suz-local/software/local/clang-trunk/lib/clang/21 -I /usr/local/include -I /local/suz-local/software/local/include -internal-isystem /local/suz-local/software/local/clang-trunk/lib/clang/21/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -w -ferror-limit 19 -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fcolor-diagnostics -vectorize-loops -vectorize-slp -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/small-933a0f.o -x c small.c
1.	<eof> parser at end of file
2.	Optimizer
3.	Running pass "function<eager-inv>(float2int,lower-constant-intrinsics,loop(loop-rotate<header-duplication;no-prepare-for-lto>,loop-deletion),loop-distribute,inject-tli-mappings,loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,infer-alignment,loop-load-elim,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>,slp-vectorizer,vector-combine,instcombine<max-iterations=1;no-verify-fixpoint>,loop-unroll<O2>,transform-warning,sroa<preserve-cfg>,infer-alignment,instcombine<max-iterations=1;no-verify-fixpoint>,loop-mssa(licm<allowspeculation>),alignment-from-assumptions,loop-sink,instsimplify,div-rem-pairs,tailcallelim,simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;hoist-loads-stores-with-cond-faulting;no-sink-common-insts;speculate-blocks;simplify-cond-branch;speculate-unpredictables>)" on module "small.c"
4.	Running pass "slp-vectorizer" on function "main"
 #0 0x00005597e9b142df llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x455e2df)
 #1 0x00005597e9b11ab4 SignalHandler(int, siginfo_t*, void*) Signals.cpp:0:0
 #2 0x00007fa06c8aa420 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x14420)
 #3 0x00007fa06c2e100b raise /build/glibc-LcI20x/glibc-2.31/signal/../sysdeps/unix/sysv/linux/raise.c:51:1
 #4 0x00007fa06c2c0859 abort /build/glibc-LcI20x/glibc-2.31/stdlib/abort.c:81:7
 #5 0x00007fa06c2c0729 get_sysdep_segment_value /build/glibc-LcI20x/glibc-2.31/intl/loadmsgcat.c:509:8
 #6 0x00007fa06c2c0729 _nl_load_domain /build/glibc-LcI20x/glibc-2.31/intl/loadmsgcat.c:970:34
 #7 0x00007fa06c2d1fd6 (/lib/x86_64-linux-gnu/libc.so.6+0x33fd6)
 #8 0x00005597eb591745 (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x5fdb745)
 #9 0x00005597eb62a4e5 llvm::slpvectorizer::BoUpSLP::getEntryCost(llvm::slpvectorizer::BoUpSLP::TreeEntry const*, llvm::ArrayRef<llvm::Value*>, llvm::SmallPtrSetImpl<llvm::Value*>&)::'lambda0'(llvm::function_ref<llvm::InstructionCost (unsigned int)>, llvm::function_ref<llvm::InstructionCost (llvm::InstructionCost)>)::operator()(llvm::function_ref<llvm::InstructionCost (unsigned int)>, llvm::function_ref<llvm::InstructionCost (llvm::InstructionCost)>) const SLPVectorizer.cpp:0:0
#10 0x00005597eb633034 llvm::slpvectorizer::BoUpSLP::getEntryCost(llvm::slpvectorizer::BoUpSLP::TreeEntry const*, llvm::ArrayRef<llvm::Value*>, llvm::SmallPtrSetImpl<llvm::Value*>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x607d034)
#11 0x00005597eb668741 llvm::slpvectorizer::BoUpSLP::getTreeCost(llvm::ArrayRef<llvm::Value*>) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x60b2741)
#12 0x00005597eb672691 llvm::SLPVectorizerPass::tryToVectorizeList(llvm::ArrayRef<llvm::Value*>, llvm::slpvectorizer::BoUpSLP&, bool) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x60bc691)
#13 0x00005597eb676e5e bool llvm::SLPVectorizerPass::vectorizeCmpInsts<std::reverse_iterator<llvm::CmpInst* const*>>(llvm::iterator_range<std::reverse_iterator<llvm::CmpInst* const*>>, llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x60c0e5e)
#14 0x00005597eb6773db llvm::SLPVectorizerPass::vectorizeChainsInBlock(llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&)::'lambda3'(bool)::operator()(bool) const SLPVectorizer.cpp:0:0
#15 0x00005597eb67ac20 llvm::SLPVectorizerPass::vectorizeChainsInBlock(llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x60c4c20)
#16 0x00005597eb681396 llvm::SLPVectorizerPass::runImpl(llvm::Function&, llvm::ScalarEvolution*, llvm::TargetTransformInfo*, llvm::TargetLibraryInfo*, llvm::AAResults*, llvm::LoopInfo*, llvm::DominatorTree*, llvm::AssumptionCache*, llvm::DemandedBits*, llvm::OptimizationRemarkEmitter*) (.part.0) SLPVectorizer.cpp:0:0
#17 0x00005597eb681ef3 llvm::SLPVectorizerPass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x60cbef3)
#18 0x00005597eb104166 llvm::detail::PassModel<llvm::Function, llvm::SLPVectorizerPass, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x5b4e166)
#19 0x00005597e948caf9 llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x3ed6af9)
#20 0x00005597e6d6c406 llvm::detail::PassModel<llvm::Function, llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x17b6406)
#21 0x00005597e948b362 llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x3ed5362)
#22 0x00005597e6d6a4b6 llvm::detail::PassModel<llvm::Module, llvm::ModuleToFunctionPassAdaptor, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x17b44b6)
#23 0x00005597e948ad81 llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x3ed4d81)
#24 0x00005597e9ddb283 (anonymous namespace)::EmitAssemblyHelper::RunOptimizationPipeline(clang::BackendAction, std::unique_ptr<llvm::raw_pwrite_stream, std::default_delete<llvm::raw_pwrite_stream>>&, std::unique_ptr<llvm::ToolOutputFile, std::default_delete<llvm::ToolOutputFile>>&, clang::BackendConsumer*) BackendUtil.cpp:0:0
#25 0x00005597e9ddf573 clang::emitBackendOutput(clang::CompilerInstance&, clang::CodeGenOptions&, llvm::StringRef, llvm::Module*, clang::BackendAction, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>, std::unique_ptr<llvm::raw_pwrite_stream, std::default_delete<llvm::raw_pwrite_stream>>, clang::BackendConsumer*) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x4829573)
#26 0x00005597ea51bba0 clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x4f65ba0)
#27 0x00005597ebe39acc clang::ParseAST(clang::Sema&, bool, bool) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x6883acc)
#28 0x00005597ea51bfc8 clang::CodeGenAction::ExecuteAction() (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x4f65fc8)
#29 0x00005597ea7f2779 clang::FrontendAction::Execute() (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x523c779)
#30 0x00005597ea77325e clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x51bd25e)
#31 0x00005597ea8e7626 clang::ExecuteCompilerInvocation(clang::CompilerInstance*) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x5331626)
#32 0x00005597e68fefb7 cc1_main(llvm::ArrayRef<char const*>, char const*, void*) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x1348fb7)
#33 0x00005597e68f66ea ExecuteCC1Tool(llvm::SmallVectorImpl<char const*>&, llvm::ToolContext const&) driver.cpp:0:0
#34 0x00005597e68fa97a clang_main(int, char**, llvm::ToolContext const&) (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x134497a)
#35 0x00005597e67edccb main (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x1237ccb)
#36 0x00007fa06c2c2083 __libc_start_main /build/glibc-LcI20x/glibc-2.31/csu/../csu/libc-start.c:342:3
#37 0x00005597e68f617e _start (/local/suz-local/software/local/clang-trunk/bin/clang-21+0x134017e)
clangtk: error: unable to execute command: Aborted
clangtk: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 21.0.0git (https://github.com/llvm/llvm-project.git d0edd931bcc328b9502289d346f2b2219341f853)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /local/suz-local/software/local/clang-trunk/bin
Build config: +assertions
clangtk: note: diagnostic msg: 
********************

PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clangtk: note: diagnostic msg: /tmp/small-fd80bc.c
clangtk: note: diagnostic msg: /tmp/small-fd80bc.sh
clangtk: note: diagnostic msg: 

********************
[518] % 
[518] % cat small.c
int a[1], g;
char b, c;
volatile int d;
long e, f;
long h(long i) { return i > 1 ? i : i << 1; }
int main() {
  if (g)
    while (1) {
      b = 0;
      for (; b < 10; b++) {
        e = c & b ? 0 : c - b;
        f = h(e);
        g = (a != 0) % (unsigned)f;
        if (g)
          d;
      }
    }
  return 0;
}
```




Fix patch:
commit a36a67c79afaa1fdd0dbe0440ec852fd4eb3a532
Author: Alexey Bataev <a.bataev@outlook.com>
Date:   Fri Feb 28 13:15:46 2025 -0800

    [SLP]Fix the analysis of the user buildvector nodes for minbitwidth
    
    If the user node is a buildvector/gather node and it has no internal
    instructions state, need to check properly for this state and check the
    type of the node itself, not its operands.
    
    Fixes #129242

diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index 4a68e0ee5989..4f3fd6d53909 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -11425,11 +11425,14 @@ BoUpSLP::getEntryCost(const TreeEntry *E, ArrayRef<Value *> VectorizedVals,
             E->Idx != 0 &&
             (E->getOpcode() != Instruction::Load || E->UserTreeIndex)) {
           const EdgeInfo &EI = E->UserTreeIndex;
-          if (EI.UserTE->getOpcode() != Instruction::Select ||
+          if (!EI.UserTE->hasState() ||
+              EI.UserTE->getOpcode() != Instruction::Select ||
               EI.EdgeIdx != 0) {
             auto UserBWIt = MinBWs.find(EI.UserTE);
             Type *UserScalarTy =
-                EI.UserTE->getOperand(EI.EdgeIdx).front()->getType();
+                EI.UserTE->isGather()
+                    ? EI.UserTE->Scalars.front()->getType()
+                    : EI.UserTE->getOperand(EI.EdgeIdx).front()->getType();
             if (UserBWIt != MinBWs.end())
               UserScalarTy = IntegerType::get(ScalarTy->getContext(),
                                               UserBWIt->second.first);


Regression tests:
file: llvm/test/Transforms/SLPVectorizer/X86/user-buildvector-with-minbiwidth.ll
commands: opt -S --passes=slp-vectorizer -mtriple=x86_64-unknown-linux-gnu < %s
tests: test_name: <module>
test_body: 
define i32 @test(i8 %0, i32 %conv2, i1 %cmp.i, i64 %shl.i) {
;
entry:
  %conv21 = sext i8 %0 to i32
  %conv7 = zext i32 %conv2 to i64
  %cond.i = shl i64 %conv7, %shl.i
  %1 = and i64 %cond.i, 4294967295
  %.not = icmp eq i64 %1, 1
  %conv7.1 = zext i32 %conv2 to i64
  %cond.i.1 = shl i64 %conv7.1, %shl.i
  %2 = and i64 %cond.i.1, 4294967295
  %.not.1 = icmp eq i64 %2, 1
  %sub.2 = or i32 %conv21, 1
  %cond.2 = select i1 %cmp.i, i32 %sub.2, i32 0
  %conv7.2 = zext i32 %cond.2 to i64
  %cmp.i.2 = icmp slt i32 %cond.2, 1
  %shl.i.2 = zext i1 %cmp.i.2 to i64
  %cond.i.2 = shl i64 %conv7.2, %shl.i.2
  %3 = and i64 %cond.i.2, 4294967295
  %.not.2 = icmp eq i64 %3, 1
  %sub.3 = or i32 %conv21, 1
  %cond.3 = select i1 %cmp.i, i32 %sub.3, i32 0
  %conv7.3 = zext i32 %cond.3 to i64
  %cmp.i.3 = icmp slt i32 %cond.3, 1
  %shl.i.3 = zext i1 %cmp.i.3 to i64
  %cond.i.3 = shl i64 %conv7.3, %shl.i.3
  %4 = and i64 %cond.i.3, 4294967295
  %.not.3 = icmp eq i64 %4, 1
  %sub.4 = or i32 %conv21, 1
  %cond.4 = select i1 %cmp.i, i32 %sub.4, i32 0
  %conv7.4 = zext i32 %cond.4 to i64
  %cmp.i.4 = icmp slt i32 %cond.4, 1
  %shl.i.4 = zext i1 %cmp.i.4 to i64
  %cond.i.4 = shl i64 %conv7.4, %shl.i.4
  %5 = and i64 %cond.i.4, 4294967295
  %.not.4 = icmp eq i64 %5, 1
  %sub.5 = or i32 %conv21, 1
  %cond.5 = select i1 %cmp.i, i32 %sub.5, i32 0
  %conv7.5 = zext i32 %cond.5 to i64
  %cmp.i.5 = icmp slt i32 %cond.5, 1
  %shl.i.5 = zext i1 %cmp.i.5 to i64
  %cond.i.5 = shl i64 %conv7.5, %shl.i.5
  %6 = and i64 %cond.i.5, 4294967295
  %.not.5 = icmp eq i64 %6, 1
  %sub.6 = or i32 %conv21, 1
  %cond.6 = select i1 %cmp.i, i32 %sub.6, i32 0
  %conv7.6 = zext i32 %cond.6 to i64
  %cmp.i.6 = icmp slt i32 %cond.6, 1
  %shl.i.6 = zext i1 %cmp.i.6 to i64
  %cond.i.6 = shl i64 %conv7.6, %shl.i.6
  %7 = and i64 %cond.i.6, 4294967295
  %.not.6 = icmp eq i64 %7, 1
  %sub.7 = or i32 %conv21, 1
  %cond.7 = select i1 %cmp.i, i32 %sub.7, i32 0
  %conv7.7 = zext i32 %cond.7 to i64
  %cmp.i.7 = icmp slt i32 %cond.7, 1
  %shl.i.7 = zext i1 %cmp.i.7 to i64
  %cond.i.7 = shl i64 %conv7.7, %shl.i.7
  %8 = and i64 %cond.i.7, 4294967295
  %.not.7 = icmp eq i64 %8, 1
  %sub.8 = or i32 %conv21, 1
  %cond.8 = select i1 %cmp.i, i32 %sub.8, i32 0
  %conv7.8 = zext i32 %cond.8 to i64
  %cmp.i.8 = icmp slt i32 %cond.8, 1
  %shl.i.8 = zext i1 %cmp.i.8 to i64
  %cond.i.8 = shl i64 %conv7.8, %shl.i.8
  %9 = and i64 %cond.i.8, 4294967295
  %.not.8 = icmp eq i64 %9, 1
  %sub.9 = or i32 %conv21, 1
  %cond.9 = select i1 %cmp.i, i32 %sub.9, i32 0
  %conv7.9 = zext i32 %cond.9 to i64
  %cmp.i.9 = icmp slt i32 %cond.9, 1
  %shl.i.9 = zext i1 %cmp.i.9 to i64
  %cond.i.9 = shl i64 %conv7.9, %shl.i.9
  %10 = and i64 %cond.i.9, 4294967295
  %.not.9 = icmp eq i64 %10, 1
  br label %while.body

while.body:
  br i1 %.not, label %for.inc, label %if.then10

if.then10:
  br label %for.inc

for.inc:
  br i1 %.not.1, label %for.inc.1, label %if.then10.1

if.then10.1:
  br label %for.inc.1

for.inc.1:
  br i1 %.not.2, label %for.inc.2, label %if.then10.2

if.then10.2:
  br label %for.inc.2

for.inc.2:
  br i1 %.not.3, label %for.inc.3, label %if.then10.3

if.then10.3:
  br label %for.inc.3

for.inc.3:
  br i1 %.not.4, label %for.inc.4, label %if.then10.4

if.then10.4:
  br label %for.inc.4

for.inc.4:
  br i1 %.not.5, label %for.inc.5, label %if.then10.5

if.then10.5:
  br label %for.inc.5

for.inc.5:
  br i1 %.not.6, label %for.inc.6, label %if.then10.6

if.then10.6:
  br label %for.inc.6

for.inc.6:
  br i1 %.not.7, label %for.inc.7, label %if.then10.7

if.then10.7:
  br label %for.inc.7

for.inc.7:
  br i1 %.not.8, label %for.inc.8, label %if.then10.8

if.then10.8:
  br label %for.inc.8

for.inc.8:
  br i1 %.not.9, label %while.body, label %if.then10.9

if.then10.9:
  br label %while.body
}