Skip to content

✨ Add MLIR pass for merging rotation gates #1019

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 45 commits into from
Jul 3, 2025
Merged
Show file tree
Hide file tree
Changes from 42 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
c606307
Begin implementing merge pass [skip ci]
denialhaag Jun 23, 2025
5bf980e
Continue implementing merge pass [skip ci]
denialhaag Jun 24, 2025
02f92c5
At least fix the segmentation fault [no ci]
denialhaag Jun 24, 2025
e8dc6d5
Make some progress [skip ci]
denialhaag Jun 24, 2025
a64c0cf
Actually make it work for rx gates!
denialhaag Jun 25, 2025
0ca5c6a
Remove setParams() again
denialhaag Jun 25, 2025
76060dd
Fix linter warnings
denialhaag Jun 25, 2025
1c6d7ec
Define createNewUser() function
denialhaag Jun 25, 2025
c3c4991
Support more gates without testing if it works
denialhaag Jun 25, 2025
df0ed8f
Test more single-qubit gates
denialhaag Jun 25, 2025
b7ccbbf
Test two-qubit gates
denialhaag Jun 25, 2025
c0e65ae
Only support simple gates for now
denialhaag Jun 25, 2025
f315ac2
Fix linter warnings
denialhaag Jun 25, 2025
00114af
Fix remaining linter warning
denialhaag Jun 25, 2025
5605dde
Also support rzx gate
denialhaag Jun 25, 2025
a3713c9
Define rewriteSingleAdditiveParam() function
denialhaag Jun 27, 2025
e71748c
Perform addition on underlying doubles
denialhaag Jun 27, 2025
6a29212
Support cancellation of gates without testing it
denialhaag Jun 27, 2025
d1d0653
Test cancellation
denialhaag Jun 27, 2025
8f7269f
Support cancellation also for xxminusyy and xxplusyy
denialhaag Jun 27, 2025
733fc23
Support cancellation also for u and u2 without testing it
denialhaag Jun 27, 2025
77f8d67
Add separators to tests
denialhaag Jun 27, 2025
0151be7
Fix matching
denialhaag Jun 27, 2025
06270d4
Test cancellation of u and u2
denialhaag Jun 27, 2025
7c89b99
Improve test comments
denialhaag Jun 27, 2025
a2f481a
Fix linter warnings
denialhaag Jun 27, 2025
7e1d6ef
Fix more linter warnings
denialhaag Jun 27, 2025
161f6e7
One more attempt at fixing linter warnings
denialhaag Jun 27, 2025
f8205b0
Merge branch 'main' into merge-pass
denialhaag Jun 27, 2025
0164648
Erase op at the very end
denialhaag Jun 30, 2025
9336060
Improve docstrings
denialhaag Jun 30, 2025
23078e5
Merge branch 'main' into merge-pass
denialhaag Jun 30, 2025
fb8465b
Only support strict merging of simple rotation gates for now
denialhaag Jun 30, 2025
608f81b
Improve tests for single-qubit gates
denialhaag Jun 30, 2025
bfa273c
Improve tests for multi-qubit gates
denialhaag Jun 30, 2025
a9f82a1
Add entry to changelog
denialhaag Jun 30, 2025
96a9af6
Clean up check statements
denialhaag Jul 1, 2025
76f6c13
Add more test cases of incompatible gates
denialhaag Jul 1, 2025
9f9ddcc
Also test variable angles
denialhaag Jul 1, 2025
577244d
Reuse set of mergeable gates
denialhaag Jul 2, 2025
4d8510f
🎨 pre-commit fixes
pre-commit-ci[bot] Jul 2, 2025
464a255
Merge branch 'main' into merge-pass
burgholzer Jul 2, 2025
aa3d444
Also support p gate
denialhaag Jul 3, 2025
ddaefd1
Add comment to test
denialhaag Jul 3, 2025
c20b21f
Define template function to reduce code duplication
denialhaag Jul 3, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ This project adheres to [Semantic Versioning], with the exception that minor rel

### Added

