/* * SubCircuit -- An implementation of the Ullmann Subgraph Isomorphism * algorithm for coarse grain logic networks * * Copyright (C) 2013 Claire Xenia Wolf * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "subcircuit.h" #include #include #include #include #ifdef _YOSYS_ # include "kernel/yosys.h" # define my_printf YOSYS_NAMESPACE_PREFIX log #else # define my_printf printf #endif using namespace SubCircuit; #ifndef _YOSYS_ static std::string my_stringf(const char *fmt, ...) { std::string string; char *str = NULL; va_list ap; va_start(ap, fmt); if (vasprintf(&str, fmt, ap) < 0) str = NULL; va_end(ap); if (str != NULL) { string = str; free(str); } return string; } #else # define my_stringf YOSYS_NAMESPACE_PREFIX stringf #endif SubCircuit::Graph::Graph(const Graph &other, const std::vector &otherNodes) { allExtern = other.allExtern; std::map other2this; for (int i = 0; i < int(otherNodes.size()); i++) { assert(other.nodeMap.count(otherNodes[i]) > 0); other2this[other.nodeMap.at(otherNodes[i])] = i; nodeMap[otherNodes[i]] = i; } std::map edges2this; for (auto &i1 : other2this) for (auto &i2 : other.nodes[i1.first].ports) for (auto &i3 : i2.bits) if (edges2this.count(i3.edgeIdx) == 0) { int next_idx = edges2this.size(); edges2this[i3.edgeIdx] = next_idx; } edges.resize(edges2this.size()); for (auto &it : edges2this) { for (auto &bit : other.edges[it.first].portBits) if (other2this.count(bit.nodeIdx) > 0) edges[it.second].portBits.insert(BitRef(other2this[bit.nodeIdx], bit.portIdx, bit.bitIdx)); edges[it.second].constValue = other.edges[it.first].constValue; edges[it.second].isExtern = other.edges[it.first].isExtern; } nodes.resize(other2this.size()); for (auto &it : other2this) { nodes[it.second] = other.nodes[it.first]; for (auto &i2 : nodes[it.second].ports) for (auto &i3 : i2.bits) i3.edgeIdx = edges2this.at(i3.edgeIdx); } } bool SubCircuit::Graph::BitRef::operator < (const BitRef &other) const { if (nodeIdx != other.nodeIdx) return nodeIdx < other.nodeIdx; if (portIdx != other.portIdx) return portIdx < other.portIdx; return bitIdx < other.bitIdx; } void SubCircuit::Graph::createNode(std::string nodeId, std::string typeId, void *userData, bool shared) { assert(nodeMap.count(nodeId) == 0); nodeMap[nodeId] = nodes.size(); nodes.push_back(Node()); Node &newNode = nodes.back(); newNode.nodeId = nodeId; newNode.typeId = typeId; newNode.userData = userData; newNode.shared = shared; } void SubCircuit::Graph::createPort(std::string nodeId, std::string portId, int width, int minWidth) { assert(nodeMap.count(nodeId) != 0); int nodeIdx = nodeMap[nodeId]; Node &node = nodes[nodeIdx]; assert(node.portMap.count(portId) == 0); int portIdx = node.ports.size(); node.portMap[portId] = portIdx; node.ports.push_back(Port()); Port &port = node.ports.back(); port.portId = portId; port.minWidth = minWidth < 0 ? width : minWidth; port.bits.insert(port.bits.end(), width, PortBit()); for (int i = 0; i < width; i++) { port.bits[i].edgeIdx = edges.size(); edges.push_back(Edge()); edges.back().portBits.insert(BitRef(nodeIdx, portIdx, i)); } } void SubCircuit::Graph::createConnection(std::string fromNodeId, std::string fromPortId, int fromBit, std::string toNodeId, std::string toPortId, int toBit, int width) { assert(nodeMap.count(fromNodeId) != 0); assert(nodeMap.count(toNodeId) != 0); int fromNodeIdx = nodeMap[fromNodeId]; Node &fromNode = nodes[fromNodeIdx]; int toNodeIdx = nodeMap[toNodeId]; Node &toNode = nodes[toNodeIdx]; assert(fromNode.portMap.count(fromPortId) != 0); assert(toNode.portMap.count(toPortId) != 0); int fromPortIdx = fromNode.portMap[fromPortId]; Port &fromPort = fromNode.ports[fromPortIdx]; int toPortIdx = toNode.portMap[toPortId]; Port &toPort = toNode.ports[toPortIdx]; if (width < 0) { assert(fromBit == 0 && toBit == 0); assert(fromPort.bits.size() == toPort.bits.size()); width = fromPort.bits.size(); } assert(fromBit >= 0 && toBit >= 0); for (int i = 0; i < width; i++) { assert(fromBit + i < int(fromPort.bits.size())); assert(toBit + i < int(toPort.bits.size())); int fromEdgeIdx = fromPort.bits[fromBit + i].edgeIdx; int toEdgeIdx = toPort.bits[toBit + i].edgeIdx; if (fromEdgeIdx == toEdgeIdx) continue; // merge toEdge into fromEdge if (edges[toEdgeIdx].isExtern) edges[fromEdgeIdx].isExtern = true; if (edges[toEdgeIdx].constValue) { assert(edges[fromEdgeIdx].constValue == 0); edges[fromEdgeIdx].constValue = edges[toEdgeIdx].constValue; } for (const auto &ref : edges[toEdgeIdx].portBits) { edges[fromEdgeIdx].portBits.insert(ref); nodes[ref.nodeIdx].ports[ref.portIdx].bits[ref.bitIdx].edgeIdx = fromEdgeIdx; } // remove toEdge (move last edge over toEdge if needed) if (toEdgeIdx+1 != int(edges.size())) { edges[toEdgeIdx] = edges.back(); for (const auto &ref : edges[toEdgeIdx].portBits) nodes[ref.nodeIdx].ports[ref.portIdx].bits[ref.bitIdx].edgeIdx = toEdgeIdx; } edges.pop_back(); } } void SubCircuit::Graph::createConnection(std::string fromNodeId, std::string fromPortId, std::string toNodeId, std::string toPortId) { createConnection(fromNodeId, fromPortId, 0, toNodeId, toPortId, 0, -1); } void SubCircuit::Graph::createConstant(std::string toNodeId, std::string toPortId, int toBit, int constValue) { assert(nodeMap.count(toNodeId) != 0); int toNodeIdx = nodeMap[toNodeId]; Node &toNode = nodes[toNodeIdx]; assert(toNode.portMap.count(toPortId) != 0); int toPortIdx = toNode.portMap[toPortId]; Port &toPort = toNode.ports[toPortIdx]; assert(toBit >= 0 && toBit < int(toPort.bits.size())); int toEdgeIdx = toPort.bits[toBit].edgeIdx; assert(edges[toEdgeIdx].constValue == 0); edges[toEdgeIdx].constValue = constValue; } void SubCircuit::Graph::createConstant(std::string toNodeId, std::string toPortId, int constValue) { assert(nodeMap.count(toNodeId) != 0); int toNodeIdx = nodeMap[toNodeId]; Node &toNode = nodes[toNodeIdx]; assert(toNode.portMap.count(toPortId) != 0); int toPortIdx = toNode.portMap[toPortId]; Port &toPort = toNode.ports[toPortIdx]; for (int i = 0; i < int(toPort.bits.size()); i++) { int toEdgeIdx = toPort.bits[i].edgeIdx; assert(edges[toEdgeIdx].constValue == 0); edges[toEdgeIdx].constValue = constValue % 2 ? '1' : '0'; constValue = constValue >> 1; } } void SubCircuit::Graph::markExtern(std::string nodeId, std::string portId, int bit) { assert(nodeMap.count(nodeId) != 0); Node &node = nodes[nodeMap[nodeId]]; assert(node.portMap.count(portId) != 0); Port &port = node.ports[node.portMap[portId]]; if (bit < 0) { for (const auto portBit : port.bits) edges[portBit.edgeIdx].isExtern = true; } else { assert(bit < int(port.bits.size())); edges[port.bits[bit].edgeIdx].isExtern = true; } } void SubCircuit::Graph::markAllExtern() { allExtern = true; } void SubCircuit::Graph::print() { for (int i = 0; i < int(nodes.size()); i++) { const Node &node = nodes[i]; my_printf("NODE %d: %s (%s)\n", i, node.nodeId.c_str(), node.typeId.c_str()); for (int j = 0; j < int(node.ports.size()); j++) { const Port &port = node.ports[j]; my_printf(" PORT %d: %s (%d/%d)\n", j, port.portId.c_str(), port.minWidth, int(port.bits.size())); for (int k = 0; k < int(port.bits.size()); k++) { int edgeIdx = port.bits[k].edgeIdx; my_printf(" BIT %d (%d):", k, edgeIdx); for (const auto &ref : edges[edgeIdx].portBits) my_printf(" %d.%d.%d", ref.nodeIdx, ref.portIdx, ref.bitIdx); if (edges[edgeIdx].isExtern) my_printf(" [extern]"); my_printf("\n"); } } } } class SubCircuit::SolverWorker { // basic internal data structures typedef std::vector> adjMatrix_t; struct GraphData { std::string graphId; Graph graph; adjMatrix_t adjMatrix; std::vector usedNodes; }; static void printAdjMatrix(const adjMatrix_t &matrix) { my_printf("%7s", ""); for (int i = 0; i < int(matrix.size()); i++) my_printf("%4d:", i); my_printf("\n"); for (int i = 0; i < int(matrix.size()); i++) { my_printf("%5d:", i); for (int j = 0; j < int(matrix.size()); j++) if (matrix.at(i).count(j) == 0) my_printf("%5s", "-"); else my_printf("%5d", matrix.at(i).at(j)); my_printf("\n"); } } // helper functions for handling permutations static constexpr int maxPermutationsLimit = 1000000; static int numberOfPermutations(const std::vector &list) { constexpr size_t mappedPermutationsSize = 10; constexpr int mappedPermutations[mappedPermutationsSize] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; assert(list.size() < mappedPermutationsSize); return mappedPermutations[list.size()]; } static void permutateVectorToMap(std::map &map, const std::vector &list, int idx) { // convert idx to a list.size() digits factoradic number std::vector factoradicDigits; for (int i = 0; i < int(list.size()); i++) { factoradicDigits.push_back(idx % (i+1)); idx = idx / (i+1); } // construct permutation std::vector pool = list; std::vector permutation; while (!factoradicDigits.empty()) { int i = factoradicDigits.back(); factoradicDigits.pop_back(); permutation.push_back(pool[i]); pool.erase(pool.begin() + i); } // update map for (int i = 0; i < int(list.size()); i++) map[list[i]] = permutation[i]; } static int numberOfPermutationsArray(const std::vector> &list) { int numPermutations = 1; for (const auto &it : list) { int thisPermutations = numberOfPermutations(it); assert(float(numPermutations) * float(thisPermutations) < maxPermutationsLimit); numPermutations *= thisPermutations; } return numPermutations; } static void permutateVectorToMapArray(std::map &map, const std::vector> &list, int idx) { for (const auto &it : list) { int thisPermutations = numberOfPermutations(it); int thisIdx = idx % thisPermutations; permutateVectorToMap(map, it, thisIdx); idx /= thisPermutations; } } static void applyPermutation(std::map &map, const std::map &permutation) { std::vector> changeLog; for (const auto &it : permutation) if (map.count(it.second)) changeLog.push_back(std::pair(it.first, map.at(it.second))); else changeLog.push_back(std::pair(it.first, it.second)); for (const auto &it : changeLog) map[it.first] = it.second; } // classes for internal digraph representation struct DiBit { std::string fromPort, toPort; int fromBit, toBit; DiBit() : fromPort(), toPort(), fromBit(-1), toBit(-1) { } DiBit(std::string fromPort, int fromBit, std::string toPort, int toBit) : fromPort(fromPort), toPort(toPort), fromBit(fromBit), toBit(toBit) { } bool operator < (const DiBit &other) const { if (fromPort != other.fromPort) return fromPort < other.fromPort; if (toPort != other.toPort) return toPort < other.toPort; if (fromBit != other.fromBit) return fromBit < other.fromBit; return toBit < other.toBit; } std::string toString() const { return my_stringf("%s[%d]:%s[%d]", fromPort.c_str(), fromBit, toPort.c_str(), toBit); } }; struct DiNode { std::string typeId; std::map portSizes; DiNode() { } DiNode(const Graph &graph, int nodeIdx) { const Graph::Node &node = graph.nodes.at(nodeIdx); typeId = node.typeId; for (const auto &port : node.ports) portSizes[port.portId] = port.bits.size(); } bool operator < (const DiNode &other) const { if (typeId != other.typeId) return typeId < other.typeId; return portSizes < other.portSizes; } std::string toString() const { std::string str; bool firstPort = true; for (const auto &it : portSizes) { str += my_stringf("%s%s[%d]", firstPort ? "" : ",", it.first.c_str(), it.second); firstPort = false; } return typeId + "(" + str + ")"; } }; struct DiEdge { DiNode fromNode, toNode; std::set bits; std::string userAnnotation; bool operator < (const DiEdge &other) const { if (fromNode < other.fromNode || other.fromNode < fromNode) return fromNode < other.fromNode; if (toNode < other.toNode || other.toNode < toNode) return toNode < other.toNode; if (bits < other.bits || other.bits < bits) return bits < other.bits; return userAnnotation < other.userAnnotation; } bool compare(const DiEdge &other, const std::map &mapFromPorts, const std::map &mapToPorts) const { // Rules for matching edges: // // For all bits in the needle edge: // - ignore if needle ports don't exist in haystack edge // - otherwise: matching bit in haystack edge must exist // // There is no need to check in the other direction, as checking // of the isExtern properties is already performed in node matching. // // Note: "this" is needle, "other" is haystack for (auto bit : bits) { if (mapFromPorts.count(bit.fromPort) > 0) bit.fromPort = mapFromPorts.at(bit.fromPort); if (mapToPorts.count(bit.toPort) > 0) bit.toPort = mapToPorts.at(bit.toPort); if (other.fromNode.portSizes.count(bit.fromPort) == 0) continue; if (other.toNode.portSizes.count(bit.toPort) == 0) continue; if (bit.fromBit >= other.fromNode.portSizes.at(bit.fromPort)) continue; if (bit.toBit >= other.toNode.portSizes.at(bit.toPort)) continue; if (other.bits.count(bit) == 0) return false; } return true; } bool compareWithFromAndToPermutations(const DiEdge &other, const std::map &mapFromPorts, const std::map &mapToPorts, const std::map>> &swapPermutations) const { if (swapPermutations.count(fromNode.typeId) > 0) for (const auto &permutation : swapPermutations.at(fromNode.typeId)) { std::map thisMapFromPorts = mapFromPorts; applyPermutation(thisMapFromPorts, permutation); if (compareWithToPermutations(other, thisMapFromPorts, mapToPorts, swapPermutations)) return true; } return compareWithToPermutations(other, mapFromPorts, mapToPorts, swapPermutations); } bool compareWithToPermutations(const DiEdge &other, const std::map &mapFromPorts, const std::map &mapToPorts, const std::map>> &swapPermutations) const { if (swapPermutations.count(toNode.typeId) > 0) for (const auto &permutation : swapPermutations.at(toNode.typeId)) { std::map thisMapToPorts = mapToPorts; applyPermutation(thisMapToPorts, permutation); if (compare(other, mapFromPorts, thisMapToPorts)) return true; } return compare(other, mapFromPorts, mapToPorts); } bool compare(const DiEdge &other, const std::map>> &swapPorts, const std::map>> &swapPermutations) const { // brute force method for port swapping: try all variations std::vector> swapFromPorts; std::vector> swapToPorts; // only use groups that are relevant for this edge if (swapPorts.count(fromNode.typeId) > 0) for (const auto &ports : swapPorts.at(fromNode.typeId)) { for (const auto &bit : bits) if (ports.count(bit.fromPort)) goto foundFromPortMatch; if (0) { foundFromPortMatch: std::vector portsVector; for (const auto &port : ports) portsVector.push_back(port); swapFromPorts.push_back(portsVector); } } if (swapPorts.count(toNode.typeId) > 0) for (const auto &ports : swapPorts.at(toNode.typeId)) { for (const auto &bit : bits) if (ports.count(bit.toPort)) goto foundToPortMatch; if (0) { foundToPortMatch: std::vector portsVector; for (const auto &port : ports) portsVector.push_back(port); swapToPorts.push_back(portsVector); } } // try all permutations std::map mapFromPorts, mapToPorts; int fromPortsPermutations = numberOfPermutationsArray(swapFromPorts); int toPortsPermutations = numberOfPermutationsArray(swapToPorts); for (int i = 0; i < fromPortsPermutations; i++) { permutateVectorToMapArray(mapFromPorts, swapFromPorts, i); for (int j = 0; j < toPortsPermutations; j++) { permutateVectorToMapArray(mapToPorts, swapToPorts, j); if (compareWithFromAndToPermutations(other, mapFromPorts, mapToPorts, swapPermutations)) return true; } } return false; } bool compare(const DiEdge &other, const std::map &mapFromPorts, const std::map>> &swapPorts, const std::map>> &swapPermutations) const { // strip-down version of the last function: only try permutations for mapToPorts, mapFromPorts is already provided by the caller std::vector> swapToPorts; if (swapPorts.count(toNode.typeId) > 0) for (const auto &ports : swapPorts.at(toNode.typeId)) { for (const auto &bit : bits) if (ports.count(bit.toPort)) goto foundToPortMatch; if (0) { foundToPortMatch: std::vector portsVector; for (const auto &port : ports) portsVector.push_back(port); swapToPorts.push_back(portsVector); } } std::map mapToPorts; int toPortsPermutations = numberOfPermutationsArray(swapToPorts); for (int j = 0; j < toPortsPermutations; j++) { permutateVectorToMapArray(mapToPorts, swapToPorts, j); if (compareWithToPermutations(other, mapFromPorts, mapToPorts, swapPermutations)) return true; } return false; } std::string toString() const { std::string buffer = fromNode.toString() + " " + toNode.toString(); for (const auto &bit : bits) buffer += " " + bit.toString(); if (!userAnnotation.empty()) buffer += " " + userAnnotation; return buffer; } static void findEdgesInGraph(const Graph &graph, std::map, DiEdge> &edges) { edges.clear(); for (const auto &edge : graph.edges) { if (edge.constValue != 0) continue; for (const auto &fromBit : edge.portBits) for (const auto &toBit : edge.portBits) if (&fromBit != &toBit) { DiEdge &de = edges[std::pair(fromBit.nodeIdx, toBit.nodeIdx)]; de.fromNode = DiNode(graph, fromBit.nodeIdx); de.toNode = DiNode(graph, toBit.nodeIdx); std::string fromPortId = graph.nodes[fromBit.nodeIdx].ports[fromBit.portIdx].portId; std::string toPortId = graph.nodes[toBit.nodeIdx].ports[toBit.portIdx].portId; de.bits.insert(DiBit(fromPortId, fromBit.bitIdx, toPortId, toBit.bitIdx)); } } } }; struct DiCache { std::map edgeTypesMap; std::vector edgeTypes; std::map, bool> compareCache; void add(const Grap