Skip to content

[mlir][LLVM] Add exact flag #115327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 8, 2024
Merged

[mlir][LLVM] Add exact flag #115327

merged 2 commits into from
Nov 8, 2024

Conversation

lfrenot
Copy link
Contributor

@lfrenot lfrenot commented Nov 7, 2024

The implementation is mostly based on the one existing for the nsw and nuw flags.

If the exact flag is present, the corresponding operation returns a poison value when the result is not exact. (For a division, if rounding happens; for a right shift, if a non-zero bit is shifted out.)

@zero9178, @gysit and @Dinistro, could you take a look?

Copy link

github-actions bot commented Nov 7, 2024

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Nov 7, 2024

@llvm/pr-subscribers-mlir-llvm

@llvm/pr-subscribers-mlir

Author: None (lfrenot)

Changes

The implementation is mostly based on the one existing for the nsw and nuw flags.

If the exact flag is present, the corresponding operation returns a poison value when the result is not exact. (For a division, if rounding happens; for a right shift, if a non-zero bit is shifted out.)

@zero9178, @gysit and @Dinistro, could you take a look?


Full diff: https://github.com/llvm/llvm-project/pull/115327.diff

8 Files Affected:

  • (modified) mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.td (+27)
  • (modified) mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td (+22-4)
  • (modified) mlir/include/mlir/Target/LLVMIR/ModuleImport.h (+5)
  • (modified) mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp (+3)
  • (modified) mlir/lib/Target/LLVMIR/ModuleImport.cpp (+8)
  • (modified) mlir/test/Dialect/LLVMIR/roundtrip.mlir (+10)
  • (added) mlir/test/Target/LLVMIR/Import/exact.ll (+14)
  • (added) mlir/test/Target/LLVMIR/exact.mlir (+14)
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.td
index 7e38e0b27fd96b..12c430df208925 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.td
@@ -87,6 +87,33 @@ def IntegerOverflowFlagsInterface : OpInterface<"IntegerOverflowFlagsInterface">
   ];
 }
 
