commit 3706dfef660097f24fb5efbac0d7f14b424492ed
Author: Florian Hahn <flo@fhahn.com>
Date:   Mon Feb 10 16:29:42 2025 +0000

    [LV] Forget LCSSA phi with new pred before other SCEV invalidation. (#119897)

    `forgetLcssaPhiWithNewPredecessor` performs additional invalidation if
    there is an existing SCEV for the phi, but earlier
    `forgetBlockAndLoopDispositions` or `forgetLoop` may already invalidate
    the SCEV for the phi.

    Change the order to first call `forgetLcssaPhiWithNewPredecessor` to
    ensure it runs before its SCEV gets invalidated too eagerly.

    Fixes https://github.com/llvm/llvm-project/issues/119665.

    PR: https://github.com/llvm/llvm-project/pull/119897

diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index 610e4904a80a..f2241be60ce0 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -2937,10 +2937,6 @@ void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
   if (EnableVPlanNativePath)
     fixNonInductionPHIs(State);

-  // Forget the original basic block.
-  PSE.getSE()->forgetLoop(OrigLoop);
-  PSE.getSE()->forgetBlockAndLoopDispositions();
-
   // After vectorization, the exit blocks of the original loop will have
   // additional predecessors. Invalidate SCEVs for the exit phis in case SE
   // looked through single-entry phis.
@@ -2950,6 +2946,10 @@ void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
     for (PHINode &PN : Exit->phis())
       PSE.getSE()->forgetLcssaPhiWithNewPredecessor(OrigLoop, &PN);

+  // Forget the original basic block.
+  PSE.getSE()->forgetLoop(OrigLoop);
+  PSE.getSE()->forgetBlockAndLoopDispositions();
+
   // Don't apply optimizations below when no vector region remains, as they all
   // require a vector loop at the moment.
   if (!State.Plan->getVectorLoopRegion())

opt -passes='print<scalar-evolution>,loop-vectorize' -force-vector-width=4 -scalar-evolution-classify-expressions=false -S %s

; Test case for https://github.com/llvm/llvm-project/issues/119665.

; %loop.2's backedge-taken-count depends on %add.1 from %loop.1 via its
; corresponding SCEV at the scope of %loop.2. After vectorizing %loop.1, %add.1
; isn't available at the entry of %loop.2 anymore and %add.1 at %loop.2's scope
; must be invalidated, as well as %loop.2's backedge-taken count.
define void @test_invalidate_scevs_at_scope(ptr %p) {
;
entry:
  br label %loop.1

loop.1:
  %iv.1 = phi i32 [ 0, %entry ], [ %iv.1.next, %loop.1 ]
  %1 = load i32, ptr %p, align 4
  %add.1 = add i32 %1, %iv.1
  %iv.1.next = add i32 %iv.1, 1
  %c.1 = icmp eq i32 %iv.1, 100
  br i1 %c.1, label %exit.1, label %loop.1

exit.1:
  %add.lcssa = phi i32 [ %add.1, %loop.1 ]
  br label %loop.2

loop.2:
  %iv.2 = phi i64 [ 0, %exit.1 ], [ %iv.2.next, %loop.2 ]
  %iv.2.trunc = trunc i64 %iv.2 to i32
  %iv.2.next = add i64 %iv.2, 1
  %gep = getelementptr inbounds i64, ptr %p, i64 %iv.2
  store i64 %iv.2, ptr %gep
  %add.2 = add i32 %add.lcssa, %iv.2.trunc
  %c.2 = icmp slt i32 %add.2, 100
  br i1 %c.2, label %loop.2, label %exit.2

exit.2:
  ret void
}

;.
;.

[clang] Crash at -O2: Assertion `isAvailableAtLoopEntry(LHS, L) && "LHS is not available at Loop Entry"' failed.

This code crashes at `-O2`:
```c
int a, e;
int *b;
short c[];
short d;
void f() {
  int g;
  for (;;)
    for (; a - 3 + g < 6; g = g + 1)
      c[g] = d;
}
void h();
void i() {
  h();
  f();
}
void h() {
  e = 0;
  for (; e <= 50; ++e) {
    int *j = &a;
    *j = *b + e;
  }
}
```

Compiler Explorer: https://godbolt.org/z/jfo65eK9x

Crash:
```console
clang: /root/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp:11744: bool llvm::ScalarEvolution::isLoopEntryGuardedByCond(const llvm::Loop*, llvm::CmpInst::Predicate, const llvm::SCEV*, const llvm::SCEV*): Assertion `isAvailableAtLoopEntry(LHS, L) && "LHS is not available at Loop Entry"' failed.
```
Backtrace:
```console
Stack dump:
0.	Program arguments: /opt/compiler-explorer/clang-assertions-trunk/bin/clang -gdwarf-4 -g -o /app/output.s -mllvm --x86-asm-syntax=intel -fno-verbose-asm -S --gcc-toolchain=/opt/compiler-explorer/gcc-snapshot -fcolor-diagnostics -fno-crash-diagnostics -O2 -Wall -Wextra -fno-strict-aliasing <source>
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 "<source>"
4.	Running pass "loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>" on function "i"
 #0 0x0000000003c19758 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x3c19758)
 #1 0x0000000003c17464 llvm::sys::CleanupOnSignal(unsigned long) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x3c17464)
 #2 0x0000000003b649c8 CrashRecoverySignalHandler(int) CrashRecoveryContext.cpp:0:0
 #3 0x000079aa17242520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #4 0x000079aa172969fc pthread_kill (/lib/x86_64-linux-gnu/libc.so.6+0x969fc)
 #5 0x000079aa17242476 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x42476)
 #6 0x000079aa172287f3 abort (/lib/x86_64-linux-gnu/libc.so.6+0x287f3)
 #7 0x000079aa1722871b (/lib/x86_64-linux-gnu/libc.so.6+0x2871b)
 #8 0x000079aa17239e96 (/lib/x86_64-linux-gnu/libc.so.6+0x39e96)
 #9 0x0000000002c90a7b llvm::ScalarEvolution::isLoopEntryGuardedByCond(llvm::Loop const*, llvm::CmpInst::Predicate, llvm::SCEV const*, llvm::SCEV const*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x2c90a7b)
#10 0x0000000002ca6d97 llvm::ScalarEvolution::getTripCountFromExitCount(llvm::SCEV const*, llvm::Type*, llvm::Loop const*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x2ca6d97)
#11 0x00000000058449e4 llvm::VPlan::createInitialVPlan(llvm::Type*, llvm::PredicatedScalarEvolution&, bool, bool, llvm::Loop*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x58449e4)
#12 0x000000000572a8ce llvm::LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(llvm::VFRange&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x572a8ce)
#13 0x000000000572dd5a llvm::LoopVectorizationPlanner::buildVPlansWithVPRecipes(llvm::ElementCount, llvm::ElementCount) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x572dd5a)
#14 0x000000000572e24f llvm::LoopVectorizationPlanner::plan(llvm::ElementCount, unsigned int) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x572e24f)
#15 0x000000000573044f llvm::LoopVectorizePass::processLoop(llvm::Loop*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x573044f)
#16 0x0000000005732a89 llvm::LoopVectorizePass::runImpl(llvm::Function&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x5732a89)
#17 0x00000000057330c3 llvm::LoopVectorizePass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x57330c3)
#18 0x0000000005283abe llvm::detail::PassModel<llvm::Function, llvm::LoopVectorizePass, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x5283abe)
#19 0x00000000035c8550 llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x35c8550)
#20 0x00000000010fa0ee 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-assertions-trunk/bin/clang+0x10fa0ee)
#21 0x00000000035c6e6b llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x35c6e6b)
#22 0x00000000010f977e llvm::detail::PassModel<llvm::Module, llvm::ModuleToFunctionPassAdaptor, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x10f977e)
#23 0x00000000035c6870 llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x35c6870)
#24 0x0000000003eca382 (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 0x0000000003ecdbfd 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*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x3ecdbfd)
#26 0x000000000459e07e clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x459e07e)
#27 0x000000000655704c clang::ParseAST(clang::Sema&, bool, bool) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x655704c)
#28 0x000000000459e458 clang::CodeGenAction::ExecuteAction() (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x459e458)
#29 0x0000000004856fc9 clang::FrontendAction::Execute() (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x4856fc9)
#30 0x00000000047d989e clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x47d989e)
#31 0x000000000494267e clang::ExecuteCompilerInvocation(clang::CompilerInstance*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x494267e)
#32 0x0000000000cb92df cc1_main(llvm::ArrayRef<char const*>, char const*, void*) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0xcb92df)
#33 0x0000000000cb0d7a ExecuteCC1Tool(llvm::SmallVectorImpl<char const*>&, llvm::ToolContext const&) driver.cpp:0:0
#34 0x00000000045e2229 void llvm::function_ref<void ()>::callback_fn<clang::driver::CC1Command::Execute(llvm::ArrayRef<std::optional<llvm::StringRef>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>*, bool*) const::'lambda'()>(long) Job.cpp:0:0
#35 0x0000000003b64e74 llvm::CrashRecoveryContext::RunSafely(llvm::function_ref<void ()>) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x3b64e74)
#36 0x00000000045e281f clang::driver::CC1Command::Execute(llvm::ArrayRef<std::optional<llvm::StringRef>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>*, bool*) const (.part.0) Job.cpp:0:0
#37 0x00000000045a7f3d clang::driver::Compilation::ExecuteCommand(clang::driver::Command const&, clang::driver::Command const*&, bool) const (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x45a7f3d)
#38 0x00000000045a902d clang::driver::Compilation::ExecuteJobs(clang::driver::JobList const&, llvm::SmallVectorImpl<std::pair<int, clang::driver::Command const*>>&, bool) const (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x45a902d)
#39 0x00000000045b0565 clang::driver::Driver::ExecuteCompilation(clang::driver::Compilation&, llvm::SmallVectorImpl<std::pair<int, clang::driver::Command const*>>&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0x45b0565)
#40 0x0000000000cb6123 clang_main(int, char**, llvm::ToolContext const&) (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0xcb6123)
#41 0x0000000000b84564 main (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0xb84564)
#42 0x000079aa17229d90 (/lib/x86_64-linux-gnu/libc.so.6+0x29d90)
#43 0x000079aa17229e40 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x29e40)
#44 0x0000000000cb0825 _start (/opt/compiler-explorer/clang-assertions-trunk/bin/clang+0xcb0825)
```

release:backport vectorizers crash regression:18

Looks like a clang-18 regression: https://godbolt.org/z/K7MMKxjzb

Reduced reproducer: https://godbolt.org/z/s4G9Yb1vG
```
; bin/opt -passes="print<scalar-evolution>,loop-vectorize" test.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 void @i(ptr %p) {
entry:
  br label %for.body.i

for.body.i:                                       ; preds = %for.body.i, %entry
  %0 = phi i32 [ 0, %entry ], [ %inc.i, %for.body.i ]
  %1 = load i32, ptr %p, align 4
  %add.i = add i32 %1, %0
  %inc.i = add i32 %0, 1
  %exitcond.not.i = icmp eq i32 %0, 1
  br i1 %exitcond.not.i, label %for.cond.i.preheader, label %for.body.i

for.cond.i.preheader:                             ; preds = %for.body.i
  br label %for.cond.i

for.cond.i.loopexit:                              ; preds = %for.body.i1
  br label %for.cond.i

for.cond.i:                                       ; preds = %for.cond.i.loopexit, %for.cond.i.preheader
  br label %for.body.i1

for.body.i1:                                      ; preds = %for.body.i1, %for.cond.i
  %indvars.iv.i = phi i64 [ %indvars.iv.next.i, %for.body.i1 ], [ 0, %for.cond.i ]
  %indvars4.i = trunc i64 %indvars.iv.i to i32
  %indvars.iv.next.i = add i64 %indvars.iv.i, 1
  %add.reass.i = add i32 %add.i, %indvars4.i
  %cmp.i = icmp slt i32 %add.reass.i, 0
  br i1 %cmp.i, label %for.body.i1, label %for.cond.i.loopexit
}

```

Thanks, let me take a look


commit a2ba438f3e5635e368333213914c7452a6a6a2da
Author: XChy <xxs_chy@outlook.com>
Date:   Mon Oct 21 22:30:31 2024 +0800

    [InstCombine] Preserve the flag from RHS only if the `and` is bitwise (#113164)

    Fixes #113123
    Alive proof: https://alive2.llvm.org/ce/z/hnqeLC

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
index d72013ba223d..835eae9f5725 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
@@ -1531,8 +1531,10 @@ Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
     }
     if (IsLessThanOrLessEqual(IsAnd ? PredL : PredR)) {
       BuilderTy::FastMathFlagGuard Guard(Builder);
-      Builder.setFastMathFlags(LHS->getFastMathFlags() |
-                               RHS->getFastMathFlags());
+      FastMathFlags NewFlag = LHS->getFastMathFlags();
+      if (!IsLogicalSelect)
+        NewFlag |= RHS->getFastMathFlags();
+      Builder.setFastMathFlags(NewFlag);

       Value *FAbs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, LHS0);
       return Builder.CreateFCmp(PredL, FAbs,

define i1 @test_and_olt_fmf_propagation_union_logical_rhs_poison(float %x) {
  %cmp1 = fcmp ninf olt float %x, 0x3C00000000000000
  %cmp2 = fcmp ogt float %x, 0xBC00000000000000
  %cond = select i1 %cmp2, i1 %cmp1, i1 false
  ret i1 %cond
}

define i1 @test_and_olt_fmf_propagation_union_logical_both_poison(float %x) {
  %cmp1 = fcmp ninf olt float %x, 0x3C00000000000000
  %cmp2 = fcmp ninf ogt float %x, 0xBC00000000000000
  %cond = select i1 %cmp2, i1 %cmp1, i1 false
  ret i1 %cond
}

define i1 @test_and_olt_fmf_propagation_union(float %x) {
  %cmp1 = fcmp nnan ninf olt float %x, 0x3C00000000000000
  %cmp2 = fcmp nnan nsz ogt float %x, 0xBC00000000000000
  %cond = and i1 %cmp1, %cmp2
  ret i1 %cond
}

define i1 @test_and_olt_fmf_propagation_union_logical_lhs_poison(float %x) {
  %cmp1 = fcmp olt float %x, 0x3C00000000000000
  %cmp2 = fcmp ninf ogt float %x, 0xBC00000000000000
  %cond = select i1 %cmp2, i1 %cmp1, i1 false
  ret i1 %cond
}

Wrong canonicalization of a range check idiom

https://github.com/llvm/llvm-project/blob/11dad2fa5138a50d60a5a34a2c7e074b976820e2/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp#L1511-L1527

Alive2 report: https://alive2.llvm.org/ce/z/qBHAmS

```llvm
----------------------------------------
define i1 @test_and_olt_fmf_propagation_union.2(float %x) {
#0:
  %cmp1 = fcmp nnan ninf olt float %x, 0.000000
  %cmp2 = fcmp nnan nsz ogt float %x, -0.000000
  %#1 = select i1 %cmp2, i1 %cmp1, i1 %cmp2
  %cond = and i1 %#1, %cmp2
  ret i1 %cond
}
=>
define i1 @test_and_olt_fmf_propagation_union.2(float %x) {
#0:
  %#1 = fabs nnan ninf nsz float %x
  %#2 = fcmp nnan ninf nsz olt float %#1, 0.000000
  ret i1 %#2
}
Transformation doesn't verify!

ERROR: Target is more poisonous than source

Example:
float %x = #xff800000 (-oo)

Source:
i1 %cmp1 = poison
i1 %cmp2 = #x0 (0)
i1 %#1 = #x0 (0)
i1 %cond = #x0 (0)

Target:
float %#1 = poison
i1 %#2 = poison
Source value: #x0 (0)
Target value: poison

Summary:
  0 correct transformations
  1 incorrect transformations
  0 failed-to-prove transformations
  0 Alive2 errors
```

Thanks for the report.

We preserve `ninf` flag from `cmp1` when folding logical and `select cmp2, cmp1, false` into `fcmp ninf (fabs(x))`. But if `cmp2` equals to `false`, the select won't be poison whatever `cmp1` is. Thus, such fold makes it more poisonous. See https://alive2.llvm.org/ce/z/hnqeLC

> And it looks like you are mutating the unit tests to fuzz LLVM. Looks interesting to me. If OK, could you provide some information about it?

@XChy Yes we are designing a fuzzer on top of LLVM to test the compiler. We can't disclose the full detail at this time. Thank you.


commit a59976bea8ad76f18119a11391dc8ba3e6ba07d5
Author: Yingwei Zheng <dtcxzyw2333@gmail.com>
Date:   Tue Nov 19 20:06:34 2024 +0800

    [InstCombine] Drop noundef attributes in `foldCttzCtlz` (#116718)

    Closes https://github.com/llvm/llvm-project/issues/112068.

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index 6cff3c7af91e..42c0acd1e45e 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -505,8 +505,10 @@ static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) {

   // If ctlz/cttz is only used as a shift amount, set is_zero_poison to true.
   if (II.hasOneUse() && match(Op1, m_Zero()) &&
-      match(II.user_back(), m_Shift(m_Value(), m_Specific(&II))))
+      match(II.user_back(), m_Shift(m_Value(), m_Specific(&II)))) {
+    II.dropUBImplyingAttrsAndMetadata();
     return IC.replaceOperand(II, 1, IC.Builder.getTrue());
+  }

   Constant *C;

define i32 @shl_cttz_false_multiuse(i32 %x, i32 %y) {
entry:
  %cttz = call i32 @llvm.cttz.i32(i32 %y, i1 false)
  call void @use(i32 %cttz)
  %res = shl i32 %x, %cttz
  ret i32 %res
}

declare void @use(i32)

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i32 @llvm.cttz.i32(i32, i1 immarg) #0

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

define i32 @shl_cttz_false_noundef(i32 %x, i32 %y) {
entry:
  %cttz = call noundef i32 @llvm.cttz.i32(i32 %y, i1 false)
  %res = shl i32 %x, %cttz
  ret i32 %res
}

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i32 @llvm.cttz.i32(i32, i1 immarg) #0

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

define i32 @ashr_cttz_false(i32 %x, i32 %y) {
entry:
  %cttz = call i32 @llvm.cttz.i32(i32 %y, i1 false)
  %res = ashr i32 %x, %cttz
  ret i32 %res
}

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i32 @llvm.cttz.i32(i32, i1 immarg) #0

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

define i32 @shl_cttz_false(i32 %x, i32 %y) {
entry:
  %cttz = call i32 @llvm.cttz.i32(i32 %y, i1 false)
  %res = shl i32 %x, %cttz
  ret i32 %res
}

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i32 @llvm.cttz.i32(i32, i1 immarg) #0

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

define i32 @shl_cttz_as_lhs(i32 %x, i32 %y) {
entry:
  %cttz = call i32 @llvm.cttz.i32(i32 %y, i1 false)
  %res = shl i32 %cttz, %x
  ret i32 %res
}

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i32 @llvm.cttz.i32(i32, i1 immarg) #0

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

define i32 @shl_ctlz_false(i32 %x, i32 %y) {
entry:
  %cttz = call i32 @llvm.ctlz.i32(i32 %y, i1 false)
  %res = shl i32 %x, %cttz
  ret i32 %res
}

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i32 @llvm.ctlz.i32(i32, i1 immarg) #0

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

define i32 @lshr_cttz_false(i32 %x, i32 %y) {
entry:
  %cttz = call i32 @llvm.cttz.i32(i32 %y, i1 false)
  %res = lshr i32 %x, %cttz
  ret i32 %res
}

; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare i32 @llvm.cttz.i32(i32, i1 immarg) #0

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

[InstCombine] `noundef` attribute should be dropped after setting `is_zero_poison` to true

Reproducer: https://alive2.llvm.org/ce/z/7-TgAf
```
define i32 @src(i32 %x, i32 %y) {
entry:
  %cttz = call noundef i32 @llvm.cttz.i32(i32 %y, i1 false)
  %res = lshr i32 %x, %cttz
  ret i32 %res
}

define i32 @tgt(i32 %x, i32 %y) {
entry:
  %cttz = call noundef i32 @llvm.cttz.i32(i32 %y, i1 true)
  %res = lshr i32 %x, %cttz
  ret i32 %res
}

define i32 @src2(i32 %x) {
  %ct = call noundef i32 @llvm.ctlz.i32(i32 %x, i1 false)
  %cmp = icmp ne i32 %x, 0
  %res = select i1 %cmp, i32 %ct, i32 123
  ret i32 %res
}

define i32 @tgt2(i32 %x) {
  %ct = call noundef i32 @llvm.ctlz.i32(i32 %x, i1 true)
  %cmp = icmp ne i32 %x, 0
  %res = select i1 %cmp, i32 %ct, i32 123
  ret i32 %res
}
```
`noundef` attribute should be dropped. Otherwise we will convert a poison value to immediate UB.


commit 899fe2cf318f6e3c7a183125ff17ef53944b2989
Author: goldsteinn <35538541+goldsteinn@users.noreply.github.com>
Date:   Thu Jul 4 15:14:39 2024 +0800

    [CVP][LVI] Fix incorrect scalar type when getting constant folded vec (#97682)

    Fixes #97674

    After #97428 added support for vectors, our constant ranges can now be
    from splat vectors so when they reduce to a singe constant value, we
    need to return the original type as opposed to just an int.

diff --git a/llvm/lib/Analysis/LazyValueInfo.cpp b/llvm/lib/Analysis/LazyValueInfo.cpp
index b30e6a6a367c..4209ee4a7795 100644
--- a/llvm/lib/Analysis/LazyValueInfo.cpp
+++ b/llvm/lib/Analysis/LazyValueInfo.cpp
@@ -1370,6 +1370,7 @@ LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,

       // If V is the condition of the branch itself, then we know exactly what
       // it is.
+      // NB: The condition on a `br` can't be a vector type.
       if (Condition == Val)
         return ValueLatticeElement::get(ConstantInt::get(
                               Type::getInt1Ty(Val->getContext()), isTrueDest));
@@ -1723,7 +1724,7 @@ Constant *LazyValueInfo::getConstant(Value *V, Instruction *CxtI) {
   if (Result.isConstantRange()) {
     const ConstantRange &CR = Result.getConstantRange();
     if (const APInt *SingleVal = CR.getSingleElement())
-      return ConstantInt::get(V->getContext(), *SingleVal);
+      return ConstantInt::get(V->getType(), *SingleVal);
   }
   return nullptr;
 }
@@ -1758,7 +1759,7 @@ Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
   if (Result.isConstantRange()) {
     const ConstantRange &CR = Result.getConstantRange();
     if (const APInt *SingleVal = CR.getSingleElement())
-      return ConstantInt::get(V->getContext(), *SingleVal);
+      return ConstantInt::get(V->getType(), *SingleVal);
   }
   return nullptr;
 }

opt -S -passes=correlated-propagation < %s

define <2 x i16> @and_with_poison(<2 x i8> %a) {
  %zext = zext <2 x i8> %a to <2 x i16>
  %res = and <2 x i16> %zext, <i16 255, i16 poison>
  ret <2 x i16> %res
}

define <4 x i64> @issue_97674_getConstant() {
entry:
  %folds = add <4 x i64> zeroinitializer, zeroinitializer
  ret <4 x i64> %folds
}

define <4 x i64> @issue_97674_getConstantOnEdge(i1 %cond) {
entry:
  br i1 %cond, label %if.then, label %if.end

if.then:                                          ; preds = %entry
  %folds = add <4 x i64> zeroinitializer, splat (i64 1)
  br label %if.end

if.end:                                           ; preds = %if.then, %entry
  %r = phi <4 x i64> [ %folds, %if.then ], [ zeroinitializer, %entry ]
  ret <4 x i64> %r
}

A/F: `getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node !"' after 1eec81a

We have an internal test which started to hit an assertion failure when compiled which I bisected back to 1eec81a.

Consider the following code:
```c++
template <bool, class, class> using c = int;
typedef long cb __attribute__((__vector_size__(16)));
cb d(cb);
typedef long e __attribute__((__vector_size__(32)));
enum { f };
struct g {
  enum { h };
};
template <typename> struct i;
template <typename> struct aa;
template <typename> struct j;
template <typename> class k;
template <typename, int l, int m, int = 0, int = l, int = m> class n;
template <typename, typename> class o;
template <typename, int l, int m, int = 0, int = l, int = m> class p;
template <typename> struct q;
template <typename> struct r;
template <typename s> struct t { typedef q<s>::ab ab; };
template <typename ac> struct ad { typedef k<ac> ab; };
template <typename s> struct u {
  operator s() { return ae; }
  u(s v) : ae(v) {}
  s ae;
};
template <typename w> w x(const typename r<w>::ab &);
template <> struct q<int> { typedef u<e> ab; };
template <> struct r<u<e>> {
  typedef int ab;
  enum { af = 8 };
};
template <> u<e> x(const int &) {
  e y{};
  return y;
}
e z;
e ag(e a, u<e> b) {
  __attribute__((__vector_size__(4 * sizeof(long)))) long ah = b;
  z = a + ah;
  return z;
}
struct ai {
  u<__attribute__((__vector_size__(4 * sizeof(long)))) long>
  aj(u<__attribute__((__vector_size__(4 * sizeof(long)))) long> a,
     const u<__attribute__((__vector_size__(4 * sizeof(long)))) long> &b) {
    __attribute__((__vector_size__(4 * sizeof(long)))) long ak = a;
    return ag(ak, b);
  }
};
struct al {
  template <typename am> am aj() { return x<am>(an); }
  int an;
};
template <typename ac> long ao(ac);
template <typename ac> class k : j<ac> {
public:
  typedef i<ac>::ap ap;
  using j<ac>::aq;
  static o<int, c<g::h, ac, p<ac, i<ac>::ar, i<ac>::as>>> at(long, long);
  ap au() const;
  template <typename av> ap aw(const av &) const;
};
template <typename ac> struct j { ac aq() const; };
struct ax {
  template <typename s, typename ay> s aj(al az, ay) { return az.aj<s>(); }
};
template <typename ba, typename bb> struct aa<o<ba, bb>> {
  aa(o<ba, bb>);
  template <int, typename am, typename ay> am bc(ay) {
    return be.aj<am>(bf, d);
  }
  ba bf;
  ax be;
};
template <typename ac> class bg : public ad<ac>::ab {};
template <typename bh, int l, int m, int bi, int bj, int bk>
struct i<n<bh, l, m, bi, bj, bk>> {
  typedef bh ap;
  enum { ar, as };
};
template <typename bh, int l, int m, int bi, int bj, int bk>
struct i<p<bh, l, m, bi, bj, bk>> : i<n<bh, bj, bk>> {};
template <typename, int, int, int, int bj, int bk>
class p : public bg<p<int, bj, bk>> {};
template <typename ba, typename bb> struct i<o<ba, bb>> : i<bb> {};
template <typename, typename>
class o : public ad<o<al, p<int, 0, -1, 1, 0, 1>>>::ab {};
template <typename bl> struct bm {
  typedef t<typename bl::ap>::ab am;
  enum { bn = r<am>::af };
  enum { bo };
};
template <typename, typename bl, int = bm<bl>::bo> struct M;
template <typename bp, typename bl> struct M<bp, bl, f> {
  typedef bm<bl>::am bq;
  template <typename br> static bl bs(bl bt, bp bu, br bv) {
    enum { alignment };
    long bw = ao(bv);
    bq bx = bt.template bc<alignment, bq>(bw);
    if (bw > bm<bl>::bn) {
      bq by = bt.template bc<alignment, bq>(bm<bl>::bn);
      for (long bd; bd; bd += bm<bl>::bn) {
        bx = bu.aj(bx, bt.template bc<alignment, bq>(d));
        u bz = bt.template bc<alignment, bq>(bm<bl>::bn);
        by = bu.aj(by, bz);
      }
      bx = bu.aj(bx, by);
    }
    __attribute__((__vector_size__(4 * sizeof(int)))) int ca =
        __builtin_ia32_vextractf128_si256(bx, 0);
    __attribute__((__vector_size__(2 * sizeof(long)))) long b = d(ca);
  }
};
class cc : public aa<o<al, p<int, 0, -1, 1, 0, 1>>> {
public:
  typedef int ap;
};
template <typename ac>
template <typename bp>
i<ac>::ap k<ac>::aw(const bp &bu) const {
  cc cd(aq());
  o<int, int> ce;
  M<bp, cc>::bs(cd, bu, ce);
}
template <typename ac> i<ac>::ap k<ac>::au() const { aw(ai()); }
void cf() { p<int, 1, 1>::at(0, 0).au(); }
```

When compiled with optimizations and AVX support with a compiler before 1eec81a, the compilation succeeds:
```
$ ~/src/upstream/b76dd4edbfbba5593b691ef92b755f25cf63f445-linux/bin/clang -c -O2 -mavx -Wno-return-type -std=c++20 repro.cpp
$
```

When compiled with the same arguments but with a compiler built from 1eec81a, the compiler hits an assertion failure:
```
$ ~/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang -c -O2 -mavx -Wno-return-type -std=c++20 repro.cpp
clang: /home/dyung/src/upstream/llvm_clean_git/llvm/include/llvm/IR/Instructions.h:2582: void llvm::PHINode::setIncomingValue(unsigned int, llvm::Value*): Assertion `getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node
!"' 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: /home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang -c -O2 -mavx -Wno-return-type -std=c++20 repro.cpp
1.      <eof> parser at end of file
2.      Optimizer
3.      Running pass "require<globals-aa>,function(invalidate<aa>),require<profile-summary>,cgscc(devirt<4>(inline,function-attrs<skip-non-recursive-function-attrs>,openmp-opt-cgscc,function<eager-inv;no-rerun>(sroa<modify-cfg>,early-cse<memssa>,speculative-
execution<only-if-divergent-target>,jump-threading,correlated-propagation,simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-
branch>,instcombine<max-iterations=1;no-use-loop-info;no-verify-fixpoint>,aggressive-instcombine,libcalls-shrinkwrap,tailcallelim,simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-in
sts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,reassociate,constraint-elimination,loop-mssa(loop-instsimplify,loop-simplifycfg,licm<no-allowspeculation>,loop-rotate<header-duplication;no-prepare-for-lto>,licm<allowspeculation>,simple-loop-un
switch<no-nontrivial;trivial>),simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,instcombine<max-iterations=1;no-use
-loop-info;no-verify-fixpoint>,loop(loop-idiom,indvars,simple-loop-unswitch<no-nontrivial;trivial>,loop-deletion,loop-unroll-full),sroa<modify-cfg>,vector-combine,mldst-motion<no-split-footer-bb>,gvn<>,sccp,bdce,instcombine<max-iterations=1;no-use-loop-info;
no-verify-fixpoint>,jump-threading,correlated-propagation,adce,memcpyopt,dse,move-auto-init,loop-mssa(licm<allowspeculation>),coro-elide,simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;hoist-commo
n-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,instcombine<max-iterations=1;no-use-loop-info;no-verify-fixpoint>),function-attrs,function(require<should-not-run-function-passes>),coro-split)),function(invalidate<should-not-run-function-pass
es>),cgscc(devirt<4>())" on module "repro.cpp"
4.      Running pass "cgscc(devirt<4>(inline,function-attrs<skip-non-recursive-function-attrs>,openmp-opt-cgscc,function<eager-inv;no-rerun>(sroa<modify-cfg>,early-cse<memssa>,speculative-execution<only-if-divergent-target>,jump-threading,correlated-propagat
ion,simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,instcombine<max-iterations=1;no-use-loop-info;no-verify-fixpoi
nt>,aggressive-instcombine,libcalls-shrinkwrap,tailcallelim,simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,reasso
ciate,constraint-elimination,loop-mssa(loop-instsimplify,loop-simplifycfg,licm<no-allowspeculation>,loop-rotate<header-duplication;no-prepare-for-lto>,licm<allowspeculation>,simple-loop-unswitch<no-nontrivial;trivial>),simplifycfg<bonus-inst-threshold=1;no-f
orward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,instcombine<max-iterations=1;no-use-loop-info;no-verify-fixpoint>,loop(loop-idiom,indvars,simple-loop-uns
witch<no-nontrivial;trivial>,loop-deletion,loop-unroll-full),sroa<modify-cfg>,vector-combine,mldst-motion<no-split-footer-bb>,gvn<>,sccp,bdce,instcombine<max-iterations=1;no-use-loop-info;no-verify-fixpoint>,jump-threading,correlated-propagation,adce,memcpyo
pt,dse,move-auto-init,loop-mssa(licm<allowspeculation>),coro-elide,simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,instc
ombine<max-iterations=1;no-use-loop-info;no-verify-fixpoint>),function-attrs,function(require<should-not-run-function-passes>),coro-split))" on module "repro.cpp"
5.      Running pass "correlated-propagation" on function "_ZN1MI2ai2ccLi0EE2bsI1oIiiEEES1_S1_S0_T_"
 #0 0x000056411be676af llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x41856af)
 #1 0x000056411be6520c llvm::sys::CleanupOnSignal(unsigned long) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x418320c)
 #2 0x000056411bdaa728 CrashRecoverySignalHandler(int) CrashRecoveryContext.cpp:0:0
 #3 0x00007f29a8886420 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x14420)
 #4 0x00007f29a835300b raise /build/glibc-LcI20x/glibc-2.31/signal/../sysdeps/unix/sysv/linux/raise.c:51:1
 #5 0x00007f29a8332859 abort /build/glibc-LcI20x/glibc-2.31/stdlib/abort.c:81:7
 #6 0x00007f29a8332729 get_sysdep_segment_value /build/glibc-LcI20x/glibc-2.31/intl/loadmsgcat.c:509:8
 #7 0x00007f29a8332729 _nl_load_domain /build/glibc-LcI20x/glibc-2.31/intl/loadmsgcat.c:970:34
 #8 0x00007f29a8343fd6 (/lib/x86_64-linux-gnu/libc.so.6+0x33fd6)
 #9 0x00005641200199a5 processPHI(llvm::PHINode*, llvm::LazyValueInfo*, llvm::DominatorTree*, llvm::SimplifyQuery const&) CorrelatedValuePropagation.cpp:0:0
#10 0x000056412002131e runImpl(llvm::Function&, llvm::LazyValueInfo*, llvm::DominatorTree*, llvm::SimplifyQuery const&) CorrelatedValuePropagation.cpp:0:0
#11 0x0000564120022b4b llvm::CorrelatedValuePropagationPass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x8340b4b)
#12 0x000056411d2b9866 llvm::detail::PassModel<llvm::Function, llvm::CorrelatedValuePropagationPass, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x55d7866)
#13 0x000056411b80daf1 llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x3b2baf1)
#14 0x00005641193e3d86 llvm::detail::PassModel<llvm::Function, llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x1701d86)
#15 0x000056411acf6e91 llvm::CGSCCToFunctionPassAdaptor::run(llvm::LazyCallGraph::SCC&, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>&, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x3014e91)
#16 0x00005641193e5326 llvm::detail::PassModel<llvm::LazyCallGraph::SCC, llvm::CGSCCToFunctionPassAdaptor, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&>::run(llvm::LazyCallGraph::SCC&, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>&, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x1703326)
#17 0x000056411aceef7f llvm::PassManager<llvm::LazyCallGraph::SCC, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&>::run(llvm::LazyCallGraph::SCC&, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>&, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x300cf7f)
#18 0x000056411d2b71b6 llvm::detail::PassModel<llvm::LazyCallGraph::SCC, llvm::PassManager<llvm::LazyCallGraph::SCC, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&>, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&>::run(llvm::LazyCallGraph::SCC&, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>&, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x55d51b6)
#19 0x000056411acf370d llvm::DevirtSCCRepeatedPass::run(llvm::LazyCallGraph::SCC&, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>&, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x301170d)
#20 0x000056411d2b7206 llvm::detail::PassModel<llvm::LazyCallGraph::SCC, llvm::DevirtSCCRepeatedPass, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&>::run(llvm::LazyCallGraph::SCC&, llvm::AnalysisManager<llvm::LazyCallGraph::SCC, llvm::LazyCallGraph&>&, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x55d5206)
#21 0x000056411acf150c llvm::ModuleToPostOrderCGSCCPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x300f50c)
#22 0x000056411d2b7166 llvm::detail::PassModel<llvm::Module, llvm::ModuleToPostOrderCGSCCPassAdaptor, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x55d5166)
#23 0x000056411b80a601 llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x3b28601)
#24 0x000056411d4afdb5 llvm::ModuleInlinerWrapperPass::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x57cddb5)
#25 0x000056411d2b68f6 llvm::detail::PassModel<llvm::Module, llvm::ModuleInlinerWrapperPass, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x55d48f6)
#26 0x000056411b80a601 llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x3b28601)
#27 0x000056411c11c4d8 (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 0x000056411c11f855 (anonymous namespace)::EmitAssemblyHelper::EmitAssembly(clang::BackendAction, std::unique_ptr<llvm::raw_pwrite_stream, std::default_delete<llvm::raw_pwrite_stream>>, clang::BackendConsumer*) BackendUtil.cpp:0:0
#29 0x000056411c11fef6 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*) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x443def6)
#30 0x000056411c792bea clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x4ab0bea)
#31 0x000056411e56cb8c clang::ParseAST(clang::Sema&, bool, bool) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x688ab8c)
#32 0x000056411c793078 clang::CodeGenAction::ExecuteAction() (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x4ab1078)
#33 0x000056411ca26e79 clang::FrontendAction::Execute() (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x4d44e79)
#34 0x000056411c9aa76e clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x4cc876e)
#35 0x000056411cb12366 clang::ExecuteCompilerInvocation(clang::CompilerInstance*) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x4e30366)
#36 0x0000564118fcc89f cc1_main(llvm::ArrayRef<char const*>, char const*, void*) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x12ea89f)
#37 0x0000564118fc594a ExecuteCC1Tool(llvm::SmallVectorImpl<char const*>&, llvm::ToolContext const&) driver.cpp:0:0
#38 0x000056411c7d833d void llvm::function_ref<void ()>::callback_fn<clang::driver::CC1Command::Execute(llvm::ArrayRef<std::optional<llvm::StringRef>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>*, bool*) const::'lambda'()>(long) Job.cpp:0:0
#39 0x000056411bdaac30 llvm::CrashRecoveryContext::RunSafely(llvm::function_ref<void ()>) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x40c8c30)
#40 0x000056411c7d895f clang::driver::CC1Command::Execute(llvm::ArrayRef<std::optional<llvm::StringRef>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>*, bool*) const (.part.0) Job.cpp:0:0
#41 0x000056411c79cdbc clang::driver::Compilation::ExecuteCommand(clang::driver::Command const&, clang::driver::Command const*&, bool) const (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x4abadbc)
#42 0x000056411c79d84d clang::driver::Compilation::ExecuteJobs(clang::driver::JobList const&, llvm::SmallVectorImpl<std::pair<int, clang::driver::Command const*>>&, bool) const (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x4abb84d)
#43 0x000056411c7a5925 clang::driver::Driver::ExecuteCompilation(clang::driver::Compilation&, llvm::SmallVectorImpl<std::pair<int, clang::driver::Command const*>>&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x4ac3925)
#44 0x0000564118fc9bab clang_main(int, char**, llvm::ToolContext const&) (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x12e7bab)
#45 0x0000564118ebcc0b main (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x11dac0b)
#46 0x00007f29a8334083 __libc_start_main /build/glibc-LcI20x/glibc-2.31/csu/../csu/libc-start.c:342:3
#47 0x0000564118fc53de _start (/home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin/clang+0x12e33de)
clang: error: clang frontend command failed with exit code 134 (use -v to see invocation)
clang version 19.0.0 (https://github.com/llvm/llvm-project.git 1eec81a831dcf925c0c86c153e8dce019a5b5436)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /home/dyung/src/upstream/1eec81a831dcf925c0c86c153e8dce019a5b5436-linux/bin
```

Seems like when `CVP` finds a constant, its returning the scalar, not the VEC type.

Reducer of exact error:
```
define <4 x i64> @reduce(i1 %cond) {
entry:
  br i1 %cond, label %if.then, label %if.end

if.then:
  %folds = add <4 x i64> zeroinitializer, <i64 1, i64 1, i64 1, i64 1>
  br label %if.end

if.end:
  %r = phi <4 x i64> [ %folds, %if.then ], [ zeroinitializer, %entry ]
  ret <4 x i64> %r
}
```
Repro with: `opt  -passes=correlated-propagation`

Or an even simpler version (different assert location):
```
define <4 x i64> @reduce() {
entry:
  %folds = add <4 x i64> zeroinitializer, zeroinitializer
  ret <4 x i64> %folds
}

```

Same command as above.

Ill have a fix up shortly.

Fix at: https://github.com/llvm/llvm-project/pull/97682


commit af524de1fa94e4b4cee8b745d1b68f4ea0090759
Author: Alexey Bataev <a.bataev@outlook.com>
Date:   Mon Jan 13 06:48:56 2025 -0800

    [SLP]Do not include subvectors for fully matched buildvectors

    If the buildvector node fully matched another node, need to exclude
    subvectors, when building final shuffle, just a shuffle of the original
    node must be emitted.

    Fixes #122584

diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index e3487b501534..df46c69ff3ab 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -14935,8 +14935,8 @@ ResTy BoUpSLP::processBuildVector(const TreeEntry *E, Type *ScalarTy,
           }
         }
         ShuffleBuilder.add(*FrontTE, Mask);
-        Res = ShuffleBuilder.finalize(E->getCommonMask(), SubVectors,
-                                      SubVectorsMask);
+        // Full matched entry found, no need to insert subvectors.
+        Res = ShuffleBuilder.finalize(E->getCommonMask(), {}, {});
         return Res;
       }
       if (!Resized) {

opt -aa-pipeline=basic-aa -passes='slp-vectorizer' -S %s

target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128"
target triple = "arm64-apple-ios5.0.0"

define void @select_uniform_ugt_16xi8(ptr %ptr, i8 %x) {
entry:
  %l.0 = load i8, ptr %ptr, align 1
  %cmp.0 = icmp ugt i8 %l.0, -1
  %s.0 = select i1 %cmp.0, i8 %l.0, i8 %x
  store i8 %s.0, ptr %ptr, align 2
  %gep.1 = getelementptr inbounds i8, ptr %ptr, i8 1
  %l.1 = load i8, ptr %gep.1, align 1
  %cmp.1 = icmp ugt i8 %l.1, -1
  %s.1 = select i1 %cmp.1, i8 %l.1, i8 %x
  store i8 %s.1, ptr %gep.1, align 2
  %gep.2 = getelementptr inbounds i8, ptr %ptr, i8 2
  %l.2 = load i8, ptr %gep.2, align 1
  %cmp.2 = icmp ugt i8 %l.2, -1
  %s.2 = select i1 %cmp.2, i8 %l.2, i8 %x
  store i8 %s.2, ptr %gep.2, align 2
  %gep.3 = getelementptr inbounds i8, ptr %ptr, i8 3
  %l.3 = load i8, ptr %gep.3, align 1
  %cmp.3 = icmp ugt i8 %l.3, -1
  %s.3 = select i1 %cmp.3, i8 %l.3, i8 %x
  store i8 %s.3, ptr %gep.3, align 2
  %gep.4 = getelementptr inbounds i8, ptr %ptr, i8 4
  %l.4 = load i8, ptr %gep.4, align 1
  %cmp.4 = icmp ugt i8 %l.4, -1
  %s.4 = select i1 %cmp.4, i8 %l.4, i8 %x
  store i8 %s.4, ptr %gep.4, align 2
  %gep.5 = getelementptr inbounds i8, ptr %ptr, i8 5
  %l.5 = load i8, ptr %gep.5, align 1
  %cmp.5 = icmp ugt i8 %l.5, -1
  %s.5 = select i1 %cmp.5, i8 %l.5, i8 %x
  store i8 %s.5, ptr %gep.5, align 2
  %gep.6 = getelementptr inbounds i8, ptr %ptr, i8 6
  %l.6 = load i8, ptr %gep.6, align 1
  %cmp.6 = icmp ugt i8 %l.6, -1
  %s.6 = select i1 %cmp.6, i8 %l.6, i8 %x
  store i8 %s.6, ptr %gep.6, align 2
  %gep.7 = getelementptr inbounds i8, ptr %ptr, i8 7
  %l.7 = load i8, ptr %gep.7, align 1
  %cmp.7 = icmp ugt i8 %l.7, -1
  %s.7 = select i1 %cmp.7, i8 %l.7, i8 %x
  store i8 %s.7, ptr %gep.7, align 2
  %gep.8 = getelementptr inbounds i8, ptr %ptr, i8 8
  %l.8 = load i8, ptr %gep.8, align 1
  %cmp.8 = icmp ugt i8 %l.8, -1
  %s.8 = select i1 %cmp.8, i8 %l.0, i8 %x
  store i8 %s.0, ptr %gep.8, align 2
  %gep.9 = getelementptr inbounds i8, ptr %ptr, i8 9
  %l.9 = load i8, ptr %gep.9, align 1
  %cmp.9 = icmp ugt i8 %l.9, -1
  %s.9 = select i1 %cmp.9, i8 %l.9, i8 %x
  store i8 %s.9, ptr %gep.9, align 2
  %gep.10 = getelementptr inbounds i8, ptr %ptr, i8 10
  %l.10 = load i8, ptr %gep.10, align 1
  %cmp.10 = icmp ugt i8 %l.10, -1
  %s.10 = select i1 %cmp.10, i8 %l.10, i8 %x
  store i8 %s.10, ptr %gep.10, align 2
  %gep.11 = getelementptr inbounds i8, ptr %ptr, i8 11
  %l.11 = load i8, ptr %gep.11, align 1
  %cmp.11 = icmp ugt i8 %l.11, -1
  %s.11 = select i1 %cmp.11, i8 %l.11, i8 %x
  store i8 %s.11, ptr %gep.11, align 2
  %gep.12 = getelementptr inbounds i8, ptr %ptr, i8 12
  %l.12 = load i8, ptr %gep.12, align 1
  %cmp.12 = icmp ugt i8 %l.12, -1
  %s.12 = select i1 %cmp.12, i8 %l.12, i8 %x
  store i8 %s.12, ptr %gep.12, align 2
  %gep.13 = getelementptr inbounds i8, ptr %ptr, i8 13
  %l.13 = load i8, ptr %gep.13, align 1
  %cmp.13 = icmp ugt i8 %l.13, -1
  %s.13 = select i1 %cmp.13, i8 %l.13, i8 %x
  store i8 %s.13, ptr %gep.13, align 2
  %gep.14 = getelementptr inbounds i8, ptr %ptr, i8 14
  %l.14 = load i8, ptr %gep.14, align 1
  %cmp.14 = icmp ugt i8 %l.14, -1
  %s.14 = select i1 %cmp.14, i8 %l.14, i8 %x
  store i8 %s.14, ptr %gep.14, align 2
  %gep.15 = getelementptr inbounds i8, ptr %ptr, i8 15
  %l.15 = load i8, ptr %gep.15, align 1
  %cmp.15 = icmp ugt i8 %l.15, -1
  %s.15 = select i1 %cmp.15, i8 %l.15, i8 %x
  store i8 %s.15, ptr %gep.15, align 2
  ret void
}

opt -S --passes=slp-vectorizer -slp-threshold=-9999 -mtriple=x86_64-unknown-linux-gnu < %s

define i32 @test(i64 %l.549) {
entry:
  %conv3 = sext i32 0 to i64
  br label %if.then19

p:                                                ; preds = %if.end29, %if.end25
  %l.0 = phi i64 [ %xor, %if.end29 ], [ %l.5493, %if.end25 ]
  %m.0 = phi i64 [ %not21, %if.end29 ], [ %m.550, %if.end25 ]
  br i1 false, label %s, label %q

q:                                                ; preds = %land.lhs.true, %p
  %xor39 = phi i64 [ 0, %p ], [ 0, %land.lhs.true ]
  %l.1 = phi i64 [ 0, %p ], [ 0, %land.lhs.true ]
  %m.1 = phi i64 [ 0, %p ], [ 0, %land.lhs.true ]
  br i1 false, label %lor.lhs.false, label %r

lor.lhs.false:                                    ; preds = %q
  br i1 false, label %land.lhs.true, label %s

r:                                                ; preds = %if.then19, %q
  %xor38 = phi i64 [ %xor39, %q ], [ %xor, %if.then19 ]
  %j.0 = phi i64 [ %conv3, %q ], [ %not21, %if.then19 ]
  %l.2 = phi i64 [ %l.1, %q ], [ %l.549, %if.then19 ]
  %m.2 = phi i64 [ %m.1, %q ], [ %m.550, %if.then19 ]
  br i1 false, label %s, label %land.lhs.true

land.lhs.true:                                    ; preds = %r, %lor.lhs.false
  %xor37 = phi i64 [ %xor38, %r ], [ 0, %lor.lhs.false ]
  %j.1 = phi i64 [ %j.0, %r ], [ 0, %lor.lhs.false ]
  %l.3 = phi i64 [ %l.2, %r ], [ 0, %lor.lhs.false ]
  %m.3 = phi i64 [ %m.2, %r ], [ 0, %lor.lhs.false ]
  br i1 false, label %q, label %s

s:                                                ; preds = %land.lhs.true, %r, %lor.lhs.false, %p
  %xor36 = phi i64 [ %xor37, %land.lhs.true ], [ %xor38, %r ], [ %xor39, %lor.lhs.false ], [ %l.0, %p ]
  %j.2 = phi i64 [ %j.1, %land.lhs.true ], [ %j.0, %r ], [ %conv3, %lor.lhs.false ], [ %m.0, %p ]
  %l.4 = phi i64 [ %l.3, %land.lhs.true ], [ %l.2, %r ], [ %l.1, %lor.lhs.false ], [ %l.0, %p ]
  %m.4 = phi i64 [ %m.3, %land.lhs.true ], [ %m.2, %r ], [ %m.1, %lor.lhs.false ], [ %m.0, %p ]
  br label %if.then19

if.then19:                                        ; preds = %s, %entry
  %m.550 = phi i64 [ 0, %entry ], [ %m.4, %s ]
  %l.5493 = phi i64 [ 0, %entry ], [ %l.4, %s ]
  %xor = xor i64 0, 0
  %not21 = xor i64 0, 0
  br i1 false, label %r, label %if.end25

if.end25:                                         ; preds = %if.then19
  br i1 false, label %if.end29, label %p

if.end29:                                         ; preds = %if.end25
  br label %p
}

clang crashes on valid code at -O{s,2,3} on x86_64-linux-gnu: Assertion `I1 == PoisonMaskElem && "Expected unused subvectors mask"' failed

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

Compiler Explorer: https://godbolt.org/z/vWPhsMfoz

```
[510] % clangtk -v
clang version 20.0.0git (https://github.com/llvm/llvm-project.git 24bd9bc0b59d51c82e9a4d84c21d86d58d0ef6ce)
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 12.1
[511] %
[511] % clangtk -O2 small.c
clang-20: /local/suz-local/software/clangbuild/llvm-project/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp:10936: llvm::InstructionCost llvm::slpvectorizer::BoUpSLP::ShuffleCostEstimator::finalize(llvm::ArrayRef<int>, llvm::ArrayRef<std::pair<const llvm::slpvectorizer::BoUpSLP::TreeEntry*, unsigned int> >, llvm::ArrayRef<int>, unsigned int, llvm::function_ref<void(llvm::Value*&, llvm::SmallVectorImpl<int>&)>): Assertion `I1 == PoisonMaskElem && "Expected unused subvectors mask"' 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/20250111-clangtk-m64-Os-build-025751/delta -fcoverage-compilation-dir=/local/suz-local/software/emitesting/bugs/20250111-clangtk-m64-Os-build-025751/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 -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-2771d7.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 0x0000562bd646d500 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x4576500)
 #1 0x0000562bd646a91f llvm::sys::RunSignalHandlers() (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x457391f)
 #2 0x0000562bd646aa75 SignalHandler(int) Signals.cpp:0:0
 #3 0x00007f13d1771520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #4 0x00007f13d17c5a7c pthread_kill (/lib/x86_64-linux-gnu/libc.so.6+0x96a7c)
 #5 0x00007f13d1771476 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x42476)
 #6 0x00007f13d17577f3 abort (/lib/x86_64-linux-gnu/libc.so.6+0x287f3)
 #7 0x00007f13d175771b (/lib/x86_64-linux-gnu/libc.so.6+0x2871b)
 #8 0x00007f13d1768e96 (/lib/x86_64-linux-gnu/libc.so.6+0x39e96)
 #9 0x0000562bd7f25a4f llvm::slpvectorizer::BoUpSLP::ShuffleCostEstimator::finalize(llvm::ArrayRef<int>, llvm::ArrayRef<std::pair<llvm::slpvectorizer::BoUpSLP::TreeEntry const*, unsigned int>>, llvm::ArrayRef<int>, unsigned int, llvm::function_ref<void (llvm::Value*&, llvm::SmallVectorImpl<int>&)>) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x602ea4f)
#10 0x0000562bd7f9164b llvm::InstructionCost llvm::slpvectorizer::BoUpSLP::processBuildVector<llvm::slpvectorizer::BoUpSLP::ShuffleCostEstimator, llvm::InstructionCost, llvm::TargetTransformInfo, llvm::ArrayRef<llvm::Value*>, llvm::slpvectorizer::BoUpSLP, llvm::SmallPtrSetImpl<llvm::Value*>>(llvm::slpvectorizer::BoUpSLP::TreeEntry const*, llvm::Type*, llvm::TargetTransformInfo&, llvm::ArrayRef<llvm::Value*>&, llvm::slpvectorizer::BoUpSLP&, llvm::SmallPtrSetImpl<llvm::Value*>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x609a64b)
#11 0x0000562bd7f92881 llvm::slpvectorizer::BoUpSLP::getEntryCost(llvm::slpvectorizer::BoUpSLP::TreeEntry const*, llvm::ArrayRef<llvm::Value*>, llvm::SmallPtrSetImpl<llvm::Value*>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x609b881)
#12 0x0000562bd7faaa12 llvm::slpvectorizer::BoUpSLP::getTreeCost(llvm::ArrayRef<llvm::Value*>) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x60b3a12)
#13 0x0000562bd7fb43e8 llvm::SLPVectorizerPass::tryToVectorizeList(llvm::ArrayRef<llvm::Value*>, llvm::slpvectorizer::BoUpSLP&, bool) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x60bd3e8)
#14 0x0000562bd7fb92b0 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
#15 0x0000562bd7fbabe9 llvm::SLPVectorizerPass::vectorizeChainsInBlock(llvm::BasicBlock*, llvm::slpvectorizer::BoUpSLP&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x60c3be9)
#16 0x0000562bd7fc268e 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 0x0000562bd7fc31d1 llvm::SLPVectorizerPass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x60cc1d1)
#18 0x0000562bd79d6826 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+0x5adf826)
#19 0x0000562bd5de82ef 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+0x3ef12ef)
#20 0x0000562bd37a5226 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+0x18ae226)
#21 0x0000562bd5de664b llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x3eef64b)
#22 0x0000562bd37a3b36 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+0x18acb36)
#23 0x0000562bd5de724d 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+0x3ef024d)
#24 0x0000562bd67194c7 (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 0x0000562bd671d213 clang::emitBackendOutput(clang::CompilerInstance&, 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+0x4826213)
#26 0x0000562bd6df1805 clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x4efa805)
#27 0x0000562bd8a8c2cc clang::ParseAST(clang::Sema&, bool, bool) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x6b952cc)
#28 0x0000562bd70d6ca9 clang::FrontendAction::Execute() (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x51dfca9)
#29 0x0000562bd7054ad5 clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x515dad5)
#30 0x0000562bd71bbf73 clang::ExecuteCompilerInvocation(clang::CompilerInstance*) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x52c4f73)
#31 0x0000562bd334425f cc1_main(llvm::ArrayRef<char const*>, char const*, void*) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x144d25f)
#32 0x0000562bd333ab2a ExecuteCC1Tool(llvm::SmallVectorImpl<char const*>&, llvm::ToolContext const&) driver.cpp:0:0
#33 0x0000562bd333efe7 clang_main(int, char**, llvm::ToolContext const&) (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x1447fe7)
#34 0x0000562bd322eb3b main (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x1337b3b)
#35 0x00007f13d1758d90 (/lib/x86_64-linux-gnu/libc.so.6+0x29d90)
#36 0x00007f13d1758e40 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x29e40)
#37 0x0000562bd333a255 _start (/local/home/suz/suz-local/software/local/clang-trunk/bin/clang-20+0x1443255)
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 24bd9bc0b59d51c82e9a4d84c21d86d58d0ef6ce)
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-929da7.c
clangtk: note: diagnostic msg: /tmp/small-929da7.sh
clangtk: note: diagnostic msg:

********************
[512] %
[512] % cat small.c
int a, b, d, e, f, i, n;
long c, g, h;
unsigned o;
int main() {
  unsigned long j;
  long l, m;
  if (0) {
  k:
    h = ~g;
    l = g;
    m = j;
    i = d;
  p:
    b = g = i;
    if (d) {
    q:
      j = a;
      if (i || i >= a)
      r:
        if (f && h > a)
          goto q;
      goto s;
    }
    g = l;
    j = m;
  s:;
  }
  if (c) {
    n = j % -1;
    o = b;
    if (n) {
      g = d ^ j;
      j = ~(1 / o);
      if (!(n - 1))
        goto r;
      if (e)
        goto p;
    }
    goto k;
  }
}
```

llvm:SLPVectorizer
crash-on-valid
generated by fuzzer

Reduced reproducer: https://godbolt.org/z/MzcesqWz1
```
; bin/opt -passes=slp-vectorizer 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(i64 %l.549) {
entry:
  %conv3 = sext i32 0 to i64
  br label %if.then19

p:                                                ; preds = %if.end29, %if.end25
  %l.0 = phi i64 [ %xor, %if.end29 ], [ %l.5493, %if.end25 ]
  %m.0 = phi i64 [ %not21, %if.end29 ], [ %m.550, %if.end25 ]
  br i1 false, label %s, label %q

q:                                                ; preds = %land.lhs.true, %p
  %xor39 = phi i64 [ 0, %p ], [ 0, %land.lhs.true ]
  %l.1 = phi i64 [ 0, %p ], [ 0, %land.lhs.true ]
  %m.1 = phi i64 [ 0, %p ], [ 0, %land.lhs.true ]
  br i1 false, label %lor.lhs.false, label %r

lor.lhs.false:                                    ; preds = %q
  br i1 false, label %land.lhs.true, label %s

r:                                                ; preds = %if.then19, %q
  %xor38 = phi i64 [ %xor39, %q ], [ %xor, %if.then19 ]
  %j.0 = phi i64 [ %conv3, %q ], [ %not21, %if.then19 ]
  %l.2 = phi i64 [ %l.1, %q ], [ %l.549, %if.then19 ]
  %m.2 = phi i64 [ %m.1, %q ], [ %m.550, %if.then19 ]
  br i1 false, label %s, label %land.lhs.true

land.lhs.true:                                    ; preds = %r, %lor.lhs.false
  %xor37 = phi i64 [ %xor38, %r ], [ 0, %lor.lhs.false ]
  %j.1 = phi i64 [ %j.0, %r ], [ 0, %lor.lhs.false ]
  %l.3 = phi i64 [ %l.2, %r ], [ 0, %lor.lhs.false ]
  %m.3 = phi i64 [ %m.2, %r ], [ 0, %lor.lhs.false ]
  br i1 false, label %q, label %s

s:                                                ; preds = %land.lhs.true, %r, %lor.lhs.false, %p
  %xor36 = phi i64 [ %xor37, %land.lhs.true ], [ %xor38, %r ], [ %xor39, %lor.lhs.false ], [ %l.0, %p ]
  %j.2 = phi i64 [ %j.1, %land.lhs.true ], [ %j.0, %r ], [ %conv3, %lor.lhs.false ], [ %m.0, %p ]
  %l.4 = phi i64 [ %l.3, %land.lhs.true ], [ %l.2, %r ], [ %l.1, %lor.lhs.false ], [ %l.0, %p ]
  %m.4 = phi i64 [ %m.3, %land.lhs.true ], [ %m.2, %r ], [ %m.1, %lor.lhs.false ], [ %m.0, %p ]
  br label %if.then19

if.then19:                                        ; preds = %s, %entry
  %m.550 = phi i64 [ 0, %entry ], [ %m.4, %s ]
  %l.5493 = phi i64 [ 0, %entry ], [ %l.4, %s ]
  %xor = xor i64 0, 0
  %not21 = xor i64 0, 0
  br i1 false, label %r, label %if.end25

if.end25:                                         ; preds = %if.then19
  br i1 false, label %if.end29, label %p

if.end29:                                         ; preds = %if.end25
  br label %p
}

```


commit beccecaacde405a3b50891c67594eccbcd1c8b08
Author: Alexey Bataev <a.bataev@outlook.com>
Date:   Mon Jul 15 07:03:22 2024 -0700

    [SLP]Fix PR98838: do no replace condition of select-based logical op by poison.

    If the reduction operation is a select-based logical op, the condition
    should be replaced by the poison, better to replace by the non-poisoning
    constant to prevent poison propagation in the vector code.

    Fixes https://github.com/llvm/llvm-project/issues/98838

diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index 5c2fc0b9320e..74a16d3fbcad 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -14201,9 +14201,23 @@ Value *BoUpSLP::vectorizeTree(
     for (Instruction *I : RemovedInsts) {
       if (getTreeEntry(I)->Idx != 0)
         continue;
+      SmallVector<SelectInst *> LogicalOpSelects;
       I->replaceUsesWithIf(PoisonValue::get(I->getType()), [&](Use &U) {
+        // Do not replace condition of the logical op in form select <cond>.
+        bool IsPoisoningLogicalOp = isa<SelectInst>(U.getUser()) &&
+                                    (match(U.getUser(), m_LogicalAnd()) ||
+                                     match(U.getUser(), m_LogicalOr())) &&
+                                    U.getOperandNo() == 0;
+        if (IsPoisoningLogicalOp) {
+          LogicalOpSelects.push_back(cast<SelectInst>(U.getUser()));
+          return false;
+        }
         return UserIgnoreList->contains(U.getUser());
       });
+      // Replace conditions of the poisoning logical ops with the non-poison
+      // constant value.
+      for (SelectInst *SI : LogicalOpSelects)
+        SI->setCondition(Constant::getNullValue(SI->getCondition()->getType()));
     }
   }
   // Retain to-be-deleted instructions for some debug-info bookkeeping and alias

wrong code at -O3 on x86_64-linux-gnu

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

Compiler Explorer: https://godbolt.org/z/fzsqjEPWW

```
[562] % clangtk -v
clang version 19.0.0git (https://github.com/llvm/llvm-project.git 52139d8f9a4e3f595ca552393d62ba06b0bc082c)
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
[563] %
[563] % clangtk -O2 -w small.c
[564] % ./a.out
0
[565] % clangtk -O3 -w small.c
[566] % ./a.out
[567] %
[567] % cat small.c
int printf(const char *, ...);
int a, b, e, g;
volatile int c;
static int d[1] = {1}, f;
int h() {
  for (b = 0; b < 4; b++) {
    for (e = 0; e < 4; e++)
      while (b) {
        if (c > 0 && d[1])
          break;
        return f;
      }
  }
  return 0;
}
void i() {
  int *j[1];
  j[g] = &d[0];
}
int main() {
  h();
  printf("%d\n", a);
  return 0;
}
```

Reproducer: https://alive2.llvm.org/ce/z/Whfr_a
```
; bin/opt -passes=slp-vectorizer -S test.ll
define i1 @src(i1 %cmp4.118.i) {
  %cmp4.118.i.not = xor i1 %cmp4.118.i, true
  %brmerge = select i1 %cmp4.118.i.not, i1 true, i1 poison
  %.not = xor i1 poison, true
  %brmerge2 = select i1 %brmerge, i1 true, i1 %.not
  %.not3 = xor i1 poison, true
  %brmerge4 = select i1 %brmerge2, i1 true, i1 %.not3
  %.not5 = xor i1 poison, true
  %brmerge6 = select i1 %brmerge4, i1 true, i1 %.not5
  %.not7 = xor i1 poison, true
  %brmerge8 = select i1 %brmerge6, i1 true, i1 %.not7
  ret i1 %brmerge8
}
```
```
define i1 @tgt(i1 %cmp4.118.i) {
  %1 = insertelement <4 x i1> <i1 poison, i1 true, i1 true, i1 true>, i1 %cmp4.118.i, i32 0
  %2 = xor <4 x i1> %1, <i1 true, i1 poison, i1 poison, i1 poison>
  %.not7 = xor i1 poison, true
  %3 = freeze <4 x i1> %2
  %4 = call i1 @llvm.vector.reduce.or.v4i1(<4 x i1> %3)
  %op.rdx = select i1 %4, i1 true, i1 %.not7
  %op.rdx1 = select i1 poison, i1 true, i1 %op.rdx
  ret i1 %op.rdx1
}
```
cc @alexey-bataev


commit 3ff9d92aae0945daa85ec6f85f05a3aeaaa9f962
Author: Yingwei Zheng <dtcxzyw2333@gmail.com>
Date:   Fri Aug 23 16:06:00 2024 +0800

    [ConstraintElim] Fix miscompilation caused by PR97974 (#105790)

    Fixes https://github.com/llvm/llvm-project/issues/105785.

    (cherry picked from commit 85b6aac7c25f9d2a976a76045ace1e7afebb5965)

diff --git a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
index c31173879af1..37022104d0a9 100644
--- a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
+++ b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
@@ -1464,7 +1464,7 @@ static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info,
     ToRemove.push_back(I);
     return true;
   }
-  if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info)) {
+  if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) {
     I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0));
     ToRemove.push_back(I);
     return true;

