Bug type: crash
Component: SLPVectorizer
Bug location: llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp: BoUpSLP::collectValuesToDemote
Issue title: clang crashes on valid code at -O{s,2,3} on x86_64-linux-gnu: Assertion `isa<To>(Val) && "cast<Ty>() argument of incompatible type!"' 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/cb67rEodY

```
[516] % clangtk -v
clang version 20.0.0git (https://github.com/llvm/llvm-project.git 5208bc3694473f9378fc0d98eeee63e5ad5c5f04)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /local/home/suz/suz-local/software/local/clang-trunk/bin
Build config: +assertions
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/11
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/12
Selected GCC installation: /usr/lib/gcc/x86_64-linux-gnu/12
Candidate multilib: .;@m64
Selected multilib: .;@m64
Found CUDA installation: /usr/local/cuda, version 11.8
[517] % 
[517] % clangtk -O2 -w small.c
clang-20: /local/suz-local/software/clangbuild/llvm-project/llvm/include/llvm/Support/Casting.h:578: decltype(auto) llvm::cast(From*) [with To = llvm::Instruction; From = llvm::Value]: Assertion `isa<To>(Val) && "cast<Ty>() argument of incompatible type!"' 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/home/suz/suz-local/software/local/clang-trunk/bin/clang-20 -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/20241125-clangtk-m64-O3-fpointer-tbaa-build-014338/delta -fcoverage-compilation-dir=/local/suz-local/software/emitesting/bugs/20241125-clangtk-m64-O3-fpointer-tbaa-build-014338/delta -resource-dir /local/home/suz/suz-local/software/local/clang-trunk/lib/clang/20 -I /usr/local/include -I /local/suz-local/software/local/include -internal-isystem /local/home/suz/suz-local/software/local/clang-trunk/lib/clang/20/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/12/../../../../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-99895f.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 0x0000562e34749b50 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x455db50)
 #1 0x0000562e34746f5f llvm::sys::RunSignalHandlers() (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x455af5f)
 #2 0x0000562e347470b5 SignalHandler(int) Signals.cpp:0:0
 #3 0x00007f99ac5bf520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #4 0x00007f99ac613a7c pthread_kill (/lib/x86_64-linux-gnu/libc.so.6+0x96a7c)
 #5 0x00007f99ac5bf476 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x42476)
 #6 0x00007f99ac5a57f3 abort (/lib/x86_64-linux-gnu/libc.so.6+0x287f3)
 #7 0x00007f99ac5a571b (/lib/x86_64-linux-gnu/libc.so.6+0x2871b)
 #8 0x00007f99ac5b6e96 (/lib/x86_64-linux-gnu/libc.so.6+0x39e96)
 #9 0x0000562e31712868 (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x1526868)
#10 0x0000562e3616cf4e llvm::slpvectorizer::BoUpSLP::collectValuesToDemote(llvm::slpvectorizer::BoUpSLP::TreeEntry const&, bool, unsigned int&, llvm::SmallVectorImpl<unsigned int>&, llvm::DenseSet<llvm::slpvectorizer::BoUpSLP::TreeEntry const*, llvm::DenseMapInfo<llvm::slpvectorizer::BoUpSLP::TreeEntry const*, void>>&, unsigned int&, bool&, bool) const::'lambda9'(unsigned int, unsigned int)::operator()(unsigned int, unsigned int) const::'lambda'(llvm::Value*)::operator()(llvm::Value*) const SLPVectorizer.cpp:0:0
#11 0x0000562e3616d208 bool llvm::function_ref<bool (unsigned int, unsigned int)>::callback_fn<llvm::slpvectorizer::BoUpSLP::collectValuesToDemote(llvm::slpvectorizer::BoUpSLP::TreeEntry const&, bool, unsigned int&, llvm::SmallVectorImpl<unsigned int>&, llvm::DenseSet<llvm::slpvectorizer::BoUpSLP::TreeEntry const*, llvm::DenseMapInfo<llvm::slpvectorizer::BoUpSLP::TreeEntry const*, void>>&, unsigned int&, bool&, bool) const::'lambda9'(unsigned int, unsigned int)>(long, unsigned int, unsigned int) SLPVectorizer.cpp:0:0
#12 0x0000562e361c72e9 llvm::slpvectorizer::BoUpSLP::collectValuesToDemote(llvm::slpvectorizer::BoUpSLP::TreeEntry const&, bool, unsigned int&, llvm::SmallVectorImpl<unsigned int>&, llvm::DenseSet<llvm::slpvectorizer::BoUpSLP::TreeEntry const*, llvm::DenseMapInfo<llvm::slpvectorizer::BoUpSLP::TreeEntry const*, void>>&, unsigned int&, bool&, bool) const::'lambda6'(unsigned int&, llvm::ArrayRef<llvm::slpvectorizer::BoUpSLP::TreeEntry const*>, llvm::function_ref<bool (unsigned int, unsigned int)>)::operator()(unsigned int&, llvm::ArrayRef<llvm::slpvectorizer::BoUpSLP::TreeEntry const*>, llvm::function_ref<bool (unsigned int, unsigned int)>) const SLPVectorizer.cpp:0:0
#13 0x0000562e361c6065 llvm::slpvectorizer::BoUpSLP::collectValuesToDemote(llvm::slpvectorizer::BoUpSLP::TreeEntry const&, bool, unsigned int&, llvm::SmallVectorImpl<unsigned int>&, llvm::DenseSet<llvm::slpvectorizer::BoUpSLP::TreeEntry const*, llvm::DenseMapInfo<llvm::slpvectorizer::BoUpSLP::TreeEntry const*, void>>&, unsigned int&, bool&, bool) const (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x5fda065)
#14 0x0000562e361c6d09 llvm::slpvectorizer::BoUpSLP::computeMinimumValueSizes()::'lambda0'(llvm::slpvectorizer::BoUpSLP::TreeEntry const&, bool, bool, unsigned int, unsigned int, bool, bool)::operator()(llvm::slpvectorizer::BoUpSLP::TreeEntry const&, bool, bool, unsigned int, unsigned int, bool, bool) const SLPVectorizer.cpp:0:0
#15 0x0000562e361db4e3 llvm::slpvectorizer::BoUpSLP::computeMinimumValueSizes() (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x5fef4e3)
#16 0x0000562e3623dc1e llvm::SLPVectorizerPass::tryToVectorizeList(llvm::ArrayRef<llvm::Value*>, llvm::slpvectorizer::BoUpSLP&, bool) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x6051c1e)
#17 0x0000562e362427c0 bool tryToVectorizeSequence<llvm::Value>(llvm::SmallVectorImpl<llvm::Value*>&, llvm::function_ref<bool (llvm::Value*, llvm::Value*)>, llvm::function_ref<bool (llvm::Value*, llvm::Value*)>, llvm::function_ref<bool (llvm::ArrayRef<llvm::Value*>, bool)>, bool, llvm::slpvectorizer::BoUpSLP&) (.constprop.0) SLPVectorizer.cpp:0:0
#18 0x0000562e36244162 llvm::SLPVectorizerPass::vectorizeChainsInBlock(llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x6058162)
#19 0x0000562e3624bc96 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
#20 0x0000562e3624c802 llvm::SLPVectorizerPass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x6060802)
#21 0x0000562e35c92cf6 llvm::detail::PassModel<llvm::Function, llvm::SLPVectorizerPass, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x5aa6cf6)
#22 0x0000562e340cd78f llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x3ee178f)
#23 0x0000562e31add026 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/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x18f1026)
#24 0x0000562e340cbb1b llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x3edfb1b)
#25 0x0000562e31adb986 llvm::detail::PassModel<llvm::Module, llvm::ModuleToFunctionPassAdaptor, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x18ef986)
#26 0x0000562e340cc67d llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x3ee067d)
#27 0x0000562e349f1d16 (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
#28 0x0000562e349f566c clang::EmitBackendOutput(clang::DiagnosticsEngine&, clang::HeaderSearchOptions const&, clang::CodeGenOptions const&, clang::TargetOptions const&, clang::LangOptions const&, 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/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x480966c)
#29 0x0000562e350be425 clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x4ed2425)
#30 0x0000562e36cf2c7c clang::ParseAST(clang::Sema&, bool, bool) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x6b06c7c)
#31 0x0000562e3539f2c9 clang::FrontendAction::Execute() (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x51b32c9)
#32 0x0000562e353190f5 clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x512d0f5)
#33 0x0000562e354836b3 clang::ExecuteCompilerInvocation(clang::CompilerInstance*) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x52976b3)
#34 0x0000562e316862d1 cc1_main(llvm::ArrayRef<char const*>, char const*, void*) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x149a2d1)
#35 0x0000562e3167cc8a ExecuteCC1Tool(llvm::SmallVectorImpl<char const*>&, llvm::ToolContext const&) driver.cpp:0:0
#36 0x0000562e31681067 clang_main(int, char**, llvm::ToolContext const&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x1495067)
#37 0x0000562e31579a7b main (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x138da7b)
#38 0x00007f99ac5a6d90 (/lib/x86_64-linux-gnu/libc.so.6+0x29d90)
#39 0x00007f99ac5a6e40 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x29e40)
#40 0x0000562e3167c3b5 _start (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x14903b5)
clangtk: error: unable to execute command: Aborted
clangtk: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 20.0.0git (https://github.com/llvm/llvm-project.git 5208bc3694473f9378fc0d98eeee63e5ad5c5f04)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /local/home/suz/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-522eca.c
clangtk: note: diagnostic msg: /tmp/small-522eca.sh
clangtk: note: diagnostic msg: 

********************
[518] % 
[518] % cat small.c
struct {
  int b : 31;
  int c : 6;
} f, g, j;
int d, e, h, i, k, l, m, n, o;
int main() {
  if (m) {
    short q = d;
    if (d)
    r:
      d = q;
    if (0) {
    s:
    t:
      if (h)
      u:
        o = g.c;
      if (n)
        goto v;
    }
    if (n)
      while (g.c) {
        if (e)
          k;
        int w = j.b, a, b = g.c, c = ~b;
        a = f.b;
        if (l) {
          c = 0 % 0;
          goto u;
        }
        if (a)
          goto s;
        l;
      v:
        if (i)
          goto ae;
        if (b)
          j.b = w;
        f.b = a;
        l = c;
      }
    short p = n;
    if (0) {
    ag:
      h = p;
      if (f.b)
        goto t;
    }
    if (j.b) {
    ae:
      e = 0;
    ai:
      if (q)
        goto r;
    }
  }
  if (j.b)
    goto ai;
  if (d)
    goto ag;
  return 0;
}
```


Fix patch:
commit f4974e09312afc9549fcfc0304b738d235da9eca
Author: Alexey Bataev <a.bataev@outlook.com>
Date:   Fri Nov 29 06:20:19 2024 -0800

    [SLP] Add a check for poison value in AShrChecker
    
    Need to check if the value in AShrChecker is a poison before casting it
    to instruction to avoid compiler crash
    
    Fixes #118030

diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index 48a8520a966f..7723442bc0fb 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -17799,6 +17799,8 @@ bool BoUpSLP::collectValuesToDemote(
     // original type and the sign bit of the truncate type are similar.
     auto AShrChecker = [&](unsigned BitWidth, unsigned OrigBitWidth) {
       return all_of(E.Scalars, [&](Value *V) {
+        if (isa<PoisonValue>(V))
+          return true;
         auto *I = cast<Instruction>(V);
         KnownBits AmtKnownBits = computeKnownBits(I->getOperand(1), *DL);
         unsigned ShiftedBits = OrigBitWidth - BitWidth;


Regression tests:
file: llvm/test/Transforms/SLPVectorizer/X86/ashr-node-with-poison.ll
commands: opt -S --passes=slp-vectorizer -mtriple=x86_64-unknown-linux < %s
tests: test_name: <module>
test_body: 
define i32 @test(ptr %n, i32 %conv57, i1 %tobool5.not, i64 %bf.load14) {
;
entry:
  br i1 false, label %entry.if.end54_crit_edge, label %while.cond

entry.if.end54_crit_edge:
  br label %if.end54

tthread-pre-split:
  br label %t

t:
  %w.2 = phi i32 [ 1, %tthread-pre-split ], [ 0, %if.end83 ]
  br label %if.end7

t.u_crit_edge:
  br label %if.end7

if.end7:
  %w.4 = phi i32 [ %w.2, %t ], [ %w.2, %t.u_crit_edge ], [ %bf.cast25, %while.body ]
  %a.4 = phi i32 [ 0, %t ], [ %conv57, %t.u_crit_edge ], [ %bf.cast2910, %while.body ]
  %b.4 = phi i32 [ 0, %t ], [ 0, %t.u_crit_edge ], [ %bf.cast2910, %while.body ]
  %c.4 = phi i32 [ 0, %t ], [ 1, %t.u_crit_edge ], [ poison, %while.body ]
  br label %v

while.cond:
  %bf.load66.pre.pre1135 = phi i64 [ 0, %entry ], [ %spec.select, %if.end42 ]
  br i1 %tobool5.not, label %if.end54, label %while.body

while.body:
  %bf.ashr24 = ashr i64 %bf.load14, 33
  %bf.cast25 = trunc nsw i64 %bf.ashr24 to i32
  %bf.ashr28 = lshr i64 %bf.load14, 1
  %bf.cast2910 = trunc i64 %bf.ashr28 to i32
  br label %if.end7

if.end36:
  br label %v

v:
  %c.7 = phi i32 [ %c.4, %if.end7 ], [ 0, %if.end36 ]
  br i1 true, label %if.end42, label %v.if.end83_crit_edge

v.if.end83_crit_edge:
  br label %if.end83

if.end42:
  %tobool43.not = icmp eq i32 %b.4, 0
  %narrow = select i1 %tobool43.not, i32 0, i32 %w.4
  %spec.select = zext i32 %narrow to i64
  %bf.value48 = zext i32 %a.4 to i64
  store i64 %bf.value48, ptr %n, align 8
  store i32 %c.7, ptr %n, align 4
  br label %while.cond

if.end54:
  %bf.load66.pre.pre113125 = phi i64 [ %bf.load66.pre.pre1135, %while.cond ], [ poison, %entry.if.end54_crit_edge ]
  %0 = icmp eq i64 %bf.load66.pre.pre113125, 0
  br i1 %0, label %if.end83, label %ai.if.end76_crit_edge

ai.if.end76_crit_edge:
  br label %if.end83

if.end83:
  br label %t
}