+def ExactFlagInterface : OpInterface<"ExactFlagInterface"> {
+  let description = [{
+    This interface defines an LLVM operation with an exact flag and
+    provides a uniform API for accessing it.
+  }];
+
+  let cppNamespace = "::mlir::LLVM";
+
+  let methods = [
+    InterfaceMethod<[{
+      Get the exact flag for the operation.
+    }], "bool", "getIsExact", (ins), [{}], [{
+      return $_op.getProperties().isExact;
+    }]>,
+    InterfaceMethod<[{
+      Set the exact flag for the operation.
+    }], "void", "setIsExact", (ins "bool":$isExact), [{}], [{
+      $_op.getProperties().isExact = isExact;
+    }]>,
+    StaticInterfaceMethod<[{
+      Get the attribute name of the isExact property.
+    }], "StringRef", "getIsExactName", (ins), [{}], [{
+      return "isExact";
+    }]>,
+  ];
+}
+
 def BranchWeightOpInterface : OpInterface<"BranchWeightOpInterface"> {
   let description = [{
     An interface for operations that can carry branch weights metadata. It
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
index d5def510a904d3..b7ce126dbf54dd 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
@@ -76,6 +76,24 @@ class LLVM_IntArithmeticOpWithOverflowFlag<string mnemonic, string instName,
     "$res = builder.Create" # instName #
     "($lhs, $rhs, /*Name=*/\"\", op.hasNoUnsignedWrap(), op.hasNoSignedWrap());";
 }
+class LLVM_IntArithmeticOpWithIsExact<string mnemonic, string instName,
+                                   list<Trait> traits = []> :
+    LLVM_ArithmeticOpBase<AnySignlessInteger, mnemonic, instName,
+    !listconcat([DeclareOpInterfaceMethods<ExactFlagInterface>], traits)> {
+  let arguments = !con(commonArgs, (ins UnitAttr:$isExact));
+
+  string mlirBuilder = [{
+    auto op = $_builder.create<$_qualCppClassName>($_location, $lhs, $rhs);
+    moduleImport.setExactFlag(inst, op);
+    $res = op;
+  }];
+  let assemblyFormat = [{
+    (`exact` $isExact^)? $lhs `,` $rhs custom<LLVMOpAttrs>(attr-dict) `:` type($res)
+  }];
+  string llvmBuilder =
+    "$res = builder.Create" # instName #
+    "($lhs, $rhs, /*Name=*/\"\", op.getIsExact());";
+}
 class LLVM_FloatArithmeticOp<string mnemonic, string instName,
                              list<Trait> traits = []> :
     LLVM_ArithmeticOpBase<LLVM_AnyFloat, mnemonic, instName,
@@ -116,8 +134,8 @@ def LLVM_AddOp : LLVM_IntArithmeticOpWithOverflowFlag<"add", "Add",
 def LLVM_SubOp : LLVM_IntArithmeticOpWithOverflowFlag<"sub", "Sub", []>;
 def LLVM_MulOp : LLVM_IntArithmeticOpWithOverflowFlag<"mul", "Mul",
     [Commutative]>;
-def LLVM_UDivOp : LLVM_IntArithmeticOp<"udiv", "UDiv">;
-def LLVM_SDivOp : LLVM_IntArithmeticOp<"sdiv", "SDiv">;
+def LLVM_UDivOp : LLVM_IntArithmeticOpWithIsExact<"udiv", "UDiv">;
+def LLVM_SDivOp : LLVM_IntArithmeticOpWithIsExact<"sdiv", "SDiv">;
 def LLVM_URemOp : LLVM_IntArithmeticOp<"urem", "URem">;
 def LLVM_SRemOp : LLVM_IntArithmeticOp<"srem", "SRem">;
 def LLVM_AndOp : LLVM_IntArithmeticOp<"and", "And">;
@@ -128,8 +146,8 @@ def LLVM_XOrOp : LLVM_IntArithmeticOp<"xor", "Xor">;
 def LLVM_ShlOp : LLVM_IntArithmeticOpWithOverflowFlag<"shl", "Shl", []> {
   let hasFolder = 1;
 }
-def LLVM_LShrOp : LLVM_IntArithmeticOp<"lshr", "LShr">;
-def LLVM_AShrOp : LLVM_IntArithmeticOp<"ashr", "AShr">;
+def LLVM_LShrOp : LLVM_IntArithmeticOpWithIsExact<"lshr", "LShr">;
+def LLVM_AShrOp : LLVM_IntArithmeticOpWithIsExact<"ashr", "AShr">;
 
 // Base class for compare operations. A compare operation takes two operands
 // of the same type and returns a boolean result. If the operands are
diff --git a/mlir/include/mlir/Target/LLVMIR/ModuleImport.h b/mlir/include/mlir/Target/LLVMIR/ModuleImport.h
index bbb7af58d27393..6c3a500f20e3a9 100644
--- a/mlir/include/mlir/Target/LLVMIR/ModuleImport.h
+++ b/mlir/include/mlir/Target/LLVMIR/ModuleImport.h
@@ -187,6 +187,11 @@ class ModuleImport {
   /// operation does not implement the integer overflow flag interface.
   void setIntegerOverflowFlags(llvm::Instruction *inst, Operation *op) const;
 
+  /// Sets the exact flag attribute for the imported operation `op` given
+  /// the original instruction `inst`. Asserts if the operation does not
+  /// implement the exact flag interface.
+  void setExactFlag(llvm::Instruction *inst, Operation *op) const;
+
   /// Sets the fastmath flags attribute for the imported operation `op` given
   /// the original instruction `inst`. Asserts if the operation does not
   /// implement the fastmath interface.
diff --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
index c9bc9533ca2a6b..6b2d8943bf4885 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
@@ -143,6 +143,9 @@ static void printLLVMOpAttrs(OpAsmPrinter &printer, Operation *op,
   if (auto iface = dyn_cast<IntegerOverflowFlagsInterface>(op)) {
     printer.printOptionalAttrDict(
         filteredAttrs, /*elidedAttrs=*/{iface.getOverflowFlagsAttrName()});
+  } else if (auto iface = dyn_cast<ExactFlagInterface>(op)) {
+    printer.printOptionalAttrDict(filteredAttrs,
+                                  /*elidedAttrs=*/{iface.getIsExactName()});
   } else {
     printer.printOptionalAttrDict(filteredAttrs);
   }
diff --git a/mlir/lib/Target/LLVMIR/ModuleImport.cpp b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
index 1f63519373ecab..ccec2034a298b2 100644
--- a/mlir/lib/Target/LLVMIR/ModuleImport.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
@@ -683,6 +683,14 @@ void ModuleImport::setIntegerOverflowFlags(llvm::Instruction *inst,
   iface.setOverflowFlags(value);
 }
 
+void ModuleImport::setExactFlag(llvm::Instruction *inst, Operation *op) const {
+  auto iface = cast<ExactFlagInterface>(op);
+
+  bool value = inst->isExact();
+
+  iface.setIsExact(value);
+}
+
 void ModuleImport::setFastmathFlagsAttr(llvm::Instruction *inst,
                                         Operation *op) const {
   auto iface = cast<FastmathFlagsInterface>(op);
diff --git a/mlir/test/Dialect/LLVMIR/roundtrip.mlir b/mlir/test/Dialect/LLVMIR/roundtrip.mlir
index b8ce7db795a1d1..9daad2ef5b0b1b 100644
--- a/mlir/test/Dialect/LLVMIR/roundtrip.mlir
+++ b/mlir/test/Dialect/LLVMIR/roundtrip.mlir
@@ -49,6 +49,16 @@ func.func @ops(%arg0: i32, %arg1: f32,
   %mul_flag = llvm.mul %arg0, %arg0 overflow<nsw, nuw> : i32
   %shl_flag = llvm.shl %arg0, %arg0 overflow<nuw, nsw> : i32
 
+// Integer exact
+// CHECK: {{.*}} = llvm.sdiv exact %[[I32]], %[[I32]] : i32
+// CHECK: {{.*}} = llvm.udiv exact %[[I32]], %[[I32]] : i32
+// CHECK: {{.*}} = llvm.ashr exact %[[I32]], %[[I32]] : i32
+// CHECK: {{.*}} = llvm.lshr exact %[[I32]], %[[I32]] : i32
+  %sdiv_flag = llvm.sdiv exact %arg0, %arg0 : i32
+  %udiv_flag = llvm.udiv exact %arg0, %arg0 : i32
+  %ashr_flag = llvm.ashr exact %arg0, %arg0 : i32
+  %lshr_flag = llvm.lshr exact %arg0, %arg0 : i32
+
 // Floating point binary operations.
 //
 // CHECK: {{.*}} = llvm.fadd %[[FLOAT]], %[[FLOAT]] : f32
diff --git a/mlir/test/Target/LLVMIR/Import/exact.ll b/mlir/test/Target/LLVMIR/Import/exact.ll
new file mode 100644
index 00000000000000..528fee5091d2da
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/Import/exact.ll
@@ -0,0 +1,14 @@
+; RUN: mlir-translate -import-llvm -split-input-file %s | FileCheck %s
+
+; CHECK-LABEL: @exactflag_inst
+define void @exactflag_inst(i64 %arg1, i64 %arg2) {
+  ; CHECK: llvm.udiv exact %{{.*}}, %{{.*}} : i64
+  %1 = udiv exact i64 %arg1, %arg2
+  ; CHECK: llvm.sdiv exact %{{.*}}, %{{.*}} : i64
+  %2 = sdiv exact i64 %arg1, %arg2
+  ; CHECK: llvm.lshr exact %{{.*}}, %{{.*}} : i64
+  %3 = lshr exact i64 %arg1, %arg2
+  ; CHECK: llvm.ashr exact %{{.*}}, %{{.*}} : i64
+  %4 = ashr exact i64 %arg1, %arg2
+  ret void
+}
diff --git a/mlir/test/Target/LLVMIR/exact.mlir b/mlir/test/Target/LLVMIR/exact.mlir
new file mode 100644
index 00000000000000..b6c378c2fdcc94
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/exact.mlir
@@ -0,0 +1,14 @@
+// RUN: mlir-translate -mlir-to-llvmir %s | FileCheck %s
+
+// CHECK-LABEL: define void @exactflag_func
+llvm.func @exactflag_func(%arg0: i64, %arg1: i64) {
+  // CHECK: %{{.*}} = udiv exact i64 %{{.*}}, %{{.*}}
+  %0 = llvm.udiv exact %arg0, %arg1 : i64
+  // CHECK: %{{.*}} = sdiv exact i64 %{{.*}}, %{{.*}}
+  %1 = llvm.sdiv exact %arg0, %arg1 : i64
+  // CHECK: %{{.*}} = lshr exact i64 %{{.*}}, %{{.*}}
+  %2 = llvm.lshr exact %arg0, %arg1 : i64
+  // CHECK: %{{.*}} = ashr exact i64 %{{.*}}, %{{.*}}
+  %3 = llvm.ashr exact %arg0, %arg1 : i64
+  llvm.return
+}

Copy link
Contributor

@Dinistro Dinistro left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this contribution 🙂
Very nice work, LGTM % a small nit comment.

Comment on lines 689 to 691
bool value = inst->isExact();

iface.setIsExact(value);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
bool value = inst->isExact();
iface.setIsExact(value);
iface.setIsExact(inst->isExact());

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

Copy link
Contributor

@gysit gysit left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding the flag!

LGTM modulo nits.

@@ -76,6 +76,24 @@ class LLVM_IntArithmeticOpWithOverflowFlag<string mnemonic, string instName,
"$res = builder.Create" # instName #
"($lhs, $rhs, /*Name=*/\"\", op.hasNoUnsignedWrap(), op.hasNoSignedWrap());";
}
class LLVM_IntArithmeticOpWithIsExact<string mnemonic, string instName,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
class LLVM_IntArithmeticOpWithIsExact<string mnemonic, string instName,
class LLVM_IntArithmeticOpWithExactFlag<string mnemonic, string instName,

nit: Should we use ExactFlag to follow the naming of LLVM_IntArithmeticOpWithIsExact?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

@@ -49,6 +49,16 @@ func.func @ops(%arg0: i32, %arg1: f32,
%mul_flag = llvm.mul %arg0, %arg0 overflow<nsw, nuw> : i32
%shl_flag = llvm.shl %arg0, %arg0 overflow<nuw, nsw> : i32

// Integer exact
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Integer exact
// Integer exact flag.

ultra nit:

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

tobiasgrosser pushed a commit to xdslproject/xdsl that referenced this pull request Nov 8, 2024
This changes the representation of the exact attribute from a mandatory
bool to an optional Unit.

This is to follow the syntax introduced by
llvm/llvm-project#115327
@lfrenot
Copy link
Contributor Author

lfrenot commented Nov 8, 2024

If everything is fixed, is it possible for someone with write access to merge the PR?

@tobiasgrosser
Copy link
Contributor

@Dinistro @gysit @zero9178, thank you for helping with this PR (and potentially merging it when ready).

@gysit gysit merged commit afa178d into llvm:main Nov 8, 2024
8 checks passed
Copy link

github-actions bot commented Nov 8, 2024

@lfrenot Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@lfrenot lfrenot deleted the mlir-llvm-exact branch November 8, 2024 14:40
Groverkss pushed a commit to iree-org/llvm-project that referenced this pull request Nov 15, 2024
The implementation is mostly based on the one existing for the nsw and
nuw flags.

If the exact flag is present, the corresponding operation returns a
poison value when the result is not exact. (For a division, if rounding
happens; for a right shift, if a non-zero bit is shifted out.)
EdmundGoodman pushed a commit to EdmundGoodman/xdsl that referenced this pull request Dec 6, 2024
…ct#3408)

This changes the representation of the exact attribute from a mandatory
bool to an optional Unit.

This is to follow the syntax introduced by
llvm/llvm-project#115327
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants