[Mlir-commits] [mlir] Add a polynomial dialect shell, attributes, and types (PR #72081)

Jeremy Kun llvmlistbot at llvm.org
Sun Nov 12 20:04:43 PST 2023


https://github.com/j2kun created https://github.com/llvm/llvm-project/pull/72081

RFC: https://discourse.llvm.org/t/rfc-a-poly-dialect-for-polynomial-arithmetic/73891

This PR implements the minimal work needed to represent the polynomial type such that it can be tested with `lit`.

Please let me know if this PR is too big to review, and I can split it into smaller pieces:

- Dialect shell
- `Polynomial` storage type
- Polynomial attributes (`PolynomialAttr` and `RingAttr`)
- `polynomial.polynomial` type

Note that I also have C++ unit tests for the polynomial storage type that can be ported from https://github.com/google/heir/blob/main/lib/Dialect/Polynomial/IR/PolynomialTest.cpp, if desired. I believe C++ unit tests are considered less preferred than `lit` tests, but let me know if you prefer unit tests on top of lit tests.

>From a3151b1355a5d01110ac84f7a73fb746297bb4a2 Mon Sep 17 00:00:00 2001
From: Jeremy Kun <jkun at google.com>
Date: Sat, 4 Nov 2023 10:05:33 -0700
Subject: [PATCH] polynomial: add dialect shell, attrs, and types

---
 mlir/include/mlir/Dialect/CMakeLists.txt      |   1 +
 .../mlir/Dialect/Polynomial/CMakeLists.txt    |   1 +
 .../mlir/Dialect/Polynomial/IR/CMakeLists.txt |  19 ++
 .../mlir/Dialect/Polynomial/IR/Polynomial.h   | 157 +++++++++++++
 .../Polynomial/IR/PolynomialAttributes.h      |  18 ++
 .../Polynomial/IR/PolynomialAttributes.td     |  81 +++++++
 .../Dialect/Polynomial/IR/PolynomialDialect.h |  19 ++
 .../Polynomial/IR/PolynomialDialect.td        |  54 +++++
 .../Dialect/Polynomial/IR/PolynomialOps.h     |  21 ++
 .../Dialect/Polynomial/IR/PolynomialOps.td    |  40 ++++
 .../Dialect/Polynomial/IR/PolynomialTypes.h   |  17 ++
 .../Dialect/Polynomial/IR/PolynomialTypes.td  |  32 +++
 mlir/include/mlir/InitAllDialects.h           |   2 +
 mlir/lib/Dialect/CMakeLists.txt               |   1 +
 mlir/lib/Dialect/Polynomial/CMakeLists.txt    |   1 +
 mlir/lib/Dialect/Polynomial/IR/CMakeLists.txt |  21 ++
 mlir/lib/Dialect/Polynomial/IR/Polynomial.cpp |  97 ++++++++
 .../Polynomial/IR/PolynomialAttributes.cpp    | 216 ++++++++++++++++++
 .../Dialect/Polynomial/IR/PolynomialDetail.h  |  65 ++++++
 .../Polynomial/IR/PolynomialDialect.cpp       |  47 ++++
 .../Dialect/Polynomial/IR/PolynomialOps.cpp   |  16 ++
 mlir/test/Dialect/Polynomial/types.td         |  19 ++
 22 files changed, 945 insertions(+)
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/CMakeLists.txt
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/CMakeLists.txt
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/Polynomial.h
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/PolynomialAttributes.h
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/PolynomialAttributes.td
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/PolynomialDialect.h
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/PolynomialDialect.td
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/PolynomialOps.h
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/PolynomialOps.td
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/PolynomialTypes.h
 create mode 100644 mlir/include/mlir/Dialect/Polynomial/IR/PolynomialTypes.td
 create mode 100644 mlir/lib/Dialect/Polynomial/CMakeLists.txt
 create mode 100644 mlir/lib/Dialect/Polynomial/IR/CMakeLists.txt
 create mode 100644 mlir/lib/Dialect/Polynomial/IR/Polynomial.cpp
 create mode 100644 mlir/lib/Dialect/Polynomial/IR/PolynomialAttributes.cpp
 create mode 100644 mlir/lib/Dialect/Polynomial/IR/PolynomialDetail.h
 create mode 100644 mlir/lib/Dialect/Polynomial/IR/PolynomialDialect.cpp
 create mode 100644 mlir/lib/Dialect/Polynomial/IR/PolynomialOps.cpp
 create mode 100644 mlir/test/Dialect/Polynomial/types.td

diff --git a/mlir/include/mlir/Dialect/CMakeLists.txt b/mlir/include/mlir/Dialect/CMakeLists.txt
index 1c4569ecfa58485..fa2393ff67d00fd 100644
--- a/mlir/include/mlir/Dialect/CMakeLists.txt
+++ b/mlir/include/mlir/Dialect/CMakeLists.txt
@@ -27,6 +27,7 @@ add_subdirectory(OpenACCMPCommon)
 add_subdirectory(OpenMP)
 add_subdirectory(PDL)
 add_subdirectory(PDLInterp)
+add_subdirectory(Polynomial)
 add_subdirectory(Quant)
 add_subdirectory(SCF)
 add_subdirectory(Shape)
diff --git a/mlir/include/mlir/Dialect/Polynomial/CMakeLists.txt b/mlir/include/mlir/Dialect/Polynomial/CMakeLists.txt
new file mode 100644
index 000000000000000..f33061b2d87cffc
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(IR)
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/CMakeLists.txt b/mlir/include/mlir/Dialect/Polynomial/IR/CMakeLists.txt
new file mode 100644
index 000000000000000..3719fda2aec6d43
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/CMakeLists.txt
@@ -0,0 +1,19 @@
+set(LLVM_TARGET_DEFINITIONS PolynomialOps.td)
+mlir_tablegen(PolynomialDialect.cpp.inc -gen-dialect-defs -dialect=polynomial)
+mlir_tablegen(PolynomialDialect.h.inc -gen-dialect-decls -dialect=polynomial)
+add_public_tablegen_target(MLIRPolynomialDialectIncGen)
+
+mlir_tablegen(PolynomialAttributes.cpp.inc -gen-attrdef-defs -attrdefs-dialect=polynomial)
+mlir_tablegen(PolynomialAttributes.h.inc -gen-attrdef-decls -attrdefs-dialect=polynomial)
+mlir_tablegen(PolynomialOps.cpp.inc -gen-op-defs)
+mlir_tablegen(PolynomialOps.h.inc -gen-op-decls)
+mlir_tablegen(PolynomialTypes.cpp.inc -gen-typedef-defs -typedefs-dialect=polynomial)
+mlir_tablegen(PolynomialTypes.h.inc -gen-typedef-decls -typedefs-dialect=polynomial)
+add_public_tablegen_target(MLIRPolynomialAttributesIncGen)
+add_public_tablegen_target(MLIRPolynomialOpsIncGen)
+add_public_tablegen_target(MLIRPolynomialTypesIncGen)
+add_dependencies(mlir-headers MLIRPolynomialOpsIncGen)
+
+add_mlir_doc(PolynoialOps PolynoialOps Dialects/ -gen-dialect-doc -dialect polynomial)
+add_mlir_doc(PolynomialAttributes PolynomialAttributes Dialects/ -gen-attrdef-doc)
+add_mlir_doc(PolynomialTypes PolynomialTypes Dialects/ -gen-typedef-doc)
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/Polynomial.h b/mlir/include/mlir/Dialect/Polynomial/IR/Polynomial.h
new file mode 100644
index 000000000000000..757ee61ec8c7a28
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/Polynomial.h
@@ -0,0 +1,157 @@
+//===- Polynomial.h - A storage class for polynomial types --------*- C++-*-==//
+//
+// 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 INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIAL_H_
+#define INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIAL_H_
+
+#include <utility>
+
+#include "mlir/Support/LLVM.h"
+#include "llvm/ADT/APInt.h"
+#include "llvm/ADT/DenseMapInfo.h"
+#include "llvm/ADT/Hashing.h"
+
+namespace mlir {
+
+class MLIRContext;
+
+namespace polynomial {
+
+// This restricts statically defined polynomials to have at most 64-bit
+// coefficients. This may be relaxed in the future, but it seems unlikely one
+// would want to specify 128-bit polynomials statically in the source code.
+constexpr unsigned apintBitWidth = 64;
+
+namespace detail {
+struct PolynomialStorage;
+} // namespace detail
+
+class Monomial {
+public:
+  Monomial(int64_t coeff, uint64_t expo)
+      : coefficient(apintBitWidth, coeff), exponent(apintBitWidth, expo) {}
+
+  Monomial(APInt coeff, APInt expo)
+      : coefficient(std::move(coeff)), exponent(std::move(expo)) {}
+
+  Monomial() : coefficient(apintBitWidth, 0), exponent(apintBitWidth, 0) {}
+
+  bool operator==(const Monomial &other) const {
+    return other.coefficient == coefficient && other.exponent == exponent;
+  }
+  bool operator!=(const Monomial &other) const {
+    return other.coefficient != coefficient || other.exponent != exponent;
+  }
+
+  /// Monomials are ordered by exponent.
+  bool operator<(const Monomial &other) const {
+    return (exponent.ult(other.exponent));
+  }
+
+  // Prints polynomial to 'os'.
+  void print(raw_ostream &os) const;
+
+  friend ::llvm::hash_code hash_value(Monomial arg);
+
+public:
+  APInt coefficient;
+
+  // Always unsigned
+  APInt exponent;
+};
+
+/// A single-variable polynomial with integer coefficients. Polynomials are
+/// immutable and uniqued.
+///
+/// Eg: x^1024 + x + 1
+///
+/// The symbols used as the polynomial's indeterminate don't matter, so long as
+/// it is used consistently throughout the polynomial.
+class Polynomial {
+public:
+  using ImplType = detail::PolynomialStorage;
+
+  constexpr Polynomial() = default;
+  explicit Polynomial(ImplType *terms) : terms(terms) {}
+
+  static Polynomial fromMonomials(ArrayRef<Monomial> monomials,
+                                  MLIRContext *context);
+  /// Returns a polynomial with coefficients given by `coeffs`
+  static Polynomial fromCoefficients(ArrayRef<int64_t> coeffs,
+                                     MLIRContext *context);
+
+  MLIRContext *getContext() const;
+
+  explicit operator bool() const { return terms != nullptr; }
+  bool operator==(Polynomial other) const { return other.terms == terms; }
+  bool operator!=(Polynomial other) const { return !(other.terms == terms); }
+
+  // Prints polynomial to 'os'.
+  void print(raw_ostream &os) const;
+  void print(raw_ostream &os, const std::string &separator,
+             const std::string &exponentiation) const;
+  void dump() const;
+
+  // Prints polynomial so that it can be used as a valid identifier
+  std::string toIdentifier() const;
+
+  // A polynomial's terms are canonically stored in order of increasing degree.
+  ArrayRef<Monomial> getTerms() const;
+
+  unsigned getDegree() const;
+
+  friend ::llvm::hash_code hash_value(Polynomial arg);
+
+private:
+  ImplType *terms{nullptr};
+};
+
+// Make Polynomial hashable.
+inline ::llvm::hash_code hash_value(Polynomial arg) {
+  return ::llvm::hash_value(arg.terms);
+}
+
+inline ::llvm::hash_code hash_value(Monomial arg) {
+  return ::llvm::hash_value(arg.coefficient) ^ ::llvm::hash_value(arg.exponent);
+}
+
+inline raw_ostream &operator<<(raw_ostream &os, Polynomial polynomial) {
+  polynomial.print(os);
+  return os;
+}
+
+} // namespace polynomial
+} // namespace mlir
+
+namespace llvm {
+
+// Polynomials hash just like pointers
+template <>
+struct DenseMapInfo<mlir::polynomial::Polynomial> {
+  static mlir::polynomial::Polynomial getEmptyKey() {
+    auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
+    return mlir::polynomial::Polynomial(
+        static_cast<mlir::polynomial::Polynomial::ImplType *>(pointer));
+  }
+  static mlir::polynomial::Polynomial getTombstoneKey() {
+    auto *pointer = llvm::DenseMapInfo<void *>::getTombstoneKey();
+    return mlir::polynomial::Polynomial(
+        static_cast<mlir::polynomial::Polynomial::ImplType *>(pointer));
+  }
+  static unsigned getHashValue(mlir::polynomial::Polynomial val) {
+    return mlir::polynomial::hash_value(val);
+  }
+  static bool isEqual(mlir::polynomial::Polynomial lhs,
+                      mlir::polynomial::Polynomial rhs) {
+    return lhs == rhs;
+  }
+};
+
+} // namespace llvm
+
+#endif // INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIAL_H_
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialAttributes.h b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialAttributes.h
new file mode 100644
index 000000000000000..6d6941cf6bdcc6d
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialAttributes.h
@@ -0,0 +1,18 @@
+//===- PolynomialAttributes.h - Attributes for the Polynomial dialect -*- C++
+//-*-===//
+//
+// 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 INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALATTRIBUTES_H_
+#define INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALATTRIBUTES_H_
+
+#include "Polynomial.h"
+#include "PolynomialDialect.h"
+
+#define GET_ATTRDEF_CLASSES
+#include "mlir/Dialect/Polynomial/IR/PolynomialAttributes.h.inc"
+
+#endif // INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALATTRIBUTES_H_
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialAttributes.td b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialAttributes.td
new file mode 100644
index 000000000000000..0e4f2f182ede1fe
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialAttributes.td
@@ -0,0 +1,81 @@
+//===- PolynomialAttributes.td - Attribute definitions for the polynomial dialect ------*- tablegen -*-==//
+//
+// 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 POLYNOMIAL_ATTRIBUTES
+#define POLYNOMIAL_ATTRIBUTES
+
+include "PolynomialDialect.td"
+include "mlir/IR/BuiltinAttributes.td"
+include "mlir/IR/OpBase.td"
+
+class Polynomial_Attr<string name, string attrMnemonic, list<Trait> traits = []>
+    : AttrDef<Polynomial_Dialect, name, traits> {
+  let mnemonic = attrMnemonic;
+}
+
+def Polynomial_PolynomialAttr : Polynomial_Attr<"Polynomial", "polynomial"> {
+  let summary = "An attribute containing a single-variable polynomial.";
+  let description = [{
+     #poly = #polynomial.poly<x**1024 + 1>
+  }];
+
+  let parameters = (ins "Polynomial":$polynomial);
+
+  let builders = [
+    AttrBuilderWithInferredContext<(ins "Polynomial":$polynomial), [{
+      return $_get(polynomial.getContext(), polynomial);
+    }]>
+  ];
+
+  let skipDefaultBuilders = 1;
+  let hasCustomAssemblyFormat = 1;
+}
+
+def Polynomial_RingAttr : Polynomial_Attr<"Ring", "ring"> {
+  let summary = "An attribute specifying a polynomial ring.";
+  let description = [{
+    A ring describes the domain in which polynomial arithmetic occurs. The ring
+    attribute in `polynomial` represents the more specific case of polynomials
+    with a single indeterminate; whose coefficients can be represented by
+    another MLIR type (`ctype`); and, if the coefficient type is integral,
+    whose coefficients are taken modulo some statically known modulus (`cmod`).
+
+    Additionally, a polynomial ring can specify an _ideal_, which converts
+    polynomial arithmetic to the analogue of modular integer arithmetic, where
+    each polynomial is represented as its remainder when dividing by the
+    modulus. For single-variable polynomials, an "ideal" is always specificed
+    via a single polynomial, which we call `polynomialModulus`.
+
+    An expressive example is polynomials with i32 coefficients, whose
+    coefficients are taken modulo `2**32 - 5`, with a polynomial modulus of
+    `x**1024 - 1`.
+
+    ```
+    #poly_mod = #polynomial.polynomial<-1 + x**1024>
+    #ring = #polynomial.ring<ctype=i32, cmod=4294967291, ideal=#poly_mod>
+
+    %0 = ... : polynomial.polynomial<#ring>
+    ```
+
+    In this case, the value of a polynomial is always ``converted'' to a
+    canonical form by applying repeated reductions by setting `x**1024 = 1`
+    and simplifying.
+
+    The coefficient and polynomial modulus parameters are optional, and the
+    coefficient modulus is only allowed if the coefficient type is integral.
+  }];
+
+  let parameters = (ins
+    Builtin_TypeAttr: $coefficientType,
+    OptionalParameter<"std::optional<IntegerAttr>">: $coefficientModulus,
+    OptionalParameter<"std::optional<PolynomialAttr>">: $polynomialModulus
+  );
+
+  let hasCustomAssemblyFormat = 1;
+}
+
+#endif // POLYNOMIAL_ATTRIBUTES
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialDialect.h b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialDialect.h
new file mode 100644
index 000000000000000..50538126c0372f7
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialDialect.h
@@ -0,0 +1,19 @@
+//===- PolynomialDialect.h - The Polynomial dialect -*- C++ -*-===//
+//
+// 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 INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALDIALECT_H_
+#define INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALDIALECT_H_
+
+#include "mlir/IR/Builders.h"
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/Dialect.h"
+#include "mlir/IR/DialectImplementation.h"
+
+// Generated headers (block clang-format from messing up order)
+#include "mlir/Dialect/Polynomial/IR/PolynomialDialect.h.inc"
+
+#endif // INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALDIALECT_H_
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialDialect.td b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialDialect.td
new file mode 100644
index 000000000000000..d664a7c6159fdc8
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialDialect.td
@@ -0,0 +1,54 @@
+//===- PolynomialDialect.td - Dialect definition for the polynomial dialect ------*- tablegen -*-==//
+//
+// 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 POLYNOMIAL_DIALECT
+#define POLYNOMIAL_DIALECT
+
+include "mlir/IR/OpBase.td"
+
+def Polynomial_Dialect : Dialect {
+  let name = "polynomial";
+  let cppNamespace = "::mlir::polynomial";
+  let description = [{
+    The Polynomial dialect defines single-variable polynomial types and
+    operations.
+
+    The simplest use of `polynomial` is to represent mathematical operations in
+    a polynomial ring `R[x]`, where `R` is another MLIR type like `i32`.
+
+    More generally, this dialect supports representing polynomial operations in a
+    quotient ring `R[X]/(f(x))` for some statically fixed polynomial `f(x)`.
+    Two polyomials `p(x), q(x)` are considered equal in this ring if they have the
+    same remainder when dividing by `f(x)`. When a modulus is given, ring operations
+    are performed with reductions modulo `f(x)` and relative to the coefficient ring
+    `R`.
+
+    Examples:
+
+    ```mlir
+    // A constant polynomial in a ring with i32 coefficients and no polynomial modulus
+    #ring = #polynomial.ring<ctype=i32>
+    %a = polynomial.constant <1 + x**2 - 3x**3> : polynomial.polynomial<#ring>
+
+    // A constant polynomial in a ring with i32 coefficients, modulo (x^1024 + 1)
+    #modulus = #polynomial.polynomial<1 + x**1024>
+    #ring = #polynomial.ring<ctype=i32, ideal=#modulus>
+    %a = polynomial.constant <1 + x**2 - 3x**3> : polynomial.polynomial<#ring>
+
+    // A constant polynomial in a ring with i32 coefficients, with a polynomial
+    // modulus of (x^1024 + 1) and a coefficient modulus of 17.
+    #modulus = #polynomial.polynomial<1 + x**1024>
+    #ring = #polynomial.ring<ctype=i32, cmod=17, ideal=#modulus>
+    %a = polynomial.constant <1 + x**2 - 3x**3> : polynomial.polynomial<#ring>
+    ```
+  }];
+
+  let useDefaultTypePrinterParser = 1;
+  let useDefaultAttributePrinterParser = 1;
+}
+
+#endif // POLYNOMIAL_DIALECT
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialOps.h b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialOps.h
new file mode 100644
index 000000000000000..49491c9bdc8ad30
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialOps.h
@@ -0,0 +1,21 @@
+//===- PolynomialOps.h - Ops for the Polynomial dialect -*- C++ -*-===//
+//
+// 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 INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALOPS_H_
+#define INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALOPS_H_
+
+#include "PolynomialDialect.h"
+#include "PolynomialTypes.h"
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/Dialect.h"
+#include "mlir/Interfaces/InferTypeOpInterface.h"
+
+#define GET_OP_CLASSES
+#include "mlir/Dialect/Polynomial/IR/PolynomialOps.h.inc"
+
+#endif // INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALOPS_H_
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialOps.td b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialOps.td
new file mode 100644
index 000000000000000..6ead46c953faf74
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialOps.td
@@ -0,0 +1,40 @@
+//===- PolynomialOps.td - Polynomial op definitions --------------------*- tablegen -*-===//
+//
+// 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 POLYNOMIAL_OPS
+#define POLYNOMIAL_OPS
+
+include "PolynomialDialect.td"
+include "PolynomialTypes.td"
+include "mlir/Interfaces/InferTypeOpInterface.td"
+include "mlir/Interfaces/SideEffectInterfaces.td"
+
+// Base class for polynomial dialect ops. Ops in this dialect have no side
+// effects.
+class Polynomial_Op<string mnemonic, list<Trait> traits = []> :
+    Op<Polynomial_Dialect, mnemonic, traits # [Pure]>;
+
+// Base class for unary polynomial operations.
+class Polynomial_UnaryOp<string mnemonic, list<Trait> traits = []> :
+    Polynomial_Op<mnemonic, traits # [SameOperandsAndResultType]> {
+  let arguments = (ins Polynomial_PolynomialType:$operand);
+  let results = (outs Polynomial_PolynomialType:$result);
+
+  let assemblyFormat = "$operand attr-dict `:` qualified(type($result))";
+}
+
+// Base class for binary polynomial operations.
+class Polynomial_BinaryOp<string mnemonic, list<Trait> traits = []> :
+    Polynomial_Op<mnemonic, traits # [SameOperandsAndResultType]> {
+  let arguments = (ins Polynomial_PolynomialType:$lhs, Polynomial_PolynomialType:$rhs);
+  let results = (outs Polynomial_PolynomialType:$result);
+
+  let assemblyFormat = "$lhs `,` $rhs attr-dict `:` qualified(type($result))";
+}
+
+#endif // POLYNOMIAL_OPS
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialTypes.h b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialTypes.h
new file mode 100644
index 000000000000000..c030de2d6c77fb8
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialTypes.h
@@ -0,0 +1,17 @@
+//===- PolynomialTypes.h - Types for the Polynomial dialect -*- C++ -*-===//
+//
+// 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 INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALTYPES_H_
+#define INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALTYPES_H_
+
+#include "mlir/Dialect/Polynomial/IR/PolynomialAttributes.h"
+#include "mlir/Dialect/Polynomial/IR/PolynomialDialect.h"
+
+#define GET_TYPEDEF_CLASSES
+#include "mlir/Dialect/Polynomial/IR/PolynomialTypes.h.inc"
+
+#endif // INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALTYPES_H_
diff --git a/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialTypes.td b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialTypes.td
new file mode 100644
index 000000000000000..b480c9ea7144714
--- /dev/null
+++ b/mlir/include/mlir/Dialect/Polynomial/IR/PolynomialTypes.td
@@ -0,0 +1,32 @@
+//===- PolynomialTypes.td - Type definitions for polynomial dialect ------*- tablegen -*-==//
+//
+// 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 POLYNOMIAL_TYPES
+#define POLYNOMIAL_TYPES
+
+include "PolynomialAttributes.td"
+include "PolynomialDialect.td"
+include "mlir/IR/BuiltinAttributes.td"
+include "mlir/IR/OpBase.td"
+
+class Polynomial_Type<string name, string typeMnemonic>
+    : TypeDef<Polynomial_Dialect, name> {
+  let mnemonic = typeMnemonic;
+}
+
+def Polynomial_PolynomialType : Polynomial_Type<"Polynomial", "polynomial"> {
+  let summary = "An element of a polynomial ring.";
+
+  let description = [{
+    A type for polynomials in a polynomial quotient ring.
+  }];
+
+  let parameters = (ins Polynomial_RingAttr:$ring);
+  let assemblyFormat = "`<` $ring `>`";
+}
+
+#endif // POLYNOMIAL_TYPES
diff --git a/mlir/include/mlir/InitAllDialects.h b/mlir/include/mlir/InitAllDialects.h
index 19a62cadaa2e04f..90ed32d991d68da 100644
--- a/mlir/include/mlir/InitAllDialects.h
+++ b/mlir/include/mlir/InitAllDialects.h
@@ -60,6 +60,7 @@
 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
 #include "mlir/Dialect/PDL/IR/PDL.h"
 #include "mlir/Dialect/PDLInterp/IR/PDLInterp.h"
