QIR in the MQT¶
The Quantum Intermediate Representation (QIR) expresses quantum programs in LLVM IR. The MQT Compiler Collection compiles OpenQASM, Qiskit circuits, and its own program objects to QIR. Quantum operations become calls to quantum instruction set (QIS) functions, while LLVM instructions express classical computation and control flow. A QIR profile specifies which features an execution environment must support.
The bundled DDSIM device executes QIR through QDMI, with the same job and result API used for OpenQASM.
This notebook follows that complete path: compile a program, inspect its profile and capability flags, choose LLVM text or bitcode, and retrieve counts or QIR output records. See [2] for background on QIR support in MQT.
Download this notebook
and the shared requirements.txt.
Follow the notebook setup to run it locally. All
examples use the bundled simulator and need no hardware account.
For experiments that compare static circuits with measurement feedback, continue with the QIR tutorial.
Compile a Base Profile program¶
Use the Base Profile for a circuit whose measurements do not control subsequent
quantum operations and whose QIR calls use constant arguments without runtime
storage. Native gates that pack controls into runtime arrays require the
Adaptive Profile. This Bell circuit produces the outcomes 00 and 11.
1from mqt.core.mlir import OutputFormat, QIRProfile, compile_program
2
3bell_qasm = """OPENQASM 3.0;
4include "stdgates.inc";
5qubit[2] q;
6h q[0];
7cx q[0], q[1];
8bit[2] result = measure q;
9"""
10
11base = compile_program(bell_qasm, output=OutputFormat.QIR_BASE)
12assert base.profile is QIRProfile.BASE
13base_llvm = base.to_llvm_ir(copy=True)
14print(base_llvm)
; ModuleID = 'LLVMDialectModule'
source_filename = "LLVMDialectModule"
@qir.result_label_result_1 = internal constant [9 x i8] c"result_1\00"
@qir.result_label_result_0 = internal constant [9 x i8] c"result_0\00"
@qir.result_label_result = internal constant [7 x i8] c"result\00"
define i64 @main() #0 {
call void @__quantum__rt__initialize(ptr null)
br label %1
1: ; preds = %0
call void @__quantum__qis__h__body(ptr null)
call void @__quantum__qis__cx__body(ptr null, ptr inttoptr (i64 1 to ptr))
br label %2
2: ; preds = %1
call void @__quantum__qis__mz__body(ptr null, ptr null)
call void @__quantum__qis__mz__body(ptr inttoptr (i64 1 to ptr), ptr inttoptr (i64 1 to ptr))
br label %3
3: ; preds = %2
call void @__quantum__rt__array_record_output(i64 2, ptr @qir.result_label_result)
call void @__quantum__rt__result_record_output(ptr null, ptr @qir.result_label_result_0)
call void @__quantum__rt__result_record_output(ptr inttoptr (i64 1 to ptr), ptr @qir.result_label_result_1)
ret i64 0
}
declare void @__quantum__rt__initialize(ptr)
declare void @__quantum__qis__h__body(ptr)
declare void @__quantum__qis__cx__body(ptr, ptr)
declare void @__quantum__qis__mz__body(ptr, ptr writeonly) #1
declare void @__quantum__rt__array_record_output(i64, ptr)
declare void @__quantum__rt__result_record_output(ptr, ptr)
attributes #0 = { "entry_point" "output_labeling_schema"="labeled" "qir_profiles"="base_profile" "required_num_qubits"="2" "required_num_results"="2" }
attributes #1 = { "irreversible" }
!llvm.module.flags = !{!0, !1, !2, !3, !4}
!0 = !{i32 1, !"qir_major_version", i32 2}
!1 = !{i32 7, !"qir_minor_version", i32 0}
!2 = !{i32 1, !"dynamic_qubit_management", i1 false}
!3 = !{i32 1, !"dynamic_result_management", i1 false}
!4 = !{i32 2, !"Debug Info Version", i32 3}
For synchronous simulation, the program provides sample(shots=1024, seed=0)
and simulate() without consuming it. These use the bundled DDSIM worker;
simulate() returns an uncollapsed NumPy statevector in QIR runtime qubit
order, which can differ from source-circuit order after compilation. It rejects
reset or measurement-dependent feedback. The top-level mqt.core.mlir.sample
and simulate functions also accept compiled QIR programs.
1print(base.sample(shots=32, seed=71))
2print(base.simulate())
{'00': 13, '11': 19}
[0.70710678+0.j 0. +0.j 0. +0.j 0.70710678+0.j]
The returned QIRProgram owns the compiled program.
Its to_llvm_ir() method consumes it and
returns LLVM assembly. Here, copy=True keeps the program for bitcode export
below. The entry-point attributes identify base_profile, the output schema,
and the required static qubit and result capacities. The module flags identify
the minimum required QIR version and whether dynamic resource management is
used. By default, Base Profile programs use QIR 2.0. Adaptive programs use 2.1
when they require dynamic qubit or result allocation, or runtime arrays; other
Adaptive programs use 2.0. Output labels and ordinary output-array records do
not require 2.1. A target environment can constrain accepted versions, for
example >=2,<3. Compilation selects the lowest known version that satisfies
the program and target; a range of >=2.1,<3 therefore emits 2.1 even for a
program with only static resources. A bare numeric target version remains a
same-major upper bound.
For a custom pipeline, a QCProgram also provides
to_qir(QIRProfile.BASE) and to_qir(QIRProfile.ADAPTIVE). These conversions
consume that program unless copy=True is set. They lower prepared QC without
inlining calls, expanding modifiers, or optimizing the resulting QIR. Calls with
quantum-register arguments must already be inlined. Base conversion requires
straight-line quantum operations; Adaptive conversion retains loops. Use
compile_program for optimization, inlining, modifier expansion, and bounded
Base loop unrolling. It also consumes typed MLIR programs unless copy=True is
set.
Execute LLVM text or bitcode¶
For a synchronous result, pass LLVM text as str or bitcode as bytes to
sample or simulate. MQT Core reads the entry point’s Base or Adaptive
profile and the QIR version from module metadata. QIR supports seed 0 for
randomness and positive signed 32-bit seeds. Reproducibility requires the same
program, build, execution path, and worker configuration. A profile declaration
is not LLVM conformance validation. Use the QDMI job API below for asynchronous
execution and additional result types.
1from mqt.core.mlir import sample, simulate
2
3print(sample(base_llvm, shots=32, seed=71))
4print(simulate(base_llvm))
{'00': 13, '11': 19}
[0.70710678+0.j 0. +0.j 0. +0.j 0.70710678+0.j]
The serialization and QDMI format must agree:
Profile |
LLVM text ( |
LLVM bitcode ( |
|---|---|---|
Base |
|
|
Adaptive |
|
|
Open DDSIM by its stable device ID and submit the Base program as text:
1from mqt.core.qdmi import ProgramFormat
2from mqt.core.qdmi import open_device
3
4device = open_device("mqt.ddsim.default")
5job = device.submit_job(base_llvm, ProgramFormat.QIR_BASE_STRING, num_shots=256, custom1=7)
6assert job.wait()
7counts = job.get_counts()
8assert set(counts) <= {"00", "11"} and sum(counts.values()) == 256
9counts
{'00': 125, '11': 131}
custom1 is DDSIM’s positive integer sampling seed. Use
to_bitcode() to serialize the same program to
LLVM bitcode, then submit those bytes without an intermediate file:
1bitcode = base.to_bitcode()
2assert isinstance(bitcode, bytes)
3binary_job = device.submit_job(bitcode, ProgramFormat.QIR_BASE_MODULE, num_shots=256, custom1=7)
4assert binary_job.wait()
5assert binary_job.get_program(bytes) == bitcode
6assert binary_job.get_counts() == counts
7print(f"Bitcode: {len(bitcode)} bytes")
8print(binary_job.get_counts())
Bitcode: 3080 bytes
{'00': 125, '11': 131}
To save these programs, use Path("bell.bc").write_bytes(bitcode) or
Path("bell.ll").write_text(base_llvm) after importing Path from pathlib.
For a program that has not yet been exported, write_bitcode(path) consumes it
and writes bitcode directly. The command-line equivalents are:
mqt-core compile bell.qasm --emit=qir-base -o bell.ll
mqt-core compile bell.qasm --emit=qir-adaptive -o bell.bc
Adaptive Profile and capability flags¶
The Adaptive Profile permits measurement-dependent control flow. This program
measures a superposition, then flips and measures the qubit again if the result
was 1. It always returns 0; the loop exits after at most one iteration.
1feedback_qasm = """OPENQASM 3.0;
2include "stdgates.inc";
3qubit q;
4h q;
5bit result = measure q;
6while (result) {
7 x q;
8 result = measure q;
9}
10"""
11
12adaptive = compile_program(feedback_qasm, output=OutputFormat.QIR_ADAPTIVE)
13assert adaptive.profile is QIRProfile.ADAPTIVE
The compiler derives capability flags from the lowered program. There is no need to write LLVM metadata yourself. Inspect the entry-point attributes and flags:
attributes #0 = { "entry_point" "output_labeling_schema"="labeled" "qir_profiles"="adaptive_profile" "required_num_qubits"="0" "required_num_results"="1" }
!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6}
!0 = !{i32 1, !"qir_major_version", i32 2}
!1 = !{i32 7, !"qir_minor_version", i32 1}
!2 = !{i32 1, !"dynamic_qubit_management", i1 true}
!3 = !{i32 1, !"dynamic_result_management", i1 false}
!4 = !{i32 1, !"backwards_branching", i2 -2}
!5 = !{i32 1, !"arrays", i1 true}
!6 = !{i32 2, !"Debug Info Version", i32 3}
For this program, backwards_branching records the conditional loop, arrays
records the result array, and dynamic_qubit_management and
dynamic_result_management describe resource allocation. LLVM prints the
conditional-loop bit pattern as i2 -2 (binary 10). Other programs can also
carry int_computations, float_computations, ir_functions,
multiple_target_branching, and multiple_return_points flags when their
lowered instructions require those capabilities.
A profile name alone does not describe every device’s capabilities. When compiling for a device, use the target-compilation API to select its supported operations, program format, and control-flow capabilities. DDSIM supports this Adaptive program in both encodings:
1adaptive_bitcode = adaptive.to_bitcode()
2for payload, program_format in (
3 (adaptive_llvm, ProgramFormat.QIR_ADAPTIVE_STRING),
4 (adaptive_bitcode, ProgramFormat.QIR_ADAPTIVE_MODULE),
5):
6 adaptive_job = device.submit_job(payload, program_format, num_shots=32, custom1=7)
7 assert adaptive_job.wait()
8 assert adaptive_job.get_counts() == {"0": 32}
9 print(program_format.name, adaptive_job.get_counts())
QIR_ADAPTIVE_STRING {'0': 32}
QIR_ADAPTIVE_MODULE {'0': 32}
From a Qiskit circuit to QIR¶
Pass a Qiskit QuantumCircuit directly to compile_program, then export the
result as LLVM text or bitcode:
1qir = compile_program(circuit, output=OutputFormat.QIR_BASE)
2bitcode = qir.to_bitcode()
Select OutputFormat.QIR_ADAPTIVE for supported Qiskit control flow. The
Qiskit interface guide describes the accepted operations
and circuits. Compilation preserves the input circuit.
When execution is the goal, let the compiler select a device-compatible format:
1from mqt.core.mlir import submit_program
2
3compiled = compile_program(circuit, target=device)
4qiskit_job = submit_program(compiled, target=device, num_shots=256, custom1=7)
5assert qiskit_job.wait()
6assert set(qiskit_job.get_counts()) <= {"00", "11"}
7print(compiled.program_format.name)
8print(qiskit_job.get_counts())
QASM3
{'00': 125, '11': 131}
Retrieve the QIR output stream through QDMI¶
Counts summarize the measurement results and Boolean values returned by the program. To inspect more of the QIR output, capture its textual output stream. The stream includes labels, array and tuple structure, other recorded scalar values, and boundaries between shots.
Adaptive compilation records computed Boolean results directly. For classical registers, it preserves both result order and the values at the time they were read. Registers containing only measurements can use QIR result arrays when stores can be combined safely; computed values and runtime-indexed stores use Boolean storage.
Enable capture with DDSIM’s boolean custom2 parameter, then request the stream
from CustomProperty.CUSTOM1:
1from mqt.core.qdmi import CustomProperty
2
3recorded_job = device.submit_job(
4 adaptive_bitcode, ProgramFormat.QIR_ADAPTIVE_MODULE, num_shots=2, custom1=7, custom2=True
5)
6assert recorded_job.wait()
7output = recorded_job.get_custom_result(CustomProperty.CUSTOM1, str)
8assert isinstance(output, str)
9assert output.count("START\n") == 2 and output.count("END\t0\n") == 2
10print(output, end="")
11print("Counts:", recorded_job.get_counts())
12assert recorded_job.get_counts() == {"0": 2}
HEADER schema_id labeled
HEADER schema_version 2.1
START
METADATA entry_point
METADATA output_labeling_schema labeled
METADATA qir_profiles adaptive_profile
METADATA required_num_qubits 0
METADATA required_num_results 1
OUTPUT RESULT_ARRAY 0 result
END 0
START
METADATA entry_point
METADATA output_labeling_schema labeled
METADATA qir_profiles adaptive_profile
METADATA required_num_qubits 0
METADATA required_num_results 1
OUTPUT RESULT_ARRAY 0 result
END 0
Counts: {'0': 2}
The parameter and result slots are separate: job parameter CUSTOM1 is the seed; job result CUSTOM1 contains the captured text. The same capture API works for Base and Adaptive profiles, with text or bitcode input.
Capture is off by default. The stream uses QIR record order; QDMI shots and counts place the highest-index bit first. Capture jobs provide both results, and terminal sampling can also retain an uncollapsed statevector. See DDSIM for capture limits and the C API.
Execution requirements¶
The following details matter when exchanging QIR with another compiler or building on the C++ runtime. For ordinary compilation and execution, the Python examples above handle serialization, runtime setup, and result retrieval.
Runtime failures¶
The QIR allocation contract provides an optional error-output pointer. This runtime uses it to report invalid requests and qubit or result limits, releasing partial allocations. Without that pointer, these failures emit a diagnostic and terminate execution. Host-memory exhaustion and other unhandled runtime failures also terminate, even with an error-output pointer; C++ and Python exceptions cannot catch them. Setup and compilation errors remain recoverable.
Use DDSIM through QDMI to contain execution failures in a worker process and keep the host usable.
Runtime and QIS compatibility¶
QIR entry points take no arguments and return an i64 exit code. Bind named
program parameters before lowering to either supported profile. Runtime and QIS
declarations are checked before JIT compilation; a mismatched or unsupported
declaration is reported with its actual and accepted LLVM function types.
QC-to-QIR conversion records direct measurement and CBit-register returns in
source order, including repetitions, and emits exit code 0 for successful
execution. Adaptive Profile also records computed Boolean (i1) results
directly, without output-register storage. Other entry results are unsupported,
including a constant-zero i64: explicit QC and QCO returns are program data,
never exit codes. Programs without results use a void QC or QCO entry function.
These requirements apply with and without a target. Keep other classical
temporaries local, or use OpenQASM or jeff interchange for wider scalar program
outputs.
Base Profile requires every recorded bit to come from a measurement. Static Result storage has no specified initial value; use Adaptive Profile for outputs that retain their classical zero initialization.
Measurements and CBit allocations must be in the entry function. A returned scalar measurement can share Result storage with a register only when constant store indices exclude overwriting its slot. The C++ QIR builder requires dynamic qubits to be allocated before control flow.
Authored QIR can return explicit exit codes and use scalar output-recording APIs. These runtime features do not extend the supported QC-to-QIR entry results.
MQT Core implements the QIR Base and Adaptive Profile runtime APIs. The JIT accepts one exact LLVM type for each runtime declaration, so unsupported or outdated overloads fail before execution. Present version flags must be nonnegative integers with major version 2. Future minor versions are accepted assuming existing constructs and runtime ABIs remain compatible; unsupported runtime calls still fail. Authored programs without version flags are accepted; their runtime declarations still undergo the same type checks.
Classical array copies require ranked memrefs. Fixed contiguous copies use
LLVM array loads and stores;
other layouts use loops and require the corresponding backwards-branching
capability. Math operations such as sqrt lower to LLVM intrinsics. DDSIM
executes these intrinsics, but they are outside the
floating-point instructions required by QIR.
Check the backend’s extensions when using these operations.
MQT Core provides dedicated QIS functions for variants with one or two control
qubits, using the c<gate> and cc<gate> names. Operations with three or more
controls use generic __ctl and __ctladj specializations. A target that
advertises only a variadic gate uses the generic form even with one or two
controls. The control qubits are passed in an Array; parameterized and
multi-target gates pass their original arguments in a Tuple, following the
QIR-Runner calling convention. MQT accepts these functions as runtime extensions
in authored QIR with either profile attribute. Compiler-generated Base QIR
follows the
Base Profile instruction restrictions,
which exclude the allocation and stores used by generic controlled calls. Use
Adaptive QIR to retain these native calls, or compile for a target with
dedicated controlled instructions or a gate set that requires decomposition.
MQT’s two-angle phased-X rotation gate uses the prx QIS stem. The incompatible
QIR-Runner Pauli-axis operation named r is not part of MQT’s QIS.
Program data and result access¶
The QDMI Device accepts jobs in the following program formats: QASM2, QASM3, QIR Base/Adaptive Profile Module (LLVM bitcode), and QIR Base/Adaptive Profile String (LLVM assembly).
QDMI C++ applications pass a std::string to Device::submitJob for a text
program, or a std::span<const std::byte> for a binary module. The same method
accepts a span of text or binary programs for a multi-program job.
Device::supportsJob checks whether the device accepts a format, program count,
and set of job parameters without sending programs or submitting a job. Text
includes the required terminator once; binary programs preserve their exact
bytes, including embedded nulls. Job::getProgramBytes() retrieves those bytes
without interpreting their contents or removing terminal null bytes.
Job::getProgram() retrieves null-terminated text. It rejects known binary and
non-text formats based on their QDMI format identifier, even if their data
happens to end in a null byte.
The Python API follows the same distinction: pass str or bytes to
Device.submit_job for one program, or a sequence of either type for multiple
programs. Job.get_program(bytes) returns the exact program bytes. By default,
Job.get_program() decodes a null-terminated text program and rejects known
binary or non-text formats. The num_shots argument is optional for
device-defined formats that encode their repetition count in the program.
Direct host functions called by the JIT must obey their declared ABI and must
not throw. Host function pointers cannot be sent to a DDSIM worker because they
belong to the host process. JitSession::create returns an owned session or an
llvm::Error. run and the sampling methods return llvm::Expected<int64_t>:
a completed program returns its exit code, including nonzero codes, while
recoverable validation failures return owned errors. Unhandled QIR runtime
failures still terminate; see runtime failures. Textual
output uses a borrowed llvm::raw_ostream that must outlive the session;
passing null disables it.
Every DDSIM QIR job owns its JIT session, runtime, simulator state, random-number generator, and output settings. QIR jobs can therefore execute concurrently without sharing measurements or output records. DDSIM records result bits directly and formats textual records only when capture is enabled.
For sampling programs that cannot use terminal sampling, the JIT runs LLVM’s O1 module simplification pipeline with automatic loop unrolling disabled. Inlining and loop simplification reduce repeated classical work. State extraction and programs eligible for terminal sampling skip this pipeline. Exported QIR uses profile-preserving cleanup, including promotion of local classical storage to SSA values. The JIT simplifies its private module before native code generation.
Sampling and state extraction¶
Sampling supports Base and Adaptive formats. For either profile with an acyclic, unconditional entry path, constant gate arguments, terminal Z measurements and scalar result records, DDSIM prepares the DD once and samples it for all shots. The runtime preserves repeated or reordered results, constant numeric records, and tuple or array headers. Classical memory accesses, helper calls, conditional branches, resets, dynamic resources, global destructors, Boolean output records, and generic controlled argument arrays exclude this terminal optimization.
With capture disabled, JitSession::sampleCounts can group shots by measurement
outcomes and replay deterministic prefixes for sibling paths. After
simplification, eligible programs use only local stack memory, defined constant
globals, direct supported QIR calls, and deterministic scalar LLVM intrinsics.
Remaining helper calls, heap-allocated classical arrays, lifecycle hooks, native
effects, and pointer-address observations exclude grouping. If such a program
also has no result reads or explicit resets, a trial defers measurements and
collects the output projection, including dynamically allocated result arrays.
Gates on measured wires or reuse of released qubits reject the trial. Successful
trials sample a histogram directly from the retained DD; rejected trials use
ordinary grouped sampling. Other supported programs execute once per shot.
A fixed seed reproduces outcomes for the same execution path; sequences need not match across different sampling algorithms or software versions.
When provided for static resources, required_num_qubits and
required_num_results specify capacities, and out-of-range IDs are rejected.
Extracted states include unused qubits within the declared capacity, initialized
to zero. Programs without those attributes retain the runtime’s inference of
static IDs or dynamic allocations. During sampling, dynamic qubit release resets
and recycles the simulator wire; the qubit limit applies to peak simultaneous
allocations rather than their cumulative number in a shot. Released handles
remain invalid.
Statevector extraction supports Base and Adaptive formats. Base extraction stops
before the first irreversible call and requires a terminal irreversible
region; defined or indirect helpers remain unsupported for that path.
Adaptive extraction executes classical loops, branches, dynamically computed gate arguments, dynamic allocations and direct helper calls while deferring Z measurements. A measured wire cannot participate in later gates, controls or SWAPs; independent wires may still evolve. Resets and measurement-dependent computation are unsupported. Result reads must be unused or feed only direct boolean output records. Indirect calls and unknown external functions are rejected before execution. Calls cannot re-enter the entry point. Initialization, when present, must be the first instruction of the entry point. These restrictions also apply inside helpers.
During Adaptive extraction, each executed allocation adds a zero-initialized wire. Release calls mark lifetimes without resetting or recycling simulator wires, so the exported state retains all allocated wires in allocation order, including unused and released wires. The qubit limit therefore applies to all allocations in one extraction run. Each run resets the quantum runtime. Output records are suppressed, and unsupported operations produce a failed QDMI job. Both profiles preserve global phase and program wire order, including SWAPs. LLVM target triples must match the host architecture and operating system because the JIT executes in process.