forked from NVIDIA/cuda-quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResourceCount.cpp
More file actions
63 lines (58 loc) · 2.63 KB
/
Copy pathResourceCount.cpp
File metadata and controls
63 lines (58 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*******************************************************************************
* Copyright (c) 2022 - 2026 NVIDIA Corporation & Affiliates. *
* All rights reserved. *
* *
* This source code and the accompanying materials are made available under *
* the terms of the Apache License 2.0 which accompanies this distribution. *
******************************************************************************/
#include "cudaq/Optimizer/Transforms/ResourceCount.h"
#include "PassDetails.h"
#include "cudaq/Optimizer/Transforms/Passes.h"
#include "mlir/Transforms/Passes.h"
using namespace mlir;
mlir::FailureOr<cudaq::Resources>
cudaq::opt::countResourcesFromIR(ModuleOp module) {
// Check upfront whether all qubit allocations have statically known sizes.
// If any veq has a dynamic size we cannot count qubits statically, so bail
// out before running the gate-erasing pass manager.
std::size_t allocated = 0;
bool unresolvedVeq = false;
module.walk([&](cudaq::quake::AllocaOp alloc) {
if (isa<cudaq::quake::RefType>(alloc.getType())) {
allocated++;
} else if (auto size = cudaq::quake::getVeqSize(alloc.getResult())) {
allocated += *size;
} else {
unresolvedVeq = true;
}
});
if (unresolvedVeq)
return failure();
// All qubit sizes are statically known — proceed to count gates and erase
// them from the IR so the subsequent JIT compiles a near-empty module.
cudaq::Resources counts;
auto countGate = [&counts](std::string gate,
std::vector<std::size_t> controls,
std::vector<std::size_t> targets, size_t count) {
for (size_t i = 0; i < count; i++)
counts.appendInstruction(gate, controls, targets);
};
ResourceCountPreprocessOptions opt{countGate};
// The countGate callback captures &counts, a shared mutable Resources.
// createResourceCountPreprocess runs as addNestedPass<func::FuncOp>, which
// MLIR executes in parallel across functions. Disable threading for this
// PassManager so the callback is called sequentially.
auto *ctx = module.getContext();
bool wasThreadingEnabled = ctx->isMultithreadingEnabled();
ctx->disableMultithreading();
PassManager pm(ctx);
pm.addNestedPass<func::FuncOp>(createResourceCountPreprocess(opt));
pm.addPass(createCanonicalizerPass());
auto pmResult = pm.run(module);
if (wasThreadingEnabled)
ctx->enableMultithreading();
if (failed(pmResult))
return failure();
counts.setNumQubits(allocated);
return counts;
}