[llvm] [ConstraintElim] Add min/max bounds from KnownBits (PR #176607)

Ramkumar Ramachandra via llvm-commits llvm-commits at lists.llvm.org
Fri Jan 23 04:28:43 PST 2026


https://github.com/artagnon updated https://github.com/llvm/llvm-project/pull/176607

>From a01a24da543fc9188a184ddc6403c476920e47da Mon Sep 17 00:00:00 2001
From: Ramkumar Ramachandra <artagnon at tenstorrent.com>
Date: Tue, 20 Jan 2026 02:57:33 +0000
Subject: [PATCH 1/6] [Semilattice] Introduce for dataflow analysis with
 KnownBits

Introduce a semilattice data structure holding KnownBits at each node.
This will allow us to cache and invalidate KnownBits for a Value,
invalidating only dataflow-dependent KnownBits.
---
 llvm/include/llvm/Analysis/Semilattice.h    | 161 +++++++++
 llvm/lib/Analysis/CMakeLists.txt            |   1 +
 llvm/lib/Analysis/Semilattice.cpp           | 108 ++++++
 llvm/unittests/Analysis/CMakeLists.txt      |   1 +
 llvm/unittests/Analysis/SemilatticeTest.cpp | 344 ++++++++++++++++++++
 5 files changed, 615 insertions(+)
 create mode 100644 llvm/include/llvm/Analysis/Semilattice.h
 create mode 100644 llvm/lib/Analysis/Semilattice.cpp
 create mode 100644 llvm/unittests/Analysis/SemilatticeTest.cpp

diff --git a/llvm/include/llvm/Analysis/Semilattice.h b/llvm/include/llvm/Analysis/Semilattice.h
new file mode 100644
index 0000000000000..7a4f2c3b5cd00
--- /dev/null
+++ b/llvm/include/llvm/Analysis/Semilattice.h
@@ -0,0 +1,161 @@
+
+//===- Semilattice.h - A semilattice of KnownBits -------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_SEMILATTICE_H
+#define LLVM_ANALYSIS_SEMILATTICE_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DepthFirstIterator.h"
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/DerivedTypes.h"
+#include "llvm/IR/User.h"
+#include "llvm/IR/Value.h"
+#include "llvm/Support/Allocator.h"
+#include "llvm/Support/KnownBits.h"
+
+namespace llvm {
+class Semilattice;
+class Function;
+
+class SemilatticeNode {
+  friend class Semilattice;
+  PointerIntPair<Value *, 1> ValHasKnownBits;
+  KnownBits Known;
+  SmallVector<SemilatticeNode *, 4> Parents;
+  SmallVector<SemilatticeNode *, 4> Children;
+
+public:
+  SemilatticeNode() : ValHasKnownBits(nullptr, 0) {}
+  SemilatticeNode(Value *V)
+      : ValHasKnownBits(V, 0),
+        Known(V->getType()->getScalarType()->getIntegerBitWidth()) {
+    assert(V && "Attempting to create a node with an empty Value");
+  }
+  SemilatticeNode(const SemilatticeNode &) = delete;
+  SemilatticeNode &operator=(const SemilatticeNode &) = delete;
+
+public:
+  using iterator = SmallVectorImpl<SemilatticeNode *>::iterator;
+  iterator child_begin() { return Children.begin(); } // NOLINT
+  iterator child_end() { return Children.end(); }     // NOLINT
+  iterator_range<iterator> children() {
+    return make_range(child_begin(), child_end());
+  }
+  bool isLeaf() const { return Children.empty(); }
+  bool isRoot() const { return Parents.empty(); }
+
+  bool hasParent(SemilatticeNode *N) const { return is_contained(Parents, N); }
+  Value *getValue() const { return ValHasKnownBits.getPointer(); }
+  bool hasKnownBits() const { return ValHasKnownBits.getInt(); }
+  void setHasKnownBits() { ValHasKnownBits.setInt(1); }
+  KnownBits getKnownBits() const { return Known; }
+  void unionKnownWith(const KnownBits &NewKnown) {
+    Known = Known.unionWith(NewKnown);
+  }
+  void resetKnownBits() { Known.resetAll(); }
+
+  SemilatticeNode *addParent(SemilatticeNode *N) {
+    if (!hasParent(N))
+      Parents.push_back(N);
+    return this;
+  }
+
+  SemilatticeNode *addChild(SemilatticeNode *N) {
+    if (!is_contained(Children, N))
+      Children.push_back(N);
+    return this;
+  }
+
+  SemilatticeNode *rauw(Value *NewV) {
+    ValHasKnownBits.setPointer(NewV);
+    return this;
+  }
+};
+
+class Semilattice {
+  using NodeT = SemilatticeNode;
+
+  static constexpr size_t SlabSize = 8 * sizeof(NodeT);
+  BumpPtrAllocatorImpl<MallocAllocator, SlabSize, /*SizeThreshold=*/SlabSize,
+                       /*GrowthDelay=*/2>
+      NodeAllocator;
+  NodeT *RootNode;
+  DenseMap<Value *, NodeT *> NodeMap;
+  NodeT *create() { return new (NodeAllocator) NodeT(); }
+  NodeT *create(Value *V) { return new (NodeAllocator) NodeT(V); }
+  NodeT *getOrCreate(Value *V) { return NodeMap.lookup_or(V, create(V)); }
+  NodeT *insert(Value *V, NodeT *Parent = nullptr);
+  SmallVector<NodeT *, 4> insert_range(NodeT *Parent, // NOLINT
+                                       ArrayRef<User *> R);
+  void recurseInsertChildren(ArrayRef<NodeT *>);
+  void initialize(ArrayRef<Value *> Roots);
+  void initialize(Function &F);
+
+public:
+  Semilattice(Function &F);
+  Semilattice(const Semilattice &) = delete;
+  Semilattice &operator=(const Semilattice &) = delete;
+  Semilattice(Semilattice &&) = default;
+  Semilattice &operator=(Semilattice &&) = default;
+
+  NodeT *getRootNode() const { return RootNode; }
+  bool empty() const { return RootNode->isLeaf(); }
+  bool contains(const Value *V) const { return NodeMap.contains(V); }
+  NodeT *lookup(const Value *V) const { return NodeMap.lookup_or(V, RootNode); }
+  size_t size() const { return NodeMap.size(); }
+
+  bool hasKnownBits(const Value *V) const { return lookup(V)->hasKnownBits(); }
+  KnownBits getKnownBits(const Value *V) const {
+    return lookup(V)->getKnownBits();
+  }
+  void updateKnownBits(const Value *V, const KnownBits &Known) const {
+    if (!contains(V))
+      return;
+    NodeT *LookupV = lookup(V);
+    LookupV->unionKnownWith(Known);
+    LookupV->setHasKnownBits();
+  }
+  SmallVector<NodeT *> invalidateKnownBits(Value *V);
+  SmallVector<NodeT *> rauw(Value *OldV, Value *NewV);
+
+  void reset(Function &F);
+  void print(raw_ostream &OS) const;
+#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
+  LLVM_DUMP_METHOD void dump() const;
+#endif
+};
+
+template <typename NodeRef> struct NodeGraphTraitsBase {
+  using ChildIteratorType = SemilatticeNode::iterator;
+  using nodes_iterator = df_iterator<NodeRef, df_iterator_default_set<NodeRef>>;
+
+  static NodeRef getEntryNode(NodeRef N) { return N; }
+  static ChildIteratorType child_begin(NodeRef N) { // NOLINT
+    return N->child_begin();
+  }
+  static ChildIteratorType child_end(NodeRef N) {
+    return N->child_end();
+  } // NOLINT
+};
+
+template <>
+struct GraphTraits<SemilatticeNode *>
+    : public NodeGraphTraitsBase<SemilatticeNode *> {
+  using NodeRef = SemilatticeNode *;
+};
+template <>
+struct GraphTraits<const SemilatticeNode *>
+    : public NodeGraphTraitsBase<const SemilatticeNode *> {
+  using NodeRef = const SemilatticeNode *;
+};
+} // end namespace llvm
+
+#endif // LLVM_ANALYSIS_SEMILATTICE_H
diff --git a/llvm/lib/Analysis/CMakeLists.txt b/llvm/lib/Analysis/CMakeLists.txt
index 9abdca099d9fe..15fabab57b8e2 100644
--- a/llvm/lib/Analysis/CMakeLists.txt
+++ b/llvm/lib/Analysis/CMakeLists.txt
@@ -141,6 +141,7 @@ add_llvm_component_library(LLVMAnalysis
   ScalarEvolutionAliasAnalysis.cpp
   ScalarEvolutionDivision.cpp
   ScalarEvolutionNormalization.cpp
+  Semilattice.cpp
   StaticDataProfileInfo.cpp
   StackLifetime.cpp
   StackSafetyAnalysis.cpp
diff --git a/llvm/lib/Analysis/Semilattice.cpp b/llvm/lib/Analysis/Semilattice.cpp
new file mode 100644
index 0000000000000..b4c1b746bd8de
--- /dev/null
+++ b/llvm/lib/Analysis/Semilattice.cpp
@@ -0,0 +1,108 @@
+//===- Semilattice.cpp - A semilattice of KnownBits -----------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Analysis/Semilattice.h"
+#include "llvm/ADT/BreadthFirstIterator.h"
+#include "llvm/ADT/DepthFirstIterator.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SetVector.h"
+#include "llvm/IR/Function.h"
+#include "llvm/Support/Debug.h"
+
+using namespace llvm;
+using NodeT = SemilatticeNode;
+
+void Semilattice::initialize(ArrayRef<Value *> Roots) {
+  auto ToInsert = make_filter_range(Roots, [&](Value *V) {
+    return !contains(V) && V->getType()->isIntOrIntVectorTy();
+  });
+  for (Value *V : ToInsert)
+    recurseInsertChildren(insert(V));
+}
+
+void Semilattice::initialize(Function &F) {
+  SmallVector<Value *> Args(llvm::make_pointer_range(F.args()));
+  initialize(Args);
+  for (BasicBlock &BB : F)
+    if (!BB.empty()) {
+      SmallVector<Value *> Args(llvm::make_pointer_range(
+          make_range(BB.begin(), BB.getFirstNonPHIIt())));
+      initialize(Args);
+    }
+}
+
+Semilattice::Semilattice(Function &F) : RootNode(create()) { initialize(F); }
+
+NodeT *Semilattice::insert(Value *V, NodeT *Parent) {
+  assert(V->getType()->isIntOrIntVectorTy() &&
+         "Cannot insert non-integral types");
+  NodeT *Node = getOrCreate(V);
+  NodeMap.try_emplace(V, Node);
+  NodeT *ParentNode = Parent ? Parent : RootNode;
+  ParentNode->addChild(Node);
+  return Node->addParent(ParentNode);
+}
+
+SmallVector<NodeT *, 4> Semilattice::insert_range(NodeT *Parent,
+                                                  ArrayRef<User *> R) {
+  SmallVector<NodeT *, 4> Ret;
+  auto Users = make_filter_range(R, [&](User *U) {
+    return (!contains(U) || !lookup(U)->hasParent(Parent)) &&
+           U->getType()->isIntOrIntVectorTy();
+  });
+  for (User *U : Users)
+    Ret.push_back(insert(U, Parent));
+  return Ret;
+}
+
+void Semilattice::recurseInsertChildren(ArrayRef<NodeT *> Parents) {
+  for (NodeT *P : Parents)
+    recurseInsertChildren(insert_range(P, to_vector(P->getValue()->users())));
+}
+
+SmallVector<NodeT *> Semilattice::invalidateKnownBits(Value *V) {
+  if (!contains(V))
+    return {};
+  SetVector<NodeT *> ToUpdate;
+  for (NodeT *N : breadth_first(lookup(V))) {
+    N->resetKnownBits();
+    N->setHasKnownBits();
+    ToUpdate.insert(N);
+  }
+  SmallVector<NodeT *> Ret(reverse(ToUpdate.takeVector()));
+  return Ret;
+}
+
+SmallVector<NodeT *> Semilattice::rauw(Value *OldV, Value *NewV) {
+  if (!contains(OldV))
+    return {};
+  NodeMap.emplace_or_assign(NewV, lookup(OldV)->rauw(NewV));
+  NodeMap.erase(OldV);
+  return invalidateKnownBits(NewV);
+}
+
+void Semilattice::reset(Function &F) {
+  NodeAllocator.Reset();
+  NodeMap.clear();
+  RootNode = create();
+  initialize(F);
+}
+
+void Semilattice::print(raw_ostream &OS) const {
+  for (NodeT *N : drop_begin(depth_first(RootNode))) {
+    N->getValue()->print(OS);
+    OS << " | ";
+    if (N->hasKnownBits())
+      N->Known.print(OS);
+    OS << "\n";
+  }
+}
+
+#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
+LLVM_DUMP_METHOD void Semilattice::dump() const { print(dbgs()); }
+#endif
diff --git a/llvm/unittests/Analysis/CMakeLists.txt b/llvm/unittests/Analysis/CMakeLists.txt
index 50bf4539e7984..c64d9ef0d0586 100644
--- a/llvm/unittests/Analysis/CMakeLists.txt
+++ b/llvm/unittests/Analysis/CMakeLists.txt
@@ -51,6 +51,7 @@ set(ANALYSIS_TEST_SOURCES
   ProfileSummaryInfoTest.cpp
   ReplaceWithVecLibTest.cpp
   ScalarEvolutionTest.cpp
+  SemiLatticeTest.cpp
   SparsePropagation.cpp
   TargetLibraryInfoTest.cpp
   TensorSpecTest.cpp
diff --git a/llvm/unittests/Analysis/SemilatticeTest.cpp b/llvm/unittests/Analysis/SemilatticeTest.cpp
new file mode 100644
index 0000000000000..9c8babee0bd4f
--- /dev/null
+++ b/llvm/unittests/Analysis/SemilatticeTest.cpp
@@ -0,0 +1,344 @@
+//===- SemilatticeTest.cpp - Semilattice tests ----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Analysis/Semilattice.h"
+#include "llvm/AsmParser/Parser.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Support/SourceMgr.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+
+namespace {
+static Instruction *findInstructionByName(Function *F, StringRef Name) {
+  for (Instruction &I : instructions(F))
+    if (I.getName() == Name)
+      return &I;
+
+  return nullptr;
+}
+
+class SemilatticeTest : public ::testing::Test {
+protected:
+  void parseAssembly(StringRef Assembly) {
+    SMDiagnostic Error;
+    M = parseAssemblyString(Assembly, Error, Context);
+    ASSERT_TRUE(M);
+
+    F = M->getFunction("test");
+    ASSERT_TRUE(F) << "Test must have a function @test";
+    if (!F)
+      return;
+
+    A = findInstructionByName(F, "A");
+    A2 = findInstructionByName(F, "A2");
+    A3 = findInstructionByName(F, "A3");
+    A4 = findInstructionByName(F, "A4");
+    A5 = findInstructionByName(F, "A5");
+    A6 = findInstructionByName(F, "A6");
+    A7 = findInstructionByName(F, "A7");
+  }
+
+  void SetUp() override { M = std::make_unique<Module>("test", Context); }
+
+  Function *createSimpleFunction(StringRef Name,
+                                 ArrayRef<Type *> ArgTypes = {}) {
+    std::vector<Type *> Types(ArgTypes.begin(), ArgTypes.end());
+    FunctionType *FTy =
+        FunctionType::get(Type::getVoidTy(Context), Types, false);
+    return Function::Create(FTy, Function::ExternalLinkage, Name, M.get());
+  }
+
+  LLVMContext Context;
+  std::unique_ptr<Module> M;
+  Function *F = nullptr;
+  Instruction *A = nullptr, *A2 = nullptr, *A3 = nullptr, *A4 = nullptr,
+              *A5 = nullptr, *A6 = nullptr, *A7 = nullptr;
+};
+
+TEST_F(SemilatticeTest, SimplePrototype) {
+  parseAssembly("define void @test() { ret void }");
+  Semilattice EmptyLat(*F);
+  EXPECT_TRUE(EmptyLat.empty());
+  EXPECT_TRUE(EmptyLat.getRootNode()->isLeaf());
+  EXPECT_TRUE(EmptyLat.getRootNode()->isRoot());
+  EXPECT_EQ(EmptyLat.size(), 0u);
+
+  parseAssembly("define void @test(i32 %arg) { ret void }");
+  Semilattice SingleLat(*F);
+  EXPECT_FALSE(SingleLat.empty());
+  EXPECT_FALSE(SingleLat.getRootNode()->isLeaf());
+  EXPECT_EQ(SingleLat.getKnownBits(&*F->arg_begin()).getBitWidth(), 32u);
+}
+
+TEST_F(SemilatticeTest, IntegerArguments) {
+  parseAssembly("define void @test(i32 %arg1, i64 %arg2) { ret void }");
+  Semilattice TwoArgLat(*F);
+  EXPECT_FALSE(TwoArgLat.empty());
+  auto *ArgIt = F->arg_begin();
+  EXPECT_EQ(TwoArgLat.getKnownBits(&*ArgIt++).getBitWidth(), 32u);
+  EXPECT_EQ(TwoArgLat.getKnownBits(&*ArgIt).getBitWidth(), 64u);
+
+  parseAssembly("define void @test(i32 %intarg, float %floatarg) { ret void }");
+  Semilattice MixedLat(*F);
+  EXPECT_EQ(MixedLat.getKnownBits(&*F->arg_begin()).getBitWidth(), 32u);
+}
+
+TEST_F(SemilatticeTest, Iterators) {
+  parseAssembly("define void @test() { ret void }");
+  Semilattice EmptyLat(*F);
+  SemilatticeNode *EmptyRoot = EmptyLat.getRootNode();
+  EXPECT_TRUE(EmptyRoot->isLeaf());
+  EXPECT_EQ(EmptyRoot->begin(), EmptyRoot->end());
+  EXPECT_EQ(
+      std::distance(EmptyRoot->children().begin(), EmptyRoot->children().end()),
+      0u);
+
+  parseAssembly("define void @test(i32 %arg) { ret void }");
+  Semilattice SingleLat(*F);
+  SemilatticeNode *Root = SingleLat.getRootNode();
+  EXPECT_TRUE(Root->isRoot());
+  EXPECT_FALSE(Root->isLeaf());
+
+  auto *It = Root->begin();
+  EXPECT_NE(It, Root->end());
+  SemilatticeNode *Child = *It++;
+  EXPECT_EQ(It, Root->end());
+  EXPECT_FALSE(Child->isRoot());
+  EXPECT_TRUE(Child->isLeaf());
+
+  size_t ChildCount = 0;
+  for (auto *C : Root->children()) {
+    EXPECT_EQ(C, Child);
+    ++ChildCount;
+  }
+  EXPECT_EQ(ChildCount, 1u);
+}
+
+TEST_F(SemilatticeTest, LookupAndGetKnownBits) {
+  parseAssembly("define void @test(i32 %arg) { ret void }");
+
+  Function *F2 =
+      createSimpleFunction("other_func", {Type::getInt32Ty(Context)});
+  Argument *OtherArg = &*F2->arg_begin();
+
+  Semilattice Lat(*F);
+  EXPECT_FALSE(Lat.contains(OtherArg));
+  EXPECT_EQ(Lat.lookup(OtherArg), Lat.getRootNode());
+
+  Argument *Arg = &*F->arg_begin();
+  EXPECT_TRUE(Lat.getKnownBits(Arg).isUnknown());
+  KnownBits NewKnown(Arg->getType()->getIntegerBitWidth());
+  NewKnown.setAllOnes();
+  Lat.updateKnownBits(Arg, NewKnown);
+  EXPECT_TRUE(Lat.getKnownBits(Arg).isAllOnes());
+
+  Lat.invalidateKnownBits(Arg);
+  EXPECT_TRUE(Lat.getKnownBits(Arg).isUnknown());
+}
+
+TEST_F(SemilatticeTest, RuawAndReset) {
+  parseAssembly("define void @test(i32 %arg1, i32 %arg2) { ret void }");
+
+  Function *F1 = F;
+  Semilattice Lat(*F1);
+  EXPECT_FALSE(Lat.empty());
+  EXPECT_EQ(Lat.size(), 2u);
+
+  Function *F2 =
+      createSimpleFunction("other_func", {Type::getInt32Ty(Context)});
+  Argument *NewArg = &*F2->arg_begin();
+  Argument *OldArg = &*F1->arg_begin();
+
+  EXPECT_TRUE(Lat.contains(OldArg));
+
+  Lat.rauw(OldArg, NewArg);
+  EXPECT_FALSE(Lat.contains(OldArg));
+  EXPECT_TRUE(Lat.contains(NewArg));
+
+  Lat.reset(*F2);
+  EXPECT_EQ(Lat.size(), 1u);
+  EXPECT_FALSE(Lat.contains(&*F1->arg_begin()));
+  EXPECT_TRUE(Lat.contains(&*F2->arg_begin()));
+}
+
+TEST_F(SemilatticeTest, TypeFilteringAndSizing) {
+  parseAssembly("define void @test(i8 %arg1, float %arg2, i16 %arg3, double "
+                "%arg4, i32 %arg5) {\n"
+                "  ret void\n"
+                "}\n");
+
+  Semilattice MixedLat(*F);
+  EXPECT_FALSE(MixedLat.empty());
+  EXPECT_EQ(MixedLat.size(), 3u);
+
+  auto *ArgIt = F->arg_begin();
+  EXPECT_TRUE(MixedLat.contains(&*ArgIt++));
+  EXPECT_FALSE(MixedLat.contains(&*ArgIt++));
+  EXPECT_TRUE(MixedLat.contains(&*ArgIt++));
+  EXPECT_FALSE(MixedLat.contains(&*ArgIt++));
+  EXPECT_TRUE(MixedLat.contains(&*ArgIt));
+
+  parseAssembly("define void @test(i32 %arg0, i32 %arg1, i32 %arg2, i32 %arg3, "
+                "i32 %arg4) {\n"
+                "  ret void\n"
+                "}\n");
+
+  Semilattice ManyArgLat(*F);
+  EXPECT_EQ(ManyArgLat.size(), 5u);
+  for (auto &Arg : F->args()) {
+    EXPECT_TRUE(ManyArgLat.contains(&Arg));
+    EXPECT_EQ(ManyArgLat.getKnownBits(&Arg).getBitWidth(), 32u);
+  }
+}
+
+TEST_F(SemilatticeTest, LeafNodeAnalysis) {
+  parseAssembly("define void @test(i32 %arg) {\n"
+                "  %A = add i32 %arg, 42\n"
+                "  store i32 %A, ptr undef\n"
+                "  ret void\n"
+                "}\n");
+
+  Semilattice Lat(*F);
+  EXPECT_TRUE(Lat.contains(A));
+  EXPECT_TRUE(Lat.lookup(A)->isLeaf());
+  EXPECT_EQ(Lat.getKnownBits(A).getBitWidth(), 32u);
+}
+
+TEST_F(SemilatticeTest, InstructionChain) {
+  parseAssembly("define void @test(i32 %arg) {\n"
+                "  %A = add i32 %arg, 42\n"
+                "  %A2 = mul i32 %A, 2\n"
+                "  %A3 = sub i32 %A2, 10\n"
+                "  store i32 %A3, ptr undef\n"
+                "  ret void\n"
+                "}\n");
+
+  Semilattice Lat(*F);
+  EXPECT_TRUE(Lat.contains(A));
+  EXPECT_TRUE(Lat.contains(A2));
+  EXPECT_TRUE(Lat.contains(A3));
+
+  EXPECT_FALSE(Lat.lookup(A)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A2)->isLeaf());
+  EXPECT_TRUE(Lat.lookup(A3)->isLeaf());
+
+  EXPECT_EQ(Lat.getKnownBits(A).getBitWidth(), 32u);
+  EXPECT_EQ(Lat.getKnownBits(A2).getBitWidth(), 32u);
+  EXPECT_EQ(Lat.getKnownBits(A3).getBitWidth(), 32u);
+}
+
+TEST_F(SemilatticeTest, LongInstructionChain) {
+  parseAssembly("define void @test(i32 %arg) {\n"
+                "  %A = add i32 %arg, 1\n"
+                "  %A2 = add i32 %A, 2\n"
+                "  %A3 = add i32 %A2, 3\n"
+                "  %A4 = add i32 %A3, 4\n"
+                "  %A5 = add i32 %A4, 5\n"
+                "  %A6 = add i32 %A5, 6\n"
+                "  %A7 = add i32 %A6, 7\n"
+                "  store i32 %A7, ptr undef\n"
+                "  ret void\n"
+                "}\n");
+
+  Semilattice Lat(*F);
+
+  EXPECT_TRUE(Lat.contains(A));
+  EXPECT_TRUE(Lat.contains(A2));
+  EXPECT_TRUE(Lat.contains(A3));
+  EXPECT_TRUE(Lat.contains(A4));
+  EXPECT_TRUE(Lat.contains(A5));
+  EXPECT_TRUE(Lat.contains(A6));
+  EXPECT_TRUE(Lat.contains(A7));
+
+  EXPECT_FALSE(Lat.lookup(A)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A2)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A3)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A4)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A5)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A6)->isLeaf());
+  EXPECT_TRUE(Lat.lookup(A7)->isLeaf());
+
+  EXPECT_EQ(Lat.getKnownBits(A7).getBitWidth(), 32u);
+}
+
+TEST_F(SemilatticeTest, ComplexDataflow) {
+  parseAssembly("define void @test(i32 %arg1, i32 %arg2, i32 %arg3) {\n"
+                "  %A = add i32 %arg1, %arg2\n"
+                "  %A2 = mul i32 %arg1, %arg3\n"
+                "  %A3 = add i32 %A, %A2\n"
+                "  %A4 = sub i32 %A3, %arg2\n"
+                "  store i32 %A4, ptr undef\n"
+                "  ret void\n"
+                "}\n");
+
+  Semilattice Lat(*F);
+  auto *ArgIt = F->arg_begin();
+  Argument *Arg1 = &*ArgIt++;
+  Argument *Arg2 = &*ArgIt++;
+  Argument *Arg3 = &*ArgIt;
+
+  EXPECT_TRUE(Lat.contains(Arg1));
+  EXPECT_TRUE(Lat.contains(Arg2));
+  EXPECT_TRUE(Lat.contains(Arg3));
+  EXPECT_TRUE(Lat.contains(A));
+  EXPECT_TRUE(Lat.contains(A2));
+  EXPECT_TRUE(Lat.contains(A3));
+  EXPECT_TRUE(Lat.contains(A4));
+
+  EXPECT_FALSE(Lat.lookup(Arg1)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(Arg2)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(Arg3)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A2)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A3)->isLeaf());
+  EXPECT_TRUE(Lat.lookup(A4)->isLeaf());
+}
+
+TEST_F(SemilatticeTest, BranchAndPhiNodes) {
+  parseAssembly("define void @test(i32 %arg, i1 %cond) {\n"
+                "entry:\n"
+                "  %A = add i32 %arg, 10\n"
+                "  br i1 %cond, label %then, label %else\n"
+                "then:\n"
+                "  %A2 = mul i32 %A, 2\n"
+                "  br label %merge\n"
+                "else:\n"
+                "  %A3 = add i32 %A, 5\n"
+                "  br label %merge\n"
+                "merge:\n"
+                "  %A4 = phi i32 [ %A2, %then ], [ %A3, %else ]\n"
+                "  store i32 %A4, ptr undef\n"
+                "  ret void\n"
+                "}\n");
+
+  Semilattice Lat(*F);
+  auto *ArgIt = F->arg_begin();
+  Argument *IntArg = &*ArgIt++;
+  Argument *CondArg = &*ArgIt;
+
+  EXPECT_TRUE(Lat.contains(IntArg));
+  EXPECT_TRUE(Lat.contains(CondArg));
+  EXPECT_TRUE(Lat.contains(A));
+  EXPECT_TRUE(Lat.contains(A2));
+  EXPECT_TRUE(Lat.contains(A3));
+  EXPECT_TRUE(Lat.contains(A4));
+
+  EXPECT_FALSE(Lat.lookup(IntArg)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A2)->isLeaf());
+  EXPECT_FALSE(Lat.lookup(A3)->isLeaf());
+  EXPECT_TRUE(Lat.lookup(A4)->isLeaf());
+
+  EXPECT_EQ(Lat.getKnownBits(A4).getBitWidth(), 32u);
+}
+} // namespace