+#include "mlir/Dialect/Polynomial/IR/PolynomialDialect.h"
 #include "mlir/Dialect/Quant/QuantOps.h"
 #include "mlir/Dialect/SCF/IR/SCF.h"
 #include "mlir/Dialect/SCF/IR/ValueBoundsOpInterfaceImpl.h"
@@ -127,6 +128,7 @@ inline void registerAllDialects(DialectRegistry &registry) {
                   omp::OpenMPDialect,
                   pdl::PDLDialect,
                   pdl_interp::PDLInterpDialect,
+                  polynomial::PolynomialDialect,
                   quant::QuantizationDialect,
                   ROCDL::ROCDLDialect,
                   scf::SCFDialect,
diff --git a/mlir/lib/Dialect/CMakeLists.txt b/mlir/lib/Dialect/CMakeLists.txt
index 68776a695cac4d4..a990b75260f6913 100644
--- a/mlir/lib/Dialect/CMakeLists.txt
+++ b/mlir/lib/Dialect/CMakeLists.txt
@@ -27,6 +27,7 @@ add_subdirectory(OpenACCMPCommon)
 add_subdirectory(OpenMP)
 add_subdirectory(PDL)
 add_subdirectory(PDLInterp)
+add_subdirectory(Polynomial)
 add_subdirectory(Quant)
 add_subdirectory(SCF)
 add_subdirectory(Shape)
diff --git a/mlir/lib/Dialect/Polynomial/CMakeLists.txt b/mlir/lib/Dialect/Polynomial/CMakeLists.txt
new file mode 100644
index 000000000000000..f33061b2d87cffc
--- /dev/null
+++ b/mlir/lib/Dialect/Polynomial/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(IR)
diff --git a/mlir/lib/Dialect/Polynomial/IR/CMakeLists.txt b/mlir/lib/Dialect/Polynomial/IR/CMakeLists.txt
new file mode 100644
index 000000000000000..695c37f7a368b33
--- /dev/null
+++ b/mlir/lib/Dialect/Polynomial/IR/CMakeLists.txt
@@ -0,0 +1,21 @@
+add_mlir_dialect_library(MLIRPolynomialDialect
+  Polynomial.cpp
+  PolynomialAttributes.cpp
+  PolynomialDialect.cpp
+  PolynomialOps.cpp
+
+  ADDITIONAL_HEADER_DIRS
+  ${MLIR_MAIN_INCLUDE_DIR}/mlir/Dialect/Polynomial
+
+  DEPENDS
+  MLIRPolynomialOpsIncGen
+  MLIRPolynomialTypesIncGen
+  MLIRPolynomialDialectIncGen
+  MLIRPolynomialAttributesIncGen
+  MLIRBuiltinAttributesIncGen
+
+  LINK_LIBS PUBLIC
+  MLIRSupport
+  MLIRDialect
+  MLIRIR
+  )
diff --git a/mlir/lib/Dialect/Polynomial/IR/Polynomial.cpp b/mlir/lib/Dialect/Polynomial/IR/Polynomial.cpp
new file mode 100644
index 000000000000000..6e04691502275c1
--- /dev/null
+++ b/mlir/lib/Dialect/Polynomial/IR/Polynomial.cpp
@@ -0,0 +1,97 @@
+//===- Polynomial.cpp - MLIR storage type for static Polynomial
+//--------------===//
+//
+// 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 "mlir/Dialect/Polynomial/IR/Polynomial.h"
+
+#include "PolynomialDetail.h"
+#include "mlir/IR/MLIRContext.h"
+#include "llvm/ADT/APInt.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace mlir {
+namespace polynomial {
+
+MLIRContext *Polynomial::getContext() const { return terms->context; }
+
+ArrayRef<Monomial> Polynomial::getTerms() const { return terms->terms(); }
+
+Polynomial Polynomial::fromMonomials(ArrayRef<Monomial> monomials,
+                                     MLIRContext *context) {
+  auto assignCtx = [context](detail::PolynomialStorage *storage) {
+    storage->context = context;
+  };
+
+  // A polynomial's terms are canonically stored in order of increasing degree.
+  llvm::OwningArrayRef<Monomial> monomialsCopy =
+      llvm::OwningArrayRef<Monomial>(monomials);
+  std::sort(monomialsCopy.begin(), monomialsCopy.end());
+
+  StorageUniquer &uniquer = context->getAttributeUniquer();
+  return Polynomial(uniquer.get<detail::PolynomialStorage>(
+      assignCtx, monomials.size(), monomialsCopy));
+}
+
+Polynomial Polynomial::fromCoefficients(ArrayRef<int64_t> coeffs,
+                                        MLIRContext *context) {
+  std::vector<Monomial> monomials;
+  for (size_t i = 0; i < coeffs.size(); i++) {
+    monomials.emplace_back(coeffs[i], i);
+  }
+  return Polynomial::fromMonomials(monomials, context);
+}
+
+void Polynomial::print(raw_ostream &os, const std::string &separator,
+                       const std::string &exponentiation) const {
+  bool first = true;
+  for (const auto &term : terms->terms()) {
+    if (first) {
+      first = false;
+    } else {
+      os << separator;
+    }
+    std::string coeffToPrint;
+    if (term.coefficient == 1 && term.exponent.uge(1)) {
+      coeffToPrint = "";
+    } else {
+      llvm::SmallString<512> coeffString;
+      term.coefficient.toStringSigned(coeffString);
+      coeffToPrint = coeffString.str();
+    }
+
+    if (term.exponent == 0) {
+      os << coeffToPrint;
+    } else if (term.exponent == 1) {
+      os << coeffToPrint << "x";
+    } else {
+      llvm::SmallString<512> expString;
+      term.exponent.toStringSigned(expString);
+      os << coeffToPrint << "x" << exponentiation << expString;
+    }
+  }
+}
+
+void Polynomial::print(raw_ostream &os) const { print(os, " + ", "**"); }
+
+std::string Polynomial::toIdentifier() const {
+  std::string result;
+  llvm::raw_string_ostream os(result);
+  print(os, "_", "");
+  return os.str();
+}
+
+unsigned Polynomial::getDegree() const {
+  return terms->terms().back().exponent.getZExtValue();
+}
+
+} // namespace polynomial
+} // namespace mlir
+
+MLIR_DEFINE_EXPLICIT_TYPE_ID(mlir::polynomial::detail::PolynomialStorage);
diff --git a/mlir/lib/Dialect/Polynomial/IR/PolynomialAttributes.cpp b/mlir/lib/Dialect/Polynomial/IR/PolynomialAttributes.cpp
new file mode 100644
index 000000000000000..1f035e7d7890288
--- /dev/null
+++ b/mlir/lib/Dialect/Polynomial/IR/PolynomialAttributes.cpp
@@ -0,0 +1,216 @@
+//===- PolynomialAttributes.cpp - Polynomial dialect attributes --*- C++ -*-===//
+//
+// 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 "mlir/Dialect/Polynomial/IR/PolynomialAttributes.h"
+
+#include "mlir/Dialect/Polynomial/IR/Polynomial.h"
+#include "mlir/Support/LLVM.h"
+#include "mlir/Support/LogicalResult.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace mlir {
+namespace polynomial {
+
+void PolynomialAttr::print(AsmPrinter &p) const {
+  p << '<';
+  p << getPolynomial();
+  p << '>';
+}
+
+/// Try to parse a monomial. If successful, populate the fields of the outparam
+/// `monomial` with the results, and the `variable` outparam with the parsed
+/// variable name.
+ParseResult parseMonomial(AsmParser &parser, Monomial &monomial,
+                          llvm::StringRef *variable, bool *isConstantTerm) {
+  APInt parsedCoeff(apintBitWidth, 1);
+  auto result = parser.parseOptionalInteger(parsedCoeff);
+  if (result.has_value()) {
+    if (failed(*result)) {
+      parser.emitError(parser.getCurrentLocation(),
+                       "Invalid integer coefficient.");
+      return failure();
+    }
+  }
+
+  // Variable name
+  result = parser.parseOptionalKeyword(variable);
+  if (!result.has_value() || failed(*result)) {
+    // we allow "failed" because it triggers when the next token is a +,
+    // which is allowed when the input is the constant term.
+    monomial.coefficient = parsedCoeff;
+    monomial.exponent = APInt(apintBitWidth, 0);
+    *isConstantTerm = true;
+    return success();
+  }
+
+  // Parse exponentiation symbol as **
+  // We can't use caret because it's reserved for basic block identifiers
+  // If no star is present, it's treated as a polynomial with exponent 1
+  if (failed(parser.parseOptionalStar())) {
+    monomial.coefficient = parsedCoeff;
+    monomial.exponent = APInt(apintBitWidth, 1);
+    return success();
+  }
+
+  // If there's one * there must be two
+  if (failed(parser.parseStar())) {
+    parser.emitError(parser.getCurrentLocation(),
+                     "Exponents must be specified as a double-asterisk `**`.");
+    return failure();
+  }
+
+  // If there's a **, then the integer exponent is required.
+  APInt parsedExponent(apintBitWidth, 0);
+  if (failed(parser.parseInteger(parsedExponent))) {
+    parser.emitError(parser.getCurrentLocation(),
+                     "Found invalid integer exponent.");
+    return failure();
+  }
+
+  monomial.coefficient = parsedCoeff;
+  monomial.exponent = parsedExponent;
+  return success();
+}
+
+mlir::Attribute mlir::polynomial::PolynomialAttr::parse(AsmParser &parser,
+                                                        Type type) {
+  if (failed(parser.parseLess()))
+    return {};
+
+  std::vector<Monomial> monomials;
+  llvm::SmallSet<std::string, 2> variables;
+  llvm::DenseSet<APInt> exponents;
+
+  while (true) {
+    Monomial parsedMonomial;
+    llvm::StringRef parsedVariableRef;
+    bool isConstantTerm = false;
+    if (failed(parseMonomial(parser, parsedMonomial, &parsedVariableRef,
+                             &isConstantTerm))) {
+      return {};
+    }
+
+    if (!isConstantTerm) {
+      std::string parsedVariable = parsedVariableRef.str();
+      variables.insert(parsedVariable);
+    }
+    monomials.push_back(parsedMonomial);
+
+    if (exponents.count(parsedMonomial.exponent) > 0) {
+      llvm::SmallString<512> coeff_string;
+      parsedMonomial.exponent.toStringSigned(coeff_string);
+      parser.emitError(parser.getCurrentLocation(),
+                       "At most one monomial may have exponent " +
+                           coeff_string + ", but found multiple.");
+      return {};
+    }
+    exponents.insert(parsedMonomial.exponent);
+
+    // Parse optional +. If a + is absent, require > and break, otherwise forbid
+    // > and continue with the next monomial.
+    // ParseOptional{Plus, Greater} does not return an OptionalParseResult, so
+    // failed means that the token was not found.
+    if (failed(parser.parseOptionalPlus())) {
+      if (succeeded(parser.parseGreater())) {
+        break;
+      } else {
+        parser.emitError(
+            parser.getCurrentLocation(),
+            "Expected + and more monomials, or > to end polynomial attribute.");
+        return {};
+      }
+    } else if (succeeded(parser.parseOptionalGreater())) {
+      parser.emitError(
+          parser.getCurrentLocation(),
+          "Expected another monomial after +, but found > ending attribute.");
+      return {};
+    }
+  }
+
+  // insert necessary constant ops to give as input to extract_slice.
+  if (variables.size() > 1) {
+    std::string vars = llvm::join(variables.begin(), variables.end(), ", ");
+    parser.emitError(
+        parser.getCurrentLocation(),
+        "Polynomials must have one indeterminate, but there were multiple: " +
+            vars);
+  }
+
+  Polynomial poly = Polynomial::fromMonomials(monomials, parser.getContext());
+  return PolynomialAttr::get(poly);
+}
+
+void RingAttr::print(AsmPrinter &p) const {
+  p << "#polynomial.ring<ctype=" << getCoefficientType()
+    << ", cmod=" << getCoefficientModulus()
+    << ", ideal=" << getPolynomialModulus() << '>';
+}
+
+mlir::Attribute mlir::polynomial::RingAttr::parse(AsmParser &parser,
+                                                  Type type) {
+  if (failed(parser.parseLess()))
+    return {};
+
+  if (failed(parser.parseKeyword("ctype")))
+    return {};
+
+  if (failed(parser.parseEqual()))
+    return {};
+
+  TypeAttr typeAttr;
+  if (failed(parser.parseAttribute<TypeAttr>(typeAttr)))
+    return {};
+
+  if (failed(parser.parseComma()))
+    return {};
+
+  std::optional<IntegerAttr> cmodAttr = std::nullopt;
+  if (succeeded(parser.parseKeyword("cmod"))) {
+    if (failed(parser.parseEqual()))
+      return {};
+
+    IntegerType iType = llvm::dyn_cast<IntegerType>(typeAttr.getValue());
+    if (!iType) {
+      parser.emitError(
+          parser.getCurrentLocation(),
+          "Invalid coefficient modulus, ctype must specify an integer type.");
+      return {};
+    }
+    APInt cmod(iType.getWidth(), 0);
+    auto result = parser.parseInteger(cmod);
+    if (failed(result)) {
+      parser.emitError(parser.getCurrentLocation(),
+                       "Invalid coefficient modulus.");
+      return {};
+    }
+    cmodAttr = IntegerAttr::get(iType, cmod);
+
+    if (failed(parser.parseComma()))
+      return {};
+  }
+
+  std::optional<PolynomialAttr> polyAttr = std::nullopt;
+  if (succeeded(parser.parseKeyword("ideal"))) {
+    if (failed(parser.parseEqual()))
+      return {};
+
+    PolynomialAttr attr;
+    if (failed(parser.parseAttribute<PolynomialAttr>(attr)))
+      return {};
+    polyAttr = attr;
+  }
+
+  if (failed(parser.parseGreater()))
+    return {};
+
+  return RingAttr::get(parser.getContext(), typeAttr, cmodAttr, polyAttr);
+}
+
+} // namespace polynomial
+} // namespace mlir
diff --git a/mlir/lib/Dialect/Polynomial/IR/PolynomialDetail.h b/mlir/lib/Dialect/Polynomial/IR/PolynomialDetail.h
new file mode 100644
index 000000000000000..19ee6b7ec25d10c
--- /dev/null
+++ b/mlir/lib/Dialect/Polynomial/IR/PolynomialDetail.h
@@ -0,0 +1,65 @@
+//===- Polynomial.h - Storage class details for polynomial types --------*-
+// C++-*-==//
+//
+// 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 INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALDETAIL_H_
+#define INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALDETAIL_H_
+
+#include "mlir/Dialect/Polynomial/IR/Polynomial.h"
+#include "mlir/Support/StorageUniquer.h"
+#include "mlir/Support/TypeID.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/TrailingObjects.h"
+
+namespace mlir {
+namespace polynomial {
+namespace detail {
+
+// A Polynomial is stored as an ordered list of monomial terms, each of which
+// is a tuple of coefficient and exponent.
+struct PolynomialStorage final
+    : public StorageUniquer::BaseStorage,
+      public llvm::TrailingObjects<PolynomialStorage, Monomial> {
+  /// The hash key used for uniquing.
+  using KeyTy = std::tuple<unsigned, ArrayRef<Monomial>>;
+
+  unsigned numTerms;
+
+  MLIRContext *context;
+
+  /// The monomial terms for this polynomial.
+  ArrayRef<Monomial> terms() const {
+    return {getTrailingObjects<Monomial>(), numTerms};
+  }
+
+  bool operator==(const KeyTy &key) const {
+    return std::get<0>(key) == numTerms && std::get<1>(key) == terms();
+  }
+
+  // Constructs a PolynomialStorage from a key. The context must be set by the
+  // caller.
+  static PolynomialStorage *
+  construct(StorageUniquer::StorageAllocator &allocator, const KeyTy &key) {
+    auto terms = std::get<1>(key);
+    auto byteSize = PolynomialStorage::totalSizeToAlloc<Monomial>(terms.size());
+    auto *rawMem = allocator.allocate(byteSize, alignof(PolynomialStorage));
+    auto *res = new (rawMem) PolynomialStorage();
+    res->numTerms = std::get<0>(key);
+    std::uninitialized_copy(terms.begin(), terms.end(),
+                            res->getTrailingObjects<Monomial>());
+    return res;
+  }
+};
+
+} // namespace detail
+} // namespace polynomial
+} // namespace mlir
+
+MLIR_DECLARE_EXPLICIT_TYPE_ID(mlir::polynomial::detail::PolynomialStorage)
+
+#endif // INCLUDE_MLIR_DIALECT_POLYNOMIAL_IR_POLYNOMIALDETAIL_H_
diff --git a/mlir/lib/Dialect/Polynomial/IR/PolynomialDialect.cpp b/mlir/lib/Dialect/Polynomial/IR/PolynomialDialect.cpp
new file mode 100644
index 000000000000000..b618495b2cdcd08
--- /dev/null
+++ b/mlir/lib/Dialect/Polynomial/IR/PolynomialDialect.cpp
@@ -0,0 +1,47 @@
+//===- PolynomialDialect.cpp - MLIR dialect for Polynomial implementation
+//-------------===//
+//
+// 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 "mlir/Dialect/Polynomial/IR/Polynomial.h"
+
+#include "PolynomialDetail.h"
+#include "mlir/Dialect/Polynomial/IR/PolynomialAttributes.h"
+#include "mlir/Dialect/Polynomial/IR/PolynomialOps.h"
+#include "mlir/Dialect/Polynomial/IR/PolynomialTypes.h"
+#include "llvm/ADT/TypeSwitch.h"
+
+using namespace mlir;
+using namespace mlir::polynomial;
+
+#include "mlir/Dialect/Polynomial/IR/PolynomialDialect.cpp.inc"
+
+#define GET_ATTRDEF_CLASSES
+#include "mlir/Dialect/Polynomial/IR/PolynomialAttributes.cpp.inc"
+#define GET_TYPEDEF_CLASSES
+#include "mlir/Dialect/Polynomial/IR/PolynomialTypes.cpp.inc"
+#define GET_OP_CLASSES
+#include "mlir/Dialect/Polynomial/IR/PolynomialOps.cpp.inc"
+
+void PolynomialDialect::initialize() {
+  addAttributes<
+#define GET_ATTRDEF_LIST
+#include "mlir/Dialect/Polynomial/IR/PolynomialAttributes.cpp.inc"
+      >();
+  addTypes<
+#define GET_TYPEDEF_LIST
+#include "mlir/Dialect/Polynomial/IR/PolynomialTypes.cpp.inc"
+      >();
+  addOperations<
+#define GET_OP_LIST
+#include "mlir/Dialect/Polynomial/IR/PolynomialOps.cpp.inc"
+      >();
+
+  getContext()
+      ->getAttributeUniquer()
+      .registerParametricStorageType<detail::PolynomialStorage>();
+}
diff --git a/mlir/lib/Dialect/Polynomial/IR/PolynomialOps.cpp b/mlir/lib/Dialect/Polynomial/IR/PolynomialOps.cpp
new file mode 100644
index 000000000000000..644a669205213e5
--- /dev/null
+++ b/mlir/lib/Dialect/Polynomial/IR/PolynomialOps.cpp
@@ -0,0 +1,16 @@
+//===- PolynomialOps.cpp - MLIR operations for polynomial implementation
+//--------------===//
+//
+// 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 "mlir/Dialect/Polynomial/IR/Polynomial.h"
+
+using namespace mlir;
+using namespace mlir::polynomial;
+
+#define GET_OP_CLASSES
+#include "mlir/Dialect/Polynomial/IR/PolynomialOps.cpp.inc"
diff --git a/mlir/test/Dialect/Polynomial/types.td b/mlir/test/Dialect/Polynomial/types.td
new file mode 100644
index 000000000000000..7328318002203ee
--- /dev/null
+++ b/mlir/test/Dialect/Polynomial/types.td
@@ -0,0 +1,19 @@
+// RUN: mlir-opt %s | FileCheck %s
+
+#my_poly = #polynomial.polynomial<1 + x**1024>
+#my_poly_2 = #polynomial.polynomial<2>
+#my_poly_3 = #polynomial.polynomial<3x>
+#my_poly_4 = #polynomial.polynomial<t**3 + 4t + 2>
+#ring1 = #polynomial.ring<ctype=i32, cmod=2837465, ideal=#my_poly>
+
+!ty = !polynomial.polynomial<#ring1>
+
+// CHECK-LABEL: func @test_types
+// CHECK-SAME:  !polynomial.polynomial<
+// CHECK-SAME:    #polynomial.ring<
+// CHECK-SAME:       ctype=i32,
+// CHECK-SAME:       cmod=2837465 : i32,
+// CHECK-SAME:       ideal=#polynomial.polynomial<1 + x**1024>>>
+func.func @test_types(%0: !ty) -> !ty {
+  return %0 : !ty
+}



More information about the Mlir-commits mailing list