opt -passes=constraint-elimination -S %s

define void @pr105785(ptr %p) {
entry:
  br label %for.cond

for.cond:                                         ; preds = %for.cond1, %entry
  %for.ind = phi i32 [ 0, %entry ], [ 1, %for.cond1 ]
  %cmp = icmp eq i32 %for.ind, 0
  br i1 %cmp, label %for.cond1, label %for.end6

for.cond1:                                        ; preds = %for.body3, %for.cond
  %for.ind2 = phi i32 [ %inc, %for.body3 ], [ 0, %for.cond ]
  %cmp2 = icmp ult i32 %for.ind2, 3
  br i1 %cmp2, label %for.body3, label %for.cond

for.body3:                                        ; preds = %for.cond1
  %scmp = call i32 @llvm.scmp.i32.i32(i32 %for.ind, i32 1)
  store i32 %scmp, ptr %p, align 4
  %inc = add nuw nsw i32 %for.ind2, 1
  br label %for.cond1

for.end6:                                         ; preds = %for.cond
  ret void
}

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

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

[ConstraintElim] Miscompilation with cmp intrinsic

Reproducer: https://alive2.llvm.org/ce/z/Tvz2NA
```
; bin/opt -passes=constraint-elimination test.ll -S
define void @h(ptr %p) {
entry:
  br label %for.cond

for.cond:                                         ; preds = %for.cond1, %entry
  %storemerge = phi i32 [ 0, %entry ], [ 1, %for.cond1 ]
  %cmp = icmp eq i32 %storemerge, 0
  br i1 %cmp, label %for.cond1, label %for.end6

for.cond1:                                        ; preds = %for.cond, %for.body3
  %i.0 = phi i32 [ %inc, %for.body3 ], [ 0, %for.cond ]
  %cmp2 = icmp ult i32 %i.0, 3
  br i1 %cmp2, label %for.body3, label %for.cond

for.body3:                                        ; preds = %for.cond1
  %sub.i = tail call range(i32 -1, 2) i32 @llvm.scmp.i32.i32(i32 1, i32 %storemerge)
  store i32 %sub.i, ptr %p, align 4
  %inc = add nuw nsw i32 %i.0, 1
  br label %for.cond1

for.end6:
  ret void
}
```