- ✨ Add MLIR pass for merging rotation gates ([#1019]) ([**@denialhaag**])
- ✨ Add functions to generate random vector DDs ([#975]) ([**@MatthiasReumann**])
- ✨ Add function to approximate decision diagrams ([#908]) ([**@MatthiasReumann**])
- 📦 Add Windows ARM64 wheels ([#926]) ([**@burgholzer**])
Expand Down Expand Up @@ -119,6 +120,7 @@ _📚 Refer to the [GitHub Release Notes](https://github.com/munich-quantum-tool
<!-- PR links -->

[#1020]: https://github.com/munich-quantum-toolkit/core/pull/1020
[#1019]: https://github.com/munich-quantum-toolkit/core/pull/1019
[#984]: https://github.com/munich-quantum-toolkit/core/pull/984
[#982]: https://github.com/munich-quantum-toolkit/core/pull/982
[#975]: https://github.com/munich-quantum-toolkit/core/pull/975
Expand Down
9 changes: 9 additions & 0 deletions mlir/include/mlir/Dialect/MQTOpt/IR/MQTOptInterfaces.td
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,15 @@ def UnitaryInterface : OpInterface<"UnitaryInterface"> {
operands.insert(operands.end(), outQubits.begin(), outQubits.end());
operands.insert(operands.end(), controls.begin(), controls.end());
return operands;
}]>,
InterfaceMethod<
/*desc=*/ "Get params.",
/*returnType=*/ "mlir::ValueRange",
/*methodName=*/ "getParams",
/*args=*/ (ins),
/*methodBody=*/ [{}],
/*defaultImpl=*/ [{
return $_op.getParams();
}]>
];

Expand Down
1 change: 1 addition & 0 deletions mlir/include/mlir/Dialect/MQTOpt/Transforms/Passes.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ namespace mqt::ir::opt {
#include "mlir/Dialect/MQTOpt/Transforms/Passes.h.inc" // IWYU pragma: export

void populateCancelInversesPatterns(mlir::RewritePatternSet& patterns);
void populateMergeRotationGatesPatterns(mlir::RewritePatternSet& patterns);
void populateQuantumSinkShiftPatterns(mlir::RewritePatternSet& patterns);
void populateQuantumSinkPushPatterns(mlir::RewritePatternSet& patterns);
void populateToQuantumComputationPatterns(mlir::RewritePatternSet& patterns,
Expand Down
10 changes: 10 additions & 0 deletions mlir/include/mlir/Dialect/MQTOpt/Transforms/Passes.td
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ def CancelConsecutiveInverses : Pass<"cancel-consecutive-inverses", "mlir::Modul
}];
}

def MergeRotationGates : Pass<"merge-rotation-gates", "mlir::ModuleOp"> {
let summary = "This pass searches for consecutive applications of rotation gates that can be merged.";
let description = [{
Consecutive applications of gphase, rx, ry, rz, rxx, ryy, rzz, and rzx are merged into one by adding their angles.
The merged gate is currently not removed if the angles add up to zero.

This pass currently does not affect xxminusyy, xxplusyy, u, and u2.
}];
}

def QuantumSinkPass : Pass<"quantum-sink", "mlir::ModuleOp"> {
let summary = "This pass attempts to push down operations into branches for possible optimizations.";
let description = [{
Expand Down
45 changes: 45 additions & 0 deletions mlir/lib/Dialect/MQTOpt/Transforms/MergeRotationGates.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2023 - 2025 Chair for Design Automation, TUM
* Copyright (c) 2025 Munich Quantum Software Company GmbH
* All rights reserved.
*
* SPDX-License-Identifier: MIT
*
* Licensed under the MIT License
*/

#include "mlir/Dialect/Common/Compat.h"
#include "mlir/Dialect/MQTOpt/Transforms/Passes.h"

#include <mlir/IR/PatternMatch.h>
#include <mlir/Support/LLVM.h>
#include <utility>

namespace mqt::ir::opt {

#define GEN_PASS_DEF_MERGEROTATIONGATES
#include "mlir/Dialect/MQTOpt/Transforms/Passes.h.inc"

/**
* @brief This pattern attempts to merge consecutive rotation gates.
*/
struct MergeRotationGates final
: impl::MergeRotationGatesBase<MergeRotationGates> {

void runOnOperation() override {
// Get the current operation being operated on.
auto op = getOperation();
auto* ctx = &getContext();

// Define the set of patterns to use.
mlir::RewritePatternSet patterns(ctx);
populateMergeRotationGatesPatterns(patterns);

// Apply patterns in an iterative and greedy manner.
if (mlir::failed(APPLY_PATTERNS_GREEDILY(op, std::move(patterns)))) {
signalPassFailure();
}
}
};

} // namespace mqt::ir::opt
219 changes: 219 additions & 0 deletions mlir/lib/Dialect/MQTOpt/Transforms/MergeRotationGatesPattern.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
/*
* Copyright (c) 2023 - 2025 Chair for Design Automation, TUM
* Copyright (c) 2025 Munich Quantum Software Company GmbH
* All rights reserved.
*
* SPDX-License-Identifier: MIT
*
* Licensed under the MIT License
*/

#include "mlir/Dialect/MQTOpt/IR/MQTOptDialect.h"
#include "mlir/Dialect/MQTOpt/Transforms/Passes.h"
#include "mlir/IR/BuiltinAttributes.h"

#include <algorithm>
#include <cstddef>
#include <iterator>
#include <mlir/Dialect/Arith/IR/Arith.h>
#include <mlir/IR/MLIRContext.h>
#include <mlir/IR/Operation.h>
#include <mlir/IR/PatternMatch.h>
#include <mlir/IR/Value.h>
#include <mlir/IR/ValueRange.h>
#include <mlir/Support/LLVM.h>
#include <mlir/Support/LogicalResult.h>
#include <stdexcept>
#include <string>
#include <unordered_set>

namespace mqt::ir::opt {

static const std::unordered_set<std::string> MERGEABLE_GATES = {
"gphase", "rx", "ry", "rz", "rxx", "ryy", "rzz", "rzx"};

/**
* @brief This pattern attempts to merge consecutive rotation gates.
*/
struct MergeRotationGatesPattern final
: mlir::OpInterfaceRewritePattern<UnitaryInterface> {

explicit MergeRotationGatesPattern(mlir::MLIRContext* context)
: OpInterfaceRewritePattern(context) {}

/**
* @brief Checks if two gates can be merged.
*
* @param a The first gate.
* @param b The second gate.
* @return True if the gates can be merged, false otherwise.
*/
[[nodiscard]] static bool areGatesMergeable(mlir::Operation& a,
mlir::Operation& b) {
const auto aName = a.getName().stripDialect().str();
const auto bName = b.getName().stripDialect().str();

return ((aName == bName) && (MERGEABLE_GATES.count(aName) == 1));
}

/**
* @brief Checks if all users of an operation are the same.
*
* @param users The users to check.
* @return True if all users are the same, false otherwise.
*/
[[nodiscard]] static bool
areUsersUnique(const mlir::ResultRange::user_range& users) {
return std::none_of(users.begin(), users.end(),
[&](auto* user) { return user != *users.begin(); });
}

mlir::LogicalResult match(UnitaryInterface op) const override {
const auto& users = op->getUsers();
if (!areUsersUnique(users)) {
return mlir::failure();
}
auto* user = *users.begin();
if (!areGatesMergeable(*op, *user)) {
return mlir::failure();
}
auto unitaryUser = mlir::dyn_cast<UnitaryInterface>(user);
if (op.getAllOutQubits() != unitaryUser.getAllInQubits()) {
return mlir::failure();
}
if (op.getPosCtrlInQubits().size() !=
unitaryUser.getPosCtrlInQubits().size() ||
op.getNegCtrlInQubits().size() !=
unitaryUser.getNegCtrlInQubits().size()) {
// We only need to check the sizes, because the order of the controls was
// already checked by the previous condition.
return mlir::failure();
}
return mlir::success();
}

/**
* @brief Merges two consecutive rotation gates into a single gate.
*
* The function supports gphase, rx, ry, rz, rxx, ryy, rzz, and rzx.
* The gates are merged by adding their angles.
* The merged gate is not removed if the angles add up to zero.
*
* @param op The first instance of the rotation gate.
* @param rewriter The pattern rewriter.
*/
void static rewriteAdditiveAngle(UnitaryInterface op,
mlir::PatternRewriter& rewriter) {
auto const type = op->getName().stripDialect().str();

auto user = mlir::dyn_cast<UnitaryInterface>(*op->getUsers().begin());
auto loc = user->getLoc();

auto opParam = op.getParams()[0];
auto userParam = user.getParams()[0];

auto add = rewriter.create<mlir::arith::AddFOp>(loc, opParam, userParam);
const llvm::SmallVector<mlir::Value, 1> newParamsVec{add.getResult()};
const mlir::ValueRange newParams(newParamsVec);

auto userInQubits = user.getInQubits();
auto userPosCtrlInQubits = user.getPosCtrlInQubits();
auto userNegCtrlInQubits = user.getNegCtrlInQubits();

UnitaryInterface newUser;
if (type == "gphase") {
newUser = rewriter.create<GPhaseOp>(
loc, userInQubits.getType(), userPosCtrlInQubits.getType(),
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{},
mlir::DenseBoolArrayAttr{}, newParams, userInQubits,
userPosCtrlInQubits, userNegCtrlInQubits);
} else if (type == "rx") {
newUser = rewriter.create<RXOp>(
loc, userInQubits.getType(), userPosCtrlInQubits.getType(),
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{},
mlir::DenseBoolArrayAttr{}, newParams, userInQubits,
userPosCtrlInQubits, userNegCtrlInQubits);
} else if (type == "ry") {
newUser = rewriter.create<RYOp>(
loc, userInQubits.getType(), userPosCtrlInQubits.getType(),
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{},
mlir::DenseBoolArrayAttr{}, newParams, userInQubits,
userPosCtrlInQubits, userNegCtrlInQubits);
} else if (type == "rz") {
newUser = rewriter.create<RZOp>(
loc, userInQubits.getType(), userPosCtrlInQubits.getType(),
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{},
mlir::DenseBoolArrayAttr{}, newParams, userInQubits,
userPosCtrlInQubits, userNegCtrlInQubits);
} else if (type == "rxx") {
newUser = rewriter.create<RXXOp>(
loc, userInQubits.getType(), userPosCtrlInQubits.getType(),
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{},
mlir::DenseBoolArrayAttr{}, newParams, userInQubits,
userPosCtrlInQubits, userNegCtrlInQubits);
} else if (type == "ryy") {
newUser = rewriter.create<RYYOp>(
loc, userInQubits.getType(), userPosCtrlInQubits.getType(),
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{},
mlir::DenseBoolArrayAttr{}, newParams, userInQubits,
userPosCtrlInQubits, userNegCtrlInQubits);
} else if (type == "rzz") {
newUser = rewriter.create<RZZOp>(
loc, userInQubits.getType(), userPosCtrlInQubits.getType(),
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{},
mlir::DenseBoolArrayAttr{}, newParams, userInQubits,
userPosCtrlInQubits, userNegCtrlInQubits);
} else if (type == "rzx") {
newUser = rewriter.create<RZXOp>(
loc, userInQubits.getType(), userPosCtrlInQubits.getType(),
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{},
mlir::DenseBoolArrayAttr{}, newParams, userInQubits,
userPosCtrlInQubits, userNegCtrlInQubits);
} else {
throw std::runtime_error("Unsupported operation type: " + type);
}

// Prepare erasure of op
const auto& opAllInQubits = op.getAllInQubits();
const auto& newUserAllInQubits = newUser.getAllInQubits();
for (size_t i = 0; i < newUser->getOperands().size(); i++) {
const auto& operand = newUser->getOperand(i);
const auto found = std::find(newUserAllInQubits.begin(),
newUserAllInQubits.end(), operand);
if (found == newUserAllInQubits.end()) {
continue;
}
const auto idx = std::distance(newUserAllInQubits.begin(), found);
rewriter.modifyOpInPlace(
newUser, [&] { newUser->setOperand(i, opAllInQubits[idx]); });
}

// Replace user with newUser
rewriter.replaceOp(user, newUser);

// Erase op
rewriter.eraseOp(op);
}

void rewrite(UnitaryInterface op,
mlir::PatternRewriter& rewriter) const override {
auto const type = op->getName().stripDialect().str();

if (MERGEABLE_GATES.count(type) == 1) {
rewriteAdditiveAngle(op, rewriter);
} else {
throw std::runtime_error("Unsupported operation type: " + type);
}
}
};

/**
* @brief Populates the given pattern set with the `MergeRotationGatesPattern`.
*
* @param patterns The pattern set to populate.
*/
void populateMergeRotationGatesPatterns(mlir::RewritePatternSet& patterns) {
patterns.add<MergeRotationGatesPattern>(patterns.getContext());
}

} // namespace mqt::ir::opt
Loading
Loading