>From cf8b9ac5192b141db9dc81ea0dc0d04119e1344b Mon Sep 17 00:00:00 2001
From: Ramkumar Ramachandra <artagnon at tenstorrent.com>
Date: Fri, 23 Jan 2026 01:06:23 +0000
Subject: [PATCH 2/6] [SimplifyQuery, VT] Use Q.CacheLat

---
 llvm/include/llvm/Analysis/SimplifyQuery.h | 5 +++++
 llvm/lib/Analysis/ValueTracking.cpp        | 9 +++++++++
 2 files changed, 14 insertions(+)

diff --git a/llvm/include/llvm/Analysis/SimplifyQuery.h b/llvm/include/llvm/Analysis/SimplifyQuery.h
index d1d34f22a2fc5..f86e24e8800a1 100644
--- a/llvm/include/llvm/Analysis/SimplifyQuery.h
+++ b/llvm/include/llvm/Analysis/SimplifyQuery.h
@@ -10,6 +10,7 @@
 #define LLVM_ANALYSIS_SIMPLIFYQUERY_H
 
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Analysis/Semilattice.h"
 #include "llvm/IR/Operator.h"
 #include "llvm/Support/Compiler.h"
 
@@ -76,6 +77,7 @@ struct SimplifyQuery {
   const Instruction *CxtI = nullptr;
   const DomConditionCache *DC = nullptr;
   const CondContext *CC = nullptr;
+  const Semilattice *CacheLat = nullptr;
 
   // Wrapper to query additional information for instructions like metadata or
   // keywords like nsw, which provides conservative results if those cannot
@@ -90,6 +92,9 @@ struct SimplifyQuery {
   SimplifyQuery(const DataLayout &DL, const Instruction *CXTI = nullptr)
       : DL(DL), CxtI(CXTI) {}
 
+  SimplifyQuery(const DataLayout &DL, const Semilattice *CacheLat)
+      : DL(DL), CacheLat(CacheLat) {}
+
   SimplifyQuery(const DataLayout &DL, const TargetLibraryInfo *TLI,
                 const DominatorTree *DT = nullptr,
                 AssumptionCache *AC = nullptr,
diff --git a/llvm/lib/Analysis/ValueTracking.cpp b/llvm/lib/Analysis/ValueTracking.cpp
index d6fc0889c3efd..4bfa2b010f629 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -2519,6 +2519,12 @@ void computeKnownBits(const Value *V, const APInt &DemandedElts,
   // Start out not knowing anything.
   Known.resetAll();
 
+  // Return cached value, if there is one.
+  if (Q.CacheLat && Q.CacheLat->hasKnownBits(V)) {
+    Known = Q.CacheLat->getKnownBits(V);
+    return;
+  }
+
   // We can't imply anything about undefs.
   if (isa<UndefValue>(V))
     return;
@@ -2561,6 +2567,9 @@ void computeKnownBits(const Value *V, const APInt &DemandedElts,
 
   // Check whether we can determine known bits from context such as assumes.
   computeKnownBitsFromContext(V, Known, Q, Depth);
+
+  if (Q.CacheLat)
+    Q.CacheLat->updateKnownBits(V, Known);
 }
 
 /// Try to detect a recurrence that the value of the induction variable is

>From 0c162642772ed7b9bc396bef8a5d3f9b924b369a Mon Sep 17 00:00:00 2001
From: Ramkumar Ramachandra <artagnon at tenstorrent.com>
Date: Tue, 20 Jan 2026 03:07:58 +0000
Subject: [PATCH 3/6] [ConstraintElim] Pre-commit tests

---
 .../knownbits-min-max-bounds.ll               | 477 ++++++++++++++++++
 1 file changed, 477 insertions(+)
 create mode 100644 llvm/test/Transforms/ConstraintElimination/knownbits-min-max-bounds.ll

diff --git a/llvm/test/Transforms/ConstraintElimination/knownbits-min-max-bounds.ll b/llvm/test/Transforms/ConstraintElimination/knownbits-min-max-bounds.ll
new file mode 100644
index 0000000000000..58b20c6c2365b
--- /dev/null
+++ b/llvm/test/Transforms/ConstraintElimination/knownbits-min-max-bounds.ll
@@ -0,0 +1,477 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt -passes=constraint-elimination -S %s | FileCheck %s
+
+define i1 @masked_value_bounds(i32 %x) {
+; CHECK-LABEL: @masked_value_bounds(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[MASKED:%.*]] = and i32 [[X:%.*]], 15
+; CHECK-NEXT:    [[COND:%.*]] = icmp ult i32 [[MASKED]], 20
+; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[MASKED]], 16
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 false
+;
+entry:
+  %masked = and i32 %x, 15
+  %cond = icmp ult i32 %masked, 20
+  br i1 %cond, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i32 %masked, 16
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ult i32 %masked, 10
+  ret i1 %res
+}
+
+define i1 @and_power_of_two_bounds(i32 %x) {
+; CHECK-LABEL: @and_power_of_two_bounds(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[AND:%.*]] = and i32 [[X:%.*]], 127
+; CHECK-NEXT:    [[COND:%.*]] = icmp sgt i32 [[AND]], -1
+; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp slt i32 [[AND]], 128
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    [[RES:%.*]] = icmp slt i32 [[AND]], 64
+; CHECK-NEXT:    ret i1 [[RES]]
+;
+entry:
+  %and = and i32 %x, 127
+  %cond = icmp sgt i32 %and, -1
+  br i1 %cond, label %then, label %else
+
+then:
+  %cmp.redundant = icmp slt i32 %and, 128
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp slt i32 %and, 64
+  ret i1 %res
+}
+
+define i1 @shift_bounds(i8 %x) {
+; CHECK-LABEL: @shift_bounds(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[BOUNDED:%.*]] = and i8 [[X:%.*]], 7
+; CHECK-NEXT:    [[SHL:%.*]] = shl i8 [[BOUNDED]], 2
+; CHECK-NEXT:    [[COND:%.*]] = icmp ult i8 [[SHL]], 40
+; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i8 [[SHL]], 32
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 false
+;
+entry:
+  %bounded = and i8 %x, 7
+  %shl = shl i8 %bounded, 2
+  %cond = icmp ult i8 %shl, 40
+  br i1 %cond, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i8 %shl, 32
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp eq i8 %shl, 0
+  ret i1 %res
+}
+
+define i1 @or_minimum_bounds(i16 %x) {
+; CHECK-LABEL: @or_minimum_bounds(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[OR:%.*]] = or i16 [[X:%.*]], 48
+; CHECK-NEXT:    [[COND:%.*]] = icmp ugt i16 [[OR]], 40
+; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ugt i16 [[OR]], 47
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %or = or i16 %x, 48
+  %cond = icmp ugt i16 %or, 40
+  br i1 %cond, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ugt i16 %or, 47
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ult i16 %or, 48
+  ret i1 %res
+}
+
+define i1 @nested_and_operations(i32 %x) {
+; CHECK-LABEL: @nested_and_operations(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[MASK1:%.*]] = and i32 [[X:%.*]], 255
+; CHECK-NEXT:    [[MASK2:%.*]] = and i32 [[MASK1]], 63
+; CHECK-NEXT:    [[COND:%.*]] = icmp ult i32 [[MASK2]], 70
+; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[MASK2]], 64
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %mask1 = and i32 %x, 255
+  %mask2 = and i32 %mask1, 63
+  %cond = icmp ult i32 %mask2, 70
+  br i1 %cond, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i32 %mask2, 64
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ugt i32 %mask2, 63
+  ret i1 %res
+}
+
+define i1 @right_shift_bounds(i16 %x) {
+; CHECK-LABEL: @right_shift_bounds(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[LARGE:%.*]] = or i16 [[X:%.*]], 512
+; CHECK-NEXT:    [[SHR:%.*]] = lshr i16 [[LARGE]], 3
+; CHECK-NEXT:    [[COND:%.*]] = icmp ugt i16 [[SHR]], 50
+; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ugt i16 [[SHR]], 63
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %large = or i16 %x, 512
+  %shr = lshr i16 %large, 3
+  %cond = icmp ugt i16 %shr, 50
+  br i1 %cond, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ugt i16 %shr, 63
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ult i16 %shr, 64
+  ret i1 %res
+}
+
+define i1 @multiply_bounds(i8 %x) {
+; CHECK-LABEL: @multiply_bounds(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[SMALL:%.*]] = and i8 [[X:%.*]], 3
+; CHECK-NEXT:    [[MUL:%.*]] = mul i8 [[SMALL]], 5
+; CHECK-NEXT:    [[COND:%.*]] = icmp ult i8 [[MUL]], 20
+; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i8 [[MUL]], 16
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %small = and i8 %x, 3
+  %mul = mul i8 %small, 5
+  %cond = icmp ult i8 %mul, 20
+  br i1 %cond, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i8 %mul, 16
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ugt i8 %mul, 15
+  ret i1 %res
+}
+
+define i1 @select_bounded_values(i32 %x, i1 %cond) {
+; CHECK-LABEL: @select_bounded_values(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[A:%.*]] = and i32 [[X:%.*]], 7
+; CHECK-NEXT:    [[B:%.*]] = and i32 [[X]], 15
+; CHECK-NEXT:    [[SEL:%.*]] = select i1 [[COND:%.*]], i32 [[A]], i32 [[B]]
+; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i32 [[SEL]], 20
+; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[SEL]], 16
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %a = and i32 %x, 7
+  %b = and i32 %x, 15
+  %sel = select i1 %cond, i32 %a, i32 %b
+  %cmp = icmp ult i32 %sel, 20
+  br i1 %cmp, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i32 %sel, 16
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ugt i32 %sel, 15
+  ret i1 %res
+}
+
+define i1 @phi_bounded_values(i32 %x, i1 %cond) {
+; CHECK-LABEL: @phi_bounded_values(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    br i1 [[COND:%.*]], label [[PATH1:%.*]], label [[PATH2:%.*]]
+; CHECK:       path1:
+; CHECK-NEXT:    [[VAL1:%.*]] = and i32 [[X:%.*]], 15
+; CHECK-NEXT:    br label [[MERGE:%.*]]
+; CHECK:       path2:
+; CHECK-NEXT:    [[VAL2:%.*]] = and i32 [[X]], 7
+; CHECK-NEXT:    br label [[MERGE]]
+; CHECK:       merge:
+; CHECK-NEXT:    [[PHI:%.*]] = phi i32 [ [[VAL1]], [[PATH1]] ], [ [[VAL2]], [[PATH2]] ]
+; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i32 [[PHI]], 20
+; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[PHI]], 16
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  br i1 %cond, label %path1, label %path2
+
+path1:
+  %val1 = and i32 %x, 15
+  br label %merge
+
+path2:
+  %val2 = and i32 %x, 7
+  br label %merge
+
+merge:
+  %phi = phi i32 [ %val1, %path1 ], [ %val2, %path2 ]
+  %cmp = icmp ult i32 %phi, 20
+  br i1 %cmp, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i32 %phi, 16
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ugt i32 %phi, 15
+  ret i1 %res
+}
+
+define i1 @phi_loop_bounded(i32 %n) {
+; CHECK-LABEL: @phi_loop_bounded(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[BOUND_N:%.*]] = and i32 [[N:%.*]], 7
+; CHECK-NEXT:    br label [[LOOP:%.*]]
+; CHECK:       loop:
+; CHECK-NEXT:    [[I:%.*]] = phi i32 [ 0, [[ENTRY:%.*]] ], [ [[I_NEXT:%.*]], [[LOOP]] ]
+; CHECK-NEXT:    [[I_NEXT]] = add nuw nsw i32 [[I]], 1
+; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i32 [[I_NEXT]], [[BOUND_N]]
+; CHECK-NEXT:    br i1 [[CMP]], label [[LOOP]], label [[EXIT:%.*]]
+; CHECK:       exit:
+; CHECK-NEXT:    [[FINAL_CMP:%.*]] = icmp ult i32 [[I]], 10
+; CHECK-NEXT:    br i1 [[FINAL_CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[I]], 8
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %bound.n = and i32 %n, 7
+  br label %loop
+
+loop:
+  %i = phi i32 [ 0, %entry ], [ %i.next, %loop ]
+  %i.next = add nuw nsw i32 %i, 1
+  %cmp = icmp ult i32 %i.next, %bound.n
+  br i1 %cmp, label %loop, label %exit
+
+exit:
+  %final.cmp = icmp ult i32 %i, 10
+  br i1 %final.cmp, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i32 %i, 8
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ugt i32 %i, 7
+  ret i1 %res
+}
+
+define i1 @zext_bounds_i8_to_i32(i8 %x) {
+; CHECK-LABEL: @zext_bounds_i8_to_i32(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[SMALL:%.*]] = and i8 [[X:%.*]], 31
+; CHECK-NEXT:    [[EXTENDED:%.*]] = zext i8 [[SMALL]] to i32
+; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i32 [[EXTENDED]], 40
+; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[EXTENDED]], 32
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %small = and i8 %x, 31
+  %extended = zext i8 %small to i32
+  %cmp = icmp ult i32 %extended, 40
+  br i1 %cmp, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i32 %extended, 32
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ugt i32 %extended, 31
+  ret i1 %res
+}
+
+define i1 @sext_bounds_negative_check(i8 %x) {
+; CHECK-LABEL: @sext_bounds_negative_check(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[SMALL:%.*]] = and i8 [[X:%.*]], 63
+; CHECK-NEXT:    [[EXTENDED:%.*]] = sext i8 [[SMALL]] to i32
+; CHECK-NEXT:    [[CMP:%.*]] = icmp sgt i32 [[EXTENDED]], -1
+; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    ret i1 true
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %small = and i8 %x, 63
+  %extended = sext i8 %small to i32
+  %cmp = icmp sgt i32 %extended, -1
+  br i1 %cmp, label %then, label %else
+
+then:
+  %cmp.redundant = icmp sgt i32 %extended, -1
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp slt i32 %extended, 0
+  ret i1 %res
+}
+
+define i1 @zext_from_i1(i1 %flag) {
+; CHECK-LABEL: @zext_from_i1(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[EXTENDED:%.*]] = zext i1 [[FLAG:%.*]] to i32
+; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i32 [[EXTENDED]], 5
+; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[EXTENDED]], 2
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %extended = zext i1 %flag to i32
+  %cmp = icmp ult i32 %extended, 5
+  br i1 %cmp, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i32 %extended, 2
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ugt i32 %extended, 1
+  ret i1 %res
+}
+
+define i1 @trunc_bounds_i32_to_i8(i32 %x) {
+; CHECK-LABEL: @trunc_bounds_i32_to_i8(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[SMALL:%.*]] = and i32 [[X:%.*]], 63
+; CHECK-NEXT:    [[TRUNCATED:%.*]] = trunc i32 [[SMALL]] to i8
+; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i8 [[TRUNCATED]], 100
+; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i8 [[TRUNCATED]], 64
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %small = and i32 %x, 63
+  %truncated = trunc i32 %small to i8
+  %cmp = icmp ult i8 %truncated, 100
+  br i1 %cmp, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i8 %truncated, 64
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ugt i8 %truncated, 63
+  ret i1 %res
+}
+
+define i1 @trunc_nsw_bounds(i32 %x) {
+; CHECK-LABEL: @trunc_nsw_bounds(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[MASKED:%.*]] = and i32 [[X:%.*]], 127
+; CHECK-NEXT:    [[TRUNC:%.*]] = trunc nsw i32 [[MASKED]] to i8
+; CHECK-NEXT:    [[CMP:%.*]] = icmp slt i8 [[TRUNC]], 100
+; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp sgt i8 [[TRUNC]], -1
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 false
+;
+entry:
+  %masked = and i32 %x, 127
+  %trunc = trunc nsw i32 %masked to i8
+  %cmp = icmp slt i8 %trunc, 100
+  br i1 %cmp, label %then, label %else
+
+then:
+  %cmp.redundant = icmp sgt i8 %trunc, -1
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp slt i8 %trunc, 0
+  ret i1 %res
+}
+
+define i1 @trunc_combined_with_operations(i16 %x) {
+; CHECK-LABEL: @trunc_combined_with_operations(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:    [[BOUNDED:%.*]] = and i16 [[X:%.*]], 15
+; CHECK-NEXT:    [[SHIFTED:%.*]] = shl nuw nsw i16 [[BOUNDED]], 1
+; CHECK-NEXT:    [[TRUNC:%.*]] = trunc i16 [[SHIFTED]] to i8
+; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i8 [[TRUNC]], 40
+; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:       then:
+; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i8 [[TRUNC]], 31
+; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK:       else:
+; CHECK-NEXT:    ret i1 true
+;
+entry:
+  %bounded = and i16 %x, 15
+  %shifted = shl nuw nsw i16 %bounded, 1
+  %trunc = trunc i16 %shifted to i8
+  %cmp = icmp ult i8 %trunc, 40
+  br i1 %cmp, label %then, label %else
+
+then:
+  %cmp.redundant = icmp ult i8 %trunc, 31
+  ret i1 %cmp.redundant
+
+else:
+  %res = icmp ugt i8 %trunc, 30
+  ret i1 %res
+}

>From 4b61d1cc657df0ed1ffcbc51e4a30c1b6c7a802e Mon Sep 17 00:00:00 2001
From: Ramkumar Ramachandra <artagnon at tenstorrent.com>
Date: Sat, 17 Jan 2026 22:49:52 +0000
Subject: [PATCH 4/6] [ConstraintElim] Add min/max bounds from KnownBits

Co-authored-by: John Regehr <regehr at cs.utah.edu>
---
 .../Scalar/ConstraintElimination.cpp          | 154 ++++++++++++------
 .../knownbits-min-max-bounds.ll               |  43 ++---
 2 files changed, 115 insertions(+), 82 deletions(-)

diff --git a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
index 480ab8b822595..b3af55472a299 100644
--- a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
+++ b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
@@ -12,6 +12,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
+#include "llvm/ADT/BreadthFirstIterator.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallVector.h"
@@ -23,6 +24,7 @@
 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
 #include "llvm/Analysis/ScalarEvolution.h"
 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
+#include "llvm/Analysis/Semilattice.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/DataLayout.h"
@@ -248,6 +250,31 @@ struct ConstraintTy {
   bool IsNe = false;
 };
 
+class KnownBitsUpdater {
+  const DataLayout &DL;
+  Semilattice CacheLat;
+
+  template <typename ContainterT> void compute(ContainterT Nodes) const {
+    for (auto *N : Nodes)
+      computeKnownBits(N->getValue(), {DL, &CacheLat});
+  }
+
+public:
+  KnownBitsUpdater(Function &F) : DL(F.getDataLayout()), CacheLat(F) {
+    SetVector<SemilatticeNode *> BFSNodes;
+    for (auto *N : drop_begin(breadth_first(CacheLat.getRootNode())))
+      BFSNodes.insert(N);
+    compute(reverse(BFSNodes));
+  }
+  void rauw(Value *OldV, Value *NewV) {
+    OldV->replaceAllUsesWith(NewV);
+    compute(CacheLat.rauw(OldV, NewV));
+  }
+  KnownBits getKnownBits(const Value *V) const {
+    return CacheLat.getKnownBits(V);
+  }
+};
+
 /// Wrapper encapsulating separate constraint systems and corresponding value
 /// mappings for both unsigned and signed information. Facts are added to and
 /// conditions are checked against the corresponding system depending on the
@@ -262,8 +289,9 @@ class ConstraintInfo {
   const DataLayout &DL;
 
 public:
-  ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
-      : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {
+  ConstraintInfo(Function &F, ArrayRef<Value *> FunctionArgs)
+      : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(F.getDataLayout()),
+        KBUpdater(F) {
     auto &Value2Index = getValue2Index(false);
     // Add Arg > -1 constraints to unsigned system for all function arguments.
     for (Value *Arg : FunctionArgs) {
@@ -322,6 +350,8 @@ class ConstraintInfo {
                              unsigned NumIn, unsigned NumOut,
                              SmallVectorImpl<StackEntry> &DFSInStack);
 
+  KnownBitsUpdater KBUpdater;
+
 private:
   /// Adds facts into constraint system. \p ForceSignedSystem can be set when
   /// the \p Pred is eq/ne, and signed constraint system is used when it's
@@ -335,13 +365,9 @@ class ConstraintInfo {
 struct DecompEntry {
   int64_t Coefficient;
   Value *Variable;
-  /// True if the variable is known positive in the current constraint.
-  bool IsKnownNonNegative;
 
-  DecompEntry(int64_t Coefficient, Value *Variable,
-              bool IsKnownNonNegative = false)
-      : Coefficient(Coefficient), Variable(Variable),
-        IsKnownNonNegative(IsKnownNonNegative) {}
+  DecompEntry(int64_t Coefficient, Value *Variable)
+      : Coefficient(Coefficient), Variable(Variable) {}
 };
 
 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
@@ -350,9 +376,7 @@ struct Decomposition {
   SmallVector<DecompEntry, 3> Vars;
 
   Decomposition(int64_t Offset) : Offset(Offset) {}
-  Decomposition(Value *V, bool IsKnownNonNegative = false) {
-    Vars.emplace_back(1, V, IsKnownNonNegative);
-  }
+  Decomposition(Value *V) { Vars.emplace_back(1, V); }
   Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
       : Offset(Offset), Vars(Vars) {}
 
@@ -522,8 +546,6 @@ static Decomposition decompose(Value *V,
   if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
     return V;
 
-  bool IsKnownNonNegative = false;
-
   // Decompose \p V used with a signed predicate.
   if (IsSigned) {
     if (auto *CI = dyn_cast<ConstantInt>(V)) {
@@ -537,7 +559,6 @@ static Decomposition decompose(Value *V,
       V = Op0;
     else if (match(V, m_NNegZExt(m_Value(Op0)))) {
       V = Op0;
-      IsKnownNonNegative = true;
     } else if (match(V, m_NSWTrunc(m_Value(Op0)))) {
       if (Op0->getType()->getScalarSizeInBits() <= 64)
         V = Op0;
@@ -546,7 +567,7 @@ static Decomposition decompose(Value *V,
     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
       if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
         return *Decomp;
-      return {V, IsKnownNonNegative};
+      return V;
     }
 
     if (match(V, m_NSWSub(m_Value(Op0), m_Value(Op1)))) {
@@ -554,7 +575,7 @@ static Decomposition decompose(Value *V,
       auto ResB = decompose(Op1, Preconditions, IsSigned, DL);
       if (!ResA.sub(ResB))
         return ResA;
-      return {V, IsKnownNonNegative};
+      return V;
     }
 
     ConstantInt *CI;
@@ -562,7 +583,7 @@ static Decomposition decompose(Value *V,
       auto Result = decompose(Op0, Preconditions, IsSigned, DL);
       if (!Result.mul(CI->getSExtValue()))
         return Result;
-      return {V, IsKnownNonNegative};
+      return V;
     }
 
     // (shl nsw x, shift) is (mul nsw x, (1<<shift)), with the exception of
@@ -574,11 +595,11 @@ static Decomposition decompose(Value *V,
         auto Result = decompose(Op0, Preconditions, IsSigned, DL);
         if (!Result.mul(int64_t(1) << Shift))
           return Result;
-        return {V, IsKnownNonNegative};
+        return V;
       }
     }
 
-    return {V, IsKnownNonNegative};
+    return V;
   }
 
   if (auto *CI = dyn_cast<ConstantInt>(V)) {
@@ -589,7 +610,6 @@ static Decomposition decompose(Value *V,
 
   Value *Op0;
   if (match(V, m_ZExt(m_Value(Op0)))) {
-    IsKnownNonNegative = true;
     V = Op0;
   } else if (match(V, m_SExt(m_Value(Op0)))) {
     V = Op0;
@@ -611,7 +631,7 @@ static Decomposition decompose(Value *V,
   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
     if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
       return *Decomp;
-    return {V, IsKnownNonNegative};
+    return V;
   }
 
   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
@@ -621,7 +641,7 @@ static Decomposition decompose(Value *V,
         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
     if (auto Decomp = MergeResults(Op0, CI, true))
       return *Decomp;
-    return {V, IsKnownNonNegative};
+    return V;
   }
 
   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
@@ -634,23 +654,23 @@ static Decomposition decompose(Value *V,
 
     if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
       return *Decomp;
-    return {V, IsKnownNonNegative};
+    return V;
   }
 
   // Decompose or as an add if there are no common bits between the operands.
   if (match(V, m_DisjointOr(m_Value(Op0), m_ConstantInt(CI)))) {
     if (auto Decomp = MergeResults(Op0, CI, IsSigned))
       return *Decomp;
-    return {V, IsKnownNonNegative};
+    return V;
   }
 
   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
     if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64)
-      return {V, IsKnownNonNegative};
+      return V;
     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
     if (!Result.mul(int64_t{1} << CI->getSExtValue()))
       return Result;
-    return {V, IsKnownNonNegative};
+    return V;
   }
 
   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
@@ -658,7 +678,7 @@ static Decomposition decompose(Value *V,
     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
     if (!Result.mul(CI->getSExtValue()))
       return Result;
-    return {V, IsKnownNonNegative};
+    return V;
   }
 
   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) {
@@ -666,10 +686,23 @@ static Decomposition decompose(Value *V,
     auto ResB = decompose(Op1, Preconditions, IsSigned, DL);
     if (!ResA.sub(ResB))
       return ResA;
-    return {V, IsKnownNonNegative};
+    return V;
   }
 
-  return {V, IsKnownNonNegative};
+  return V;
+}
+
+static std::pair<int64_t, int64_t>
+getBoundsFromKnownBits(const KnownBits &Known, bool IsSigned) {
+  int64_t Min = MinSignedConstraintValue;
+  int64_t Max = MaxConstraintValue;
+  if (Known.isUnknown())
+    return {Min, Max};
+  Min = IsSigned ? Known.getSignedMinValue().getSExtValue()
+                 : Known.getMinValue().getZExtValue();
+  Max = IsSigned ? Known.getMaxValue().getSExtValue()
+                 : Known.getSignedMaxValue().getZExtValue();
+  return {Min, Max};
 }
 
 ConstraintTy
@@ -758,22 +791,18 @@ ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
       IsSigned, IsEq, IsNe);
   // Collect variables that are known to be positive in all uses in the
   // constraint.
-  SmallDenseMap<Value *, bool> KnownNonNegativeVariables;
+  SmallPtrSet<Value *, 8> UniqVariables;
   auto &R = Res.Coefficients;
   for (const auto &KV : VariablesA) {
     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
-    auto I =
-        KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
-    I.first->second &= KV.IsKnownNonNegative;
+    UniqVariables.insert(KV.Variable);
   }
 
   for (const auto &KV : VariablesB) {
     auto &Coeff = R[GetOrAddIndex(KV.Variable)];
     if (SubOverflow(Coeff, KV.Coefficient, Coeff))
       return {};
-    auto I =
-        KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
-    I.first->second &= KV.IsKnownNonNegative;
+    UniqVariables.insert(KV.Variable);
   }
 
   int64_t OffsetSum;
@@ -796,14 +825,30 @@ ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
     NewIndexMap.erase(RemovedV);
   }
 
-  // Add extra constraints for variables that are known positive.
-  for (auto &KV : KnownNonNegativeVariables) {
-    if (!KV.second ||
-        (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first)))
+  // Add extra constraints for Min and Max values of variables from KnownBits.
+  for (Value *V : UniqVariables) {
+    if (match(V, m_Constant()) || !V->getType()->isIntegerTy() ||
+        V->getType()->getIntegerBitWidth() > 64)
       continue;
-    auto &C = Res.ExtraInfo.emplace_back(
-        Value2Index.size() + NewVariables.size() + 1, 0);
-    C[GetOrAddIndex(KV.first)] = -1;
+    if (!Value2Index.contains(V) && !NewIndexMap.contains(V))
+      continue;
+
+    const KnownBits &Known = KBUpdater.getKnownBits(V);
+    auto [Min, Max] = getBoundsFromKnownBits(Known, IsSigned);
+
+    if (Min != MinSignedConstraintValue) {
+      auto &C = Res.ExtraInfo.emplace_back(
+          Value2Index.size() + NewVariables.size() + 1, 0);
+      C[0] = -Min;
+      C[GetOrAddIndex(V)] = -1;
+    }
+
+    if (Max != MaxConstraintValue) {
+      auto &C = Res.ExtraInfo.emplace_back(
+          Value2Index.size() + NewVariables.size() + 1, 0);
+      C[0] = Max;
+      C[GetOrAddIndex(V)] = 1;
+    }
   }
   return Res;
 }
@@ -1608,7 +1653,7 @@ static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info,
                                   SmallVectorImpl<Instruction *> &ToRemove) {
   auto ReplaceMinMaxWithOperand = [&](MinMaxIntrinsic *MinMax, bool UseLHS) {
     // TODO: generate reproducer for min/max.
-    MinMax->replaceAllUsesWith(MinMax->getOperand(UseLHS ? 0 : 1));
+    Info.KBUpdater.rauw(MinMax, MinMax->getOperand(UseLHS ? 0 : 1));
     ToRemove.push_back(MinMax);
     return true;
   };
@@ -1629,17 +1674,17 @@ static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info,
   Value *LHS = I->getOperand(0);
   Value *RHS = I->getOperand(1);
   if (checkCondition(I->getGTPredicate(), LHS, RHS, I, Info).value_or(false)) {
-    I->replaceAllUsesWith(ConstantInt::get(I->getType(), 1));
+    Info.KBUpdater.rauw(I, ConstantInt::get(I->getType(), 1));
     ToRemove.push_back(I);
     return true;
   }
   if (checkCondition(I->getLTPredicate(), LHS, RHS, I, Info).value_or(false)) {
-    I->replaceAllUsesWith(ConstantInt::getSigned(I->getType(), -1));
+    Info.KBUpdater.rauw(I, ConstantInt::getSigned(I->getType(), -1));
     ToRemove.push_back(I);
     return true;
   }
   if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) {
-    I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0));
+    Info.KBUpdater.rauw(I, ConstantInt::get(I->getType(), 0));
     ToRemove.push_back(I);
     return true;
   }
@@ -1720,10 +1765,10 @@ static bool checkOrAndOpImpliedByOther(
           checkCondition(CmpToCheck->getPredicate(), CmpToCheck->getOperand(0),
                          CmpToCheck->getOperand(1), CmpToCheck, Info)) {
     if (IsOr == *ImpliedCondition)
-      JoinOp->replaceAllUsesWith(
-          ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
+      Info.KBUpdater.rauw(
+          JoinOp, ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
     else
-      JoinOp->replaceAllUsesWith(JoinOp->getOperand(OtherOpIdx));
+      Info.KBUpdater.rauw(JoinOp, JoinOp->getOperand(OtherOpIdx));
     ToRemove.push_back(JoinOp);
     return true;
   }
@@ -1804,6 +1849,7 @@ void ConstraintInfo::addFactImpl(CmpInst::Predicate Pred, Value *A, Value *B,
 }
 
 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
+                                   ConstraintInfo &Info,
                                    SmallVectorImpl<Instruction *> &ToRemove) {
   bool Changed = false;
   IRBuilder<> Builder(II->getParent(), II->getIterator());
@@ -1812,10 +1858,10 @@ static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
     if (match(U, m_ExtractValue<0>(m_Value()))) {
       if (!Sub)
         Sub = Builder.CreateSub(A, B);
-      U->replaceAllUsesWith(Sub);
+      Info.KBUpdater.rauw(U, Sub);
       Changed = true;
     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
-      U->replaceAllUsesWith(Builder.getFalse());
+      Info.KBUpdater.rauw(U, Builder.getFalse());
       Changed = true;
     } else
       continue;
@@ -1858,7 +1904,7 @@ tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
         !DoesConditionHold(CmpInst::ICMP_SGE, B,
                            ConstantInt::get(A->getType(), 0), Info))
       return false;
-    Changed = replaceSubOverflowUses(II, A, B, ToRemove);
+    Changed = replaceSubOverflowUses(II, A, B, Info, ToRemove);
   }
   return Changed;
 }
@@ -1870,7 +1916,7 @@ static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI,
   bool Changed = false;
   DT.updateDFSNumbers();
   SmallVector<Value *> FunctionArgs(llvm::make_pointer_range(F.args()));
-  ConstraintInfo Info(F.getDataLayout(), FunctionArgs);
+  ConstraintInfo Info(F, FunctionArgs);
   State S(DT, LI, SE, TLI);
   std::unique_ptr<Module> ReproducerModule(
       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
diff --git a/llvm/test/Transforms/ConstraintElimination/knownbits-min-max-bounds.ll b/llvm/test/Transforms/ConstraintElimination/knownbits-min-max-bounds.ll
index 58b20c6c2365b..e96e3df06c5bf 100644
--- a/llvm/test/Transforms/ConstraintElimination/knownbits-min-max-bounds.ll
+++ b/llvm/test/Transforms/ConstraintElimination/knownbits-min-max-bounds.ll
@@ -8,10 +8,9 @@ define i1 @masked_value_bounds(i32 %x) {
 ; CHECK-NEXT:    [[COND:%.*]] = icmp ult i32 [[MASKED]], 20
 ; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[MASKED]], 16
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
-; CHECK-NEXT:    ret i1 false
+; CHECK-NEXT:    ret i1 true
 ;
 entry:
   %masked = and i32 %x, 15
@@ -34,8 +33,7 @@ define i1 @and_power_of_two_bounds(i32 %x) {
 ; CHECK-NEXT:    [[COND:%.*]] = icmp sgt i32 [[AND]], -1
 ; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp slt i32 [[AND]], 128
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    [[RES:%.*]] = icmp slt i32 [[AND]], 64
 ; CHECK-NEXT:    ret i1 [[RES]]
@@ -62,10 +60,9 @@ define i1 @shift_bounds(i8 %x) {
 ; CHECK-NEXT:    [[COND:%.*]] = icmp ult i8 [[SHL]], 40
 ; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i8 [[SHL]], 32
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
-; CHECK-NEXT:    ret i1 false
+; CHECK-NEXT:    ret i1 true
 ;
 entry:
   %bounded = and i8 %x, 7
@@ -89,8 +86,7 @@ define i1 @or_minimum_bounds(i16 %x) {
 ; CHECK-NEXT:    [[COND:%.*]] = icmp ugt i16 [[OR]], 40
 ; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ugt i16 [[OR]], 47
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 true
 ;
@@ -116,8 +112,7 @@ define i1 @nested_and_operations(i32 %x) {
 ; CHECK-NEXT:    [[COND:%.*]] = icmp ult i32 [[MASK2]], 70
 ; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[MASK2]], 64
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 true
 ;
@@ -144,8 +139,7 @@ define i1 @right_shift_bounds(i16 %x) {
 ; CHECK-NEXT:    [[COND:%.*]] = icmp ugt i16 [[SHR]], 50
 ; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ugt i16 [[SHR]], 63
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 true
 ;
@@ -172,8 +166,7 @@ define i1 @multiply_bounds(i8 %x) {
 ; CHECK-NEXT:    [[COND:%.*]] = icmp ult i8 [[MUL]], 20
 ; CHECK-NEXT:    br i1 [[COND]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i8 [[MUL]], 16
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 true
 ;
@@ -201,8 +194,7 @@ define i1 @select_bounded_values(i32 %x, i1 %cond) {
 ; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i32 [[SEL]], 20
 ; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[SEL]], 16
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 true
 ;
@@ -237,8 +229,7 @@ define i1 @phi_bounded_values(i32 %x, i1 %cond) {
 ; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i32 [[PHI]], 20
 ; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[PHI]], 16
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 true
 ;
@@ -317,8 +308,7 @@ define i1 @zext_bounds_i8_to_i32(i8 %x) {
 ; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i32 [[EXTENDED]], 40
 ; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i32 [[EXTENDED]], 32
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 true
 ;
@@ -398,8 +388,7 @@ define i1 @trunc_bounds_i32_to_i8(i32 %x) {
 ; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i8 [[TRUNCATED]], 100
 ; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i8 [[TRUNCATED]], 64
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 true
 ;
@@ -426,8 +415,7 @@ define i1 @trunc_nsw_bounds(i32 %x) {
 ; CHECK-NEXT:    [[CMP:%.*]] = icmp slt i8 [[TRUNC]], 100
 ; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp sgt i8 [[TRUNC]], -1
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 false
 ;
@@ -455,8 +443,7 @@ define i1 @trunc_combined_with_operations(i16 %x) {
 ; CHECK-NEXT:    [[CMP:%.*]] = icmp ult i8 [[TRUNC]], 40
 ; CHECK-NEXT:    br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
 ; CHECK:       then:
-; CHECK-NEXT:    [[CMP_REDUNDANT:%.*]] = icmp ult i8 [[TRUNC]], 31
-; CHECK-NEXT:    ret i1 [[CMP_REDUNDANT]]
+; CHECK-NEXT:    ret i1 true
 ; CHECK:       else:
 ; CHECK-NEXT:    ret i1 true
 ;

>From dce39488812aebc1acdbb167a899565fc485f6cb Mon Sep 17 00:00:00 2001
From: Ramkumar Ramachandra <artagnon at tenstorrent.com>
Date: Fri, 23 Jan 2026 11:53:11 +0000
Subject: [PATCH 5/6] [SemilatticeTest] Fix unit

---
 llvm/unittests/Analysis/SemilatticeTest.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/llvm/unittests/Analysis/SemilatticeTest.cpp b/llvm/unittests/Analysis/SemilatticeTest.cpp
index 9c8babee0bd4f..9fbd82d5d76c6 100644
--- a/llvm/unittests/Analysis/SemilatticeTest.cpp
+++ b/llvm/unittests/Analysis/SemilatticeTest.cpp
@@ -98,7 +98,7 @@ TEST_F(SemilatticeTest, Iterators) {
   Semilattice EmptyLat(*F);
   SemilatticeNode *EmptyRoot = EmptyLat.getRootNode();
   EXPECT_TRUE(EmptyRoot->isLeaf());
-  EXPECT_EQ(EmptyRoot->begin(), EmptyRoot->end());
+  EXPECT_EQ(EmptyRoot->child_begin(), EmptyRoot->child_end());
   EXPECT_EQ(
       std::distance(EmptyRoot->children().begin(), EmptyRoot->children().end()),
       0u);
@@ -109,10 +109,10 @@ TEST_F(SemilatticeTest, Iterators) {
   EXPECT_TRUE(Root->isRoot());
   EXPECT_FALSE(Root->isLeaf());
 
-  auto *It = Root->begin();
-  EXPECT_NE(It, Root->end());
+  auto *It = Root->child_begin();
+  EXPECT_NE(It, Root->child_end());
   SemilatticeNode *Child = *It++;
-  EXPECT_EQ(It, Root->end());
+  EXPECT_EQ(It, Root->child_end());
   EXPECT_FALSE(Child->isRoot());
   EXPECT_TRUE(Child->isLeaf());
 

>From 0c507ed5d919f067effa6b3768b10d80523d0109 Mon Sep 17 00:00:00 2001
From: Ramkumar Ramachandra <artagnon at tenstorrent.com>
Date: Fri, 23 Jan 2026 12:27:15 +0000
Subject: [PATCH 6/6] [unittests/Analysis] Fix CMake

---
 llvm/unittests/Analysis/CMakeLists.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/unittests/Analysis/CMakeLists.txt b/llvm/unittests/Analysis/CMakeLists.txt
index c64d9ef0d0586..852ae5d449a9c 100644
--- a/llvm/unittests/Analysis/CMakeLists.txt
+++ b/llvm/unittests/Analysis/CMakeLists.txt
@@ -51,7 +51,7 @@ set(ANALYSIS_TEST_SOURCES
   ProfileSummaryInfoTest.cpp
   ReplaceWithVecLibTest.cpp
   ScalarEvolutionTest.cpp
-  SemiLatticeTest.cpp
+  SemilatticeTest.cpp
   SparsePropagation.cpp
   TargetLibraryInfoTest.cpp
   TensorSpecTest.cpp



More information about the llvm-commits mailing list