```
define void @h(ptr %p) {
entry:
  br label %for.cond

for.cond:                                         ; preds = %for.cond1, %entry
  %storemerge = phi i32 [ 0, %entry ], [ 1, %for.cond1 ]
  %cmp = icmp eq i32 %storemerge, 0
  br i1 %cmp, label %for.cond1, label %for.end6

for.cond1:                                        ; preds = %for.body3, %for.cond
  %i.0 = phi i32 [ %inc, %for.body3 ], [ 0, %for.cond ]
  %cmp2 = icmp ult i32 %i.0, 3
  br i1 %cmp2, label %for.body3, label %for.cond

for.body3:                                        ; preds = %for.cond1
  store i32 0, ptr %p, align 4
  %inc = add nuw nsw i32 %i.0, 1
  br label %for.cond1

for.end6:                                         ; preds = %for.cond
  ret void
}
```

The result of scmp should be 1 instead of 0.

Reduced C reproducer:
```
#include <stdio.h>
#include <stdint.h>

int builtin_scmp(int d, int e) { return (d > e) - (d < e); }
int32_t f = 0;
int64_t g = 0;
void h() {
  for (f = 0; f <= 0; f++) {
    int i;
    for (i = 0; i < 3; i++)
      g = builtin_scmp(1, f);
  }
}
int main() {
  h();
  printf("%d\n", (int)g);
  return 0;
}
```

