10 #include "mlir/IR/BuiltinOps.h"
11 #include "mlir/IR/Threading.h"
13 using namespace circt;
14 using namespace igraph;
33 return instanceRecord;
49 nodes.push_back(node);
56 "top-level operation must have a single block");
57 SmallVector<std::pair<ModuleOpInterface, SmallVector<InstanceOpInterface>>>
61 parent->getRegion(0).front().getOps<igraph::ModuleOpInterface>())
62 moduleToInstances.push_back({module, {}});
65 mlir::parallelFor(
parent->getContext(), 0, moduleToInstances.size(),
67 auto module = moduleToInstances[idx].first;
68 auto &instances = moduleToInstances[idx].second;
70 module.walk([&](InstanceOpInterface instanceOp) {
71 instances.push_back(instanceOp);
76 for (
auto &[module, instances] : moduleToInstances) {
77 auto name = module.getModuleNameAttr();
78 auto *currentNode = getOrAddNode(name);
79 currentNode->module = module;
80 for (
auto instanceOp : instances) {
82 for (
auto targetNameAttr : instanceOp.getReferencedModuleNamesAttr()) {
83 auto *targetNode = getOrAddNode(cast<StringAttr>(targetNameAttr));
84 currentNode->addInstance(instanceOp, targetNode);
91 assert(!
nodeMap.count(module.getModuleNameAttr()) &&
"module already added");
93 node->module = module;
94 nodeMap[module.getModuleNameAttr()] = node;
95 nodes.push_back(node);
101 "all instances of this module must have been erased.");
103 for (
auto *instance : llvm::make_early_inc_range(*node))
111 assert(it !=
nodeMap.end() &&
"Module not in InstanceGraph!");
116 return lookup(cast<ModuleOpInterface>(op).getModuleNameAttr());
120 InstanceOpInterface newInst) {
121 assert(inst.getReferencedModuleNamesAttr() ==
122 newInst.getReferencedModuleNamesAttr() &&
123 "Both instances must be targeting the same modules");
126 for (Attribute targetNameAttr : inst.getReferencedModuleNamesAttr()) {
128 auto *node =
lookup(cast<StringAttr>(targetNameAttr));
130 if (record->getInstance() == inst) {
133 record->instance = newInst;
140 ModuleOpInterface child, ModuleOpInterface parent,
142 DenseSet<InstanceGraphNode *> seen;
143 SmallVector<InstanceGraphNode *> worklist;
145 worklist.push_back(cn);
147 while (!worklist.empty()) {
148 auto *node = worklist.back();
152 for (
auto *use : node->
uses()) {
153 if (skipInstance(use))
155 auto *mod = use->getParent();
156 if (!seen.count(mod)) {
158 worklist.push_back(mod);
165 FailureOr<llvm::ArrayRef<InstanceGraphNode *>>
171 llvm::SetVector<InstanceGraphNode *> visited, marked;
172 llvm::SetVector<InstanceGraphNode *> candidateTopLevels(this->
begin(),
174 SmallVector<InstanceGraphNode *> cycleTrace;
180 if (visited.contains(node))
182 trace.push_back(node);
183 if (marked.contains(node)) {
189 for (
auto use : *node) {
191 candidateTopLevels.remove(targetModule);
192 if (cycleUtil(targetModule, trace))
196 visited.insert(node);
201 for (
auto moduleIt : *
this) {
202 if (visited.contains(moduleIt))
205 cyclic |= cycleUtil(moduleIt, {});
212 err <<
"cannot deduce top level module - cycle "
213 "detected in instance graph (";
216 [&](
auto node) { err << node->
getModule().getModuleName(); },
"->");
220 assert(!candidateTopLevels.empty() &&
221 "if non-cyclic, there should be at least 1 candidate top level");
224 candidateTopLevels.begin(), candidateTopLevels.end());
230 ArrayRef<InstancePath>
231 InstancePathCache::getAbsolutePaths(ModuleOpInterface op) {
232 return getAbsolutePaths(op, instanceGraph.getTopLevelNode());
236 ArrayRef<InstancePath>
237 InstancePathCache::getAbsolutePaths(ModuleOpInterface op,
246 auto cached = absolutePathsCache.find(op);
247 if (cached != absolutePathsCache.end())
248 return cached->second;
252 SmallVector<InstancePath, 8> extendedPaths;
253 for (
auto *inst : node->
uses()) {
254 if (
auto module = inst->getParent()->getModule()) {
255 auto instPaths = getAbsolutePaths(module);
256 extendedPaths.reserve(instPaths.size());
257 for (
auto path : instPaths) {
258 extendedPaths.push_back(appendInstance(
259 path, cast<InstanceOpInterface>(*inst->getInstance())));
262 extendedPaths.emplace_back(
empty);
267 ArrayRef<InstancePath> pathList;
268 if (!extendedPaths.empty()) {
269 auto *paths = allocator.Allocate<
InstancePath>(extendedPaths.size());
270 std::copy(extendedPaths.begin(), extendedPaths.end(), paths);
271 pathList = ArrayRef<InstancePath>(paths, extendedPaths.size());
273 absolutePathsCache.insert({op, pathList});
278 void InstancePath::print(llvm::raw_ostream &into)
const {
280 for (
unsigned i = 0, n = path.size(); i < n; ++i) {
283 into <<
"/" << inst.getInstanceName() <<
":";
284 auto names = inst.getReferencedModuleNamesAttr();
285 if (names.size() == 1) {
287 into << cast<StringAttr>(names[0]).getValue();
293 ->getParentOfType<ModuleOpInterface>()
298 llvm::interleaveComma(names, into, [&](Attribute name) {
299 into << cast<StringAttr>(name).getValue();
308 InstanceOpInterface inst) {
309 size_t n = path.
size() + 1;
310 auto *newPath = allocator.Allocate<InstanceOpInterface>(n);
311 std::copy(path.
begin(), path.
end(), newPath);
312 newPath[path.
size()] = inst;
316 InstancePath InstancePathCache::prependInstance(InstanceOpInterface inst,
318 size_t n = path.
size() + 1;
319 auto *newPath = allocator.Allocate<InstanceOpInterface>(n);
320 std::copy(path.
begin(), path.
end(), newPath + 1);
325 void InstancePathCache::replaceInstance(InstanceOpInterface oldOp,
326 InstanceOpInterface newOp) {
328 instanceGraph.replaceInstance(oldOp, newOp);
333 auto instanceExists = [&](
const ArrayRef<InstancePath> &paths) ->
bool {
335 paths, [&](
InstancePath p) {
return llvm::is_contained(p, oldOp); });
338 for (
auto &iter : absolutePathsCache) {
339 if (!instanceExists(iter.getSecond()))
341 SmallVector<InstancePath, 8> updatedPaths;
342 for (
auto path : iter.getSecond()) {
343 const auto *iter = llvm::find(path, oldOp);
344 if (iter == path.end()) {
346 updatedPaths.push_back(path);
349 auto *newPath = allocator.Allocate<InstanceOpInterface>(path.size());
350 llvm::copy(path, newPath);
351 newPath[iter - path.begin()] = newOp;
352 updatedPaths.push_back(
InstancePath(ArrayRef(newPath, path.size())));
356 auto *paths = allocator.Allocate<
InstancePath>(updatedPaths.size());
357 llvm::copy(updatedPaths, paths);
358 iter.getSecond() = ArrayRef<InstancePath>(paths, updatedPaths.size());
362 #include "circt/Support/InstanceGraphInterface.cpp.inc"
assert(baseType &&"element must be base type")
static InstancePath empty
void erase(igraph::InstanceGraphNode *node) override
Erases a module, updating links to entry.
This is a Node in the InstanceGraph.
friend class InstanceRecord
InstanceRecord * firstUse
List of instances which instantiate this module.
bool noUses()
Return true if there are no more instances of this module.
InstanceRecord * addInstance(InstanceOpInterface instance, InstanceGraphNode *target)
Record a new instance op in the body of this module.
auto getModule()
Get the module that this node is tracking.
InstanceList instances
List of instance operations in this module.
llvm::iterator_range< UseIterator > uses()
void recordUse(InstanceRecord *record)
Record that a module instantiates this module.
virtual InstanceGraphNode * addModule(ModuleOpInterface module)
Add a newly created module to the instance graph.
Operation * parent
The node under which all modules are nested.
llvm::DenseMap< Attribute, InstanceGraphNode * > nodeMap
This maps each operation to its graph node.
virtual void replaceInstance(InstanceOpInterface inst, InstanceOpInterface newInst)
Replaces an instance of a module with another instance.
FailureOr< llvm::ArrayRef< InstanceGraphNode * > > getInferredTopLevelNodes()
Get the nodes corresponding to the inferred top-level modules of a circuit.
llvm::SmallVector< InstanceGraphNode * > inferredTopLevelNodes
A caching of the inferred top level module(s).
NodeList nodes
The storage for graph nodes, with deterministic iteration.
bool isAncestor(ModuleOpInterface child, ModuleOpInterface parent, llvm::function_ref< bool(InstanceRecord *)> skipInstance=[](InstanceRecord *_) { return false;})
Check if child is instantiated by a parent.
InstanceGraphNode * lookup(ModuleOpInterface op)
Look up an InstanceGraphNode for a module.
Operation * getParent()
Return the parent under which all nodes are nested.
InstanceGraphNode * getOrAddNode(StringAttr name)
Get the node corresponding to the module.
InstanceGraph(Operation *parent)
Create a new module graph of a circuit.
An instance path composed of a series of instances.
ArrayRef< InstanceOpInterface >::iterator end() const
ArrayRef< InstanceOpInterface >::iterator begin() const
This is an edge in the InstanceGraph.
void erase()
Erase this instance record, removing it from the parent module and the target's use-list.
InstanceGraphNode * target
This is the module which the instance-like is instantiating.
InstanceRecord * nextUse
Intrusive linked list for other uses.
InstanceGraphNode * getParent() const
Get the module where the instantiation lives.
igraph::InstanceGraphNode InstanceGraphNode
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.