I will post a fix later.


commit cb8d83a77c25e529f58eba17bb1ec76069a04e90
Author: Yingwei Zheng <dtcxzyw2333@gmail.com>
Date:   Tue Feb 6 01:29:38 2024 +0800

    [InstCombine] Fix assertion failure in issue80597 (#80614)

    The assertion in #80597 failed when we were trying to compute known bits
    of a value in an unreachable BB.

    https://github.com/llvm/llvm-project/blob/859b09da08c2a47026ba0a7d2f21b7dca705864d/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp#L749-L810

    In this case, `SignBits` is 30 (deduced from instr info), but `Known` is
    `10000101010111010011110101000?0?00000000000000000000000000000000`
    (deduced from dom cond). Setting high bits of `lshr Known, 1` will lead
    to conflict.

    This patch masks out high bits of `Known.Zero` to address this problem.

    Fixes #80597.

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp b/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
index a8a5f9831e15..79873a9b4cbb 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
@@ -802,6 +802,9 @@ Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
         return InsertNewInstWith(LShr, I->getIterator());
       } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
         Known.One |= HighBits;
+        // SignBits may be out-of-sync with Known.countMinSignBits(). Mask out
+        // high bits of Known.Zero to avoid conflicts.
+        Known.Zero &= ~HighBits;
       }
     } else {
       computeKnownBits(I, Known, Depth, CxtI);

define i64 @pr80597(i1 %cond) {
entry:
  %add = select i1 %cond, i64 0, i64 4294967293
  %add8 = shl i64 %add, 32
  %sext1 = add i64 %add8, 8836839514384105472
  %cmp = icmp ult i64 %sext1, -34359738368
  br i1 %cmp, label %if.then, label %if.else

if.else:                                          ; preds = %entry
  %sext2 = or i64 %add8, 8836839522974040064
  %ashr = ashr i64 %sext2, 1
  ret i64 %ashr

if.then:                                          ; preds = %entry
  ret i64 0
}

llvm crash: Assertion `!LHSKnown.hasConflict() && "Bits known to be one AND zero?"' failed.

llvm crashes in `instcombine`

Bisected to d77067d08a3f56dc2d0e6c95bd2852c943df743a, which was committed by @nikic

Compiler explorer: https://godbolt.org/z/e4jrvf5Wr

```console
% cat reduced.ll
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(i1 %.b.i) {
entry:
  %add.i = select i1 %.b.i, i64 0, i64 4294967293
  %add8.i = shl i64 %add.i, 32
  %sext.2.i = add i64 %add8.i, 8836839514384105472
  %cmp11.2.i = icmp ult i64 %sext.2.i, -34359738368
  br i1 %cmp11.2.i, label %return.loopexit.i, label %for.inc.2.i

for.inc.2.i:                                      ; preds = %entry
  %sext.4.i = or i64 %add8.i, 8836839522974040064
  %conv9.4.i = ashr i64 %sext.4.i, 1
  %cmp11.4.i = icmp ult i64 %conv9.4.i, 0
  br i1 %cmp11.4.i, label %return.loopexit.i, label %return.loopexit.i

return.loopexit.i:                                ; preds = %for.inc.2.i, %for.inc.2.i, %entry
  ret i32 0
}
%
% opt -disable-output -passes=instcombine reduced.ll
opt: /tmp/tmpzoi34eaf/tmporhhh5ti/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp:246: llvm::Value* llvm::InstCombinerImpl::SimplifyDemandedUseBits(llvm::Value*, llvm::APInt, llvm::KnownBits&, unsigned int, llvm::Instruction*): Assertion `!LHSKnown.hasConflict() && "Bits known to be one AND zero?"' failed.
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace.
Stack dump:
0.	Program arguments: /zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/opt -disable-output -passes=instcombine reduced.ll
 #0 0x00007f7698f4558f llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x93858f)
 #1 0x00007f7698f42ab4 SignalHandler(int) Signals.cpp:0:0
 #2 0x00007f7698222090 (/lib/x86_64-linux-gnu/libc.so.6+0x43090)
 #3 0x00007f769822200b raise /build/glibc-wuryBv/glibc-2.31/signal/../sysdeps/unix/sysv/linux/raise.c:51:1
 #4 0x00007f7698201859 abort /build/glibc-wuryBv/glibc-2.31/stdlib/abort.c:81:7
 #5 0x00007f7698201729 get_sysdep_segment_value /build/glibc-wuryBv/glibc-2.31/intl/loadmsgcat.c:509:8
 #6 0x00007f7698201729 _nl_load_domain /build/glibc-wuryBv/glibc-2.31/intl/loadmsgcat.c:970:34
 #7 0x00007f7698212fd6 (/lib/x86_64-linux-gnu/libc.so.6+0x33fd6)
 #8 0x00007f769a44445d llvm::InstCombinerImpl::SimplifyDemandedUseBits(llvm::Value*, llvm::APInt, llvm::KnownBits&, unsigned int, llvm::Instruction*) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x1e3745d)
 #9 0x00007f769a444d25 llvm::InstCombinerImpl::SimplifyDemandedInstructionBits(llvm::Instruction&, llvm::KnownBits&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x1e37d25)
#10 0x00007f769a4459c5 llvm::InstCombinerImpl::SimplifyDemandedInstructionBits(llvm::Instruction&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x1e389c5)
#11 0x00007f769a38cdc3 llvm::InstCombinerImpl::visitOr(llvm::BinaryOperator&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x1d7fdc3)
#12 0x00007f769a3537b1 llvm::InstCombinerImpl::run() (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x1d467b1)
#13 0x00007f769a355002 combineInstructionsOverFunction(llvm::Function&, llvm::InstructionWorklist&, llvm::AAResults*, llvm::AssumptionCache&, llvm::TargetLibraryInfo&, llvm::TargetTransformInfo&, llvm::DominatorTree&, llvm::OptimizationRemarkEmitter&, llvm::BlockFrequencyInfo*, llvm::ProfileSummaryInfo*, llvm::LoopInfo*, llvm::InstCombineOptions const&) (.isra.0) InstructionCombining.cpp:0:0
#14 0x00007f769a355fbb llvm::InstCombinePass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x1d48fbb)
#15 0x00007f769bea5916 llvm::detail::PassModel<llvm::Function, llvm::InstCombinePass, llvm::PreservedAnalyses, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x3898916)
#16 0x00007f769916239d llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0xb5539d)
#17 0x00007f769be9e506 llvm::detail::PassModel<llvm::Function, llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>, llvm::PreservedAnalyses, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x3891506)
#18 0x00007f7699160c2d llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0xb53c2d)
#19 0x00007f769bea5556 llvm::detail::PassModel<llvm::Module, llvm::ModuleToFunctionPassAdaptor, llvm::PreservedAnalyses, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0x3898556)
#20 0x00007f769915eb5d llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/../lib/libLLVM-18git.so+0xb51b5d)
#21 0x000055c7b779e395 llvm::runPassPipeline(llvm::StringRef, llvm::Module&, llvm::TargetMachine*, llvm::TargetLibraryInfoImpl*, llvm::ToolOutputFile*, llvm::ToolOutputFile*, llvm::ToolOutputFile*, llvm::StringRef, llvm::ArrayRef<llvm::PassPlugin>, llvm::opt_tool::OutputKind, llvm::opt_tool::VerifierKind, bool, bool, bool, bool, bool, bool, bool) (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/opt+0x26395)
#22 0x000055c7b7791e8a main (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/opt+0x19e8a)
#23 0x00007f7698203083 __libc_start_main /build/glibc-wuryBv/glibc-2.31/csu/../csu/libc-start.c:342:3
#24 0x000055c7b7792a5e _start (/zdata/shaoli/compilers/ccbuilder-compilers/clang-d77067d08a3f56dc2d0e6c95bd2852c943df743a/bin/opt+0x1aa5e)
[1]    880216 abort       -disable-output -passes=instcombine reduced.ll
%
```

The above test case was reduced from
```C
long a, i;
static long b = -4;
char c;
int d;
static int *e = &d, *h = &d;
static long *f = &b, *g = &b;
int j() {
  for (; a;) {
    c = 0;
    for (; c <= 6; c++) {
      unsigned long k = 1;
      i = -8;
      *h = i >= (int)k + (int)*f + c + 2057487030 + k;
      if (*e)
        break;
    }
    return 0;
  }
  *g = 0;
  return 0;
}
int main() { j(); }
```

Minimal reproduction: https://godbolt.org/z/5bzaqP65P

Reopen this issue to backport the fix to the 18.X release.