diff --git a/flow/platforms/asap7/verilog/stdcell/dff.v b/flow/platforms/asap7/verilog/stdcell/dff.v deleted file mode 100644 index 68e8cd3610..0000000000 --- a/flow/platforms/asap7/verilog/stdcell/dff.v +++ /dev/null @@ -1,32 +0,0 @@ -// Quick and dirty reimplementation of DFFHQNx2_ASAP7_75t_R because -// Verialtor doesn't support and has no plans to support 1995 UDP -// tables. -// -// https://github.com/verilator/verilator/issues/5243 - -module DFFHQNx1_ASAP7_75t_R (QN, D, CLK); - output reg QN; - input D, CLK; - - always @(posedge CLK) begin - QN <= ~D; - end -endmodule - -module DFFHQNx2_ASAP7_75t_R (QN, D, CLK); - output reg QN; - input D, CLK; - - always @(posedge CLK) begin - QN <= ~D; - end -endmodule - -module DFFHQNx3_ASAP7_75t_R (QN, D, CLK); - output reg QN; - input D, CLK; - - always @(posedge CLK) begin - QN <= ~D; - end -endmodule diff --git a/flow/platforms/asap7/verilog/stdcell/empty.v b/flow/platforms/asap7/verilog/stdcell/empty.v deleted file mode 100644 index db08c5d916..0000000000 --- a/flow/platforms/asap7/verilog/stdcell/empty.v +++ /dev/null @@ -1,17 +0,0 @@ -// Used to silence warnings. -module TAPCELL_ASAP7_75t_R; -endmodule -module FILLERxp5_ASAP7_75t_R; -endmodule -module FILLER_ASAP7_75t_R; -endmodule -module DECAPx1_ASAP7_75t_R; -endmodule -module DECAPx2_ASAP7_75t_R; -endmodule -module DECAPx4_ASAP7_75t_R; -endmodule -module DECAPx6_ASAP7_75t_R; -endmodule -module DECAPx10_ASAP7_75t_R; -endmodule diff --git a/flow/scripts/BUILD.bazel b/flow/scripts/BUILD.bazel new file mode 100644 index 0000000000..46cfaecb24 --- /dev/null +++ b/flow/scripts/BUILD.bazel @@ -0,0 +1,13 @@ +load("@rules_python//python:defs.bzl", "py_library", "py_test") + +py_library( + name = "lib2v", + srcs = ["lib2v.py"], + visibility = ["//visibility:public"], +) + +py_test( + name = "test_lib2v", + srcs = ["test_lib2v.py"], + deps = [":lib2v"], +) diff --git a/flow/scripts/lib2v.py b/flow/scripts/lib2v.py new file mode 100644 index 0000000000..11847c9181 --- /dev/null +++ b/flow/scripts/lib2v.py @@ -0,0 +1,709 @@ +#!/usr/bin/env python3 +"""Generate Verilator-compatible behavioral Verilog from Liberty (.lib) files. + +Verilator does not support Verilog-1995 UDP (User Defined Primitives) used in +the vendor-supplied behavioral models (e.g. altos_dff_sr_err). This script +parses .lib/.lib.gz files and emits clean behavioral Verilog that Verilator can +simulate. + +Supported cell types: + - Combinational cells (SIMPLE, AO, OA, INVBUF): assign from function expr + - Flip-flops (DFF*): always @(posedge/negedge clk) with optional async set/reset + - Scan flip-flops (SDF*): same as DFF with scan-mux in next_state + - Latches (DHL, DLL): level-sensitive always block + - Clock gating cells (ICG*): latch + AND gate + - Multi-bit DFFs (DFFHQNV2X, DFFHQNV4X, DFFHQNH2V2X): vectorized D/QN + - Physical-only cells (TAPCELL, FILLER, DECAP): empty modules from LEF + +All ASAP7 Vt variants (RVT/_R, LVT/_L, SLVT/_SL, SRAM/_SRAM) are supported. +""" + +import argparse +import gzip +import re +import sys +from dataclasses import dataclass, field +from pathlib import Path + + +@dataclass +class Pin: + name: str + direction: str = "" # input, output, internal + function: str = "" + state_function: str = "" + clock: bool = False + clock_gate_enable_pin: bool = False + + +@dataclass +class FFInfo: + var1: str = "" + var2: str = "" + clocked_on: str = "" + next_state: str = "" + clear: str = "" + preset: str = "" + + +@dataclass +class LatchInfo: + var1: str = "" + var2: str = "" + enable: str = "" + data_in: str = "" + + +@dataclass +class BundleInfo: + name: str = "" + members: list = field(default_factory=list) + direction: str = "" + function: str = "" + + +@dataclass +class Cell: + name: str + pins: dict = field(default_factory=dict) # name -> Pin + ff: FFInfo | None = None + latch: LatchInfo | None = None + bundles: list = field(default_factory=list) # list of BundleInfo + clock_gating: str = "" # clock_gating_integrated_cell value + + +def read_lib(path: Path) -> str: + """Read a .lib or .lib.gz file.""" + if path.suffix == ".gz": + with gzip.open(path, "rt") as f: + return f.read() + else: + with open(path) as f: + return f.read() + + +def parse_lib(content: str) -> list[Cell]: + """Parse liberty content and extract cells with their pins and sequential info.""" + cells = [] + lines = content.split("\n") + i = 0 + while i < len(lines): + line = lines[i].strip() + # Match cell declaration + m = re.match(r"cell\s*\((\S+)\)\s*\{", line) + if m: + cell = Cell(name=m.group(1)) + i, cell = _parse_cell(lines, i + 1, cell) + cells.append(cell) + else: + i += 1 + return cells + + +def _parse_cell(lines: list[str], start: int, cell: Cell) -> tuple[int, Cell]: + """Parse cell body, tracking brace depth.""" + i = start + depth = 1 + while i < len(lines) and depth > 0: + line = lines[i].strip() + + if line == "}": + depth -= 1 + i += 1 + continue + + # clock_gating_integrated_cell + m = re.match(r'clock_gating_integrated_cell\s*:\s*(\S+)\s*;', line) + if m: + cell.clock_gating = m.group(1) + i += 1 + continue + + # ff group (also matches ff_bank with optional bit count) + m = re.match(r'ff(?:_bank)?\s*\((\w+)\s*,\s*(\w+)(?:\s*,\s*\d+)?\)\s*\{', line) + if m: + cell.ff = FFInfo(var1=m.group(1), var2=m.group(2)) + i = _parse_ff(lines, i + 1, cell.ff) + continue + + # latch group + m = re.match(r'latch\s*\((\w+)\s*,\s*(\w+)\)\s*\{', line) + if m: + cell.latch = LatchInfo(var1=m.group(1), var2=m.group(2)) + i = _parse_latch(lines, i + 1, cell.latch) + continue + + # bundle group + m = re.match(r'bundle\s*\((\w+)\)\s*\{', line) + if m: + bundle = BundleInfo(name=m.group(1)) + i = _parse_bundle(lines, i + 1, bundle) + cell.bundles.append(bundle) + continue + + # pin group + m = re.match(r'pin\s*\((\w+)\)\s*\{', line) + if m: + pin = Pin(name=m.group(1)) + if _is_single_line_group(line): + _parse_pin_inline(line, pin) + i += 1 + else: + i = _parse_pin(lines, i + 1, pin) + cell.pins[pin.name] = pin + continue + + # pg_pin or other groups - skip + if "{" in line: + if _is_single_line_group(line): + i += 1 + else: + i = _skip_group(lines, i + 1) + continue + + i += 1 + + return i, cell + + +def _parse_ff(lines: list[str], start: int, ff: FFInfo) -> int: + i = start + depth = 1 + while i < len(lines) and depth > 0: + line = lines[i].strip() + if line == "}": + depth -= 1 + i += 1 + continue + if "{" in line: + i = _skip_group(lines, i + 1) + continue + m = re.match(r'clocked_on\s*:\s*"(.+?)"\s*;', line) + if m: + ff.clocked_on = m.group(1) + m = re.match(r'next_state\s*:\s*"(.+?)"\s*;', line) + if m: + ff.next_state = m.group(1) + m = re.match(r'clear\s*:\s*"(.+?)"\s*;', line) + if m: + ff.clear = m.group(1) + m = re.match(r'preset\s*:\s*"(.+?)"\s*;', line) + if m: + ff.preset = m.group(1) + i += 1 + return i + + +def _parse_latch(lines: list[str], start: int, latch: LatchInfo) -> int: + i = start + depth = 1 + while i < len(lines) and depth > 0: + line = lines[i].strip() + if line == "}": + depth -= 1 + i += 1 + continue + if "{" in line: + i = _skip_group(lines, i + 1) + continue + m = re.match(r'enable\s*:\s*"(.+?)"\s*;', line) + if m: + latch.enable = m.group(1) + m = re.match(r'data_in\s*:\s*"(.+?)"\s*;', line) + if m: + latch.data_in = m.group(1) + i += 1 + return i + + +def _parse_bundle(lines: list[str], start: int, bundle: BundleInfo) -> int: + i = start + depth = 1 + while i < len(lines) and depth > 0: + line = lines[i].strip() + if line == "}": + depth -= 1 + i += 1 + continue + m = re.match(r'members\s*\((.+?)\)\s*;', line) + if m: + bundle.members = [x.strip() for x in m.group(1).split(",")] + m = re.match(r'direction\s*:\s*(\w+)\s*;', line) + if m: + bundle.direction = m.group(1) + m = re.match(r'function\s*:\s*"(.+?)"\s*;', line) + if m: + bundle.function = m.group(1) + # Skip nested groups (pin sub-groups within bundle) + if "{" in line: + i = _skip_group(lines, i + 1) + continue + i += 1 + return i + + +def _parse_pin(lines: list[str], start: int, pin: Pin) -> int: + i = start + depth = 1 + while i < len(lines) and depth > 0: + line = lines[i].strip() + if line == "}": + depth -= 1 + i += 1 + continue + if "{" in line: + i = _skip_group(lines, i + 1) + continue + m = re.match(r'direction\s*:\s*(\w+)\s*;', line) + if m: + pin.direction = m.group(1) + m = re.match(r'function\s*:\s*"(.+?)"\s*;', line) + if m and "power_down" not in line: + pin.function = m.group(1) + m = re.match(r'state_function\s*:\s*"(.+?)"\s*;', line) + if m: + pin.state_function = m.group(1) + if re.match(r'clock\s*:\s*true\s*;', line): + pin.clock = True + if re.match(r'clock_gate_enable_pin\s*:\s*true\s*;', line): + pin.clock_gate_enable_pin = True + i += 1 + return i + + +def _is_single_line_group(line: str) -> bool: + """Check if a group opens and closes on the same line.""" + return line.count("{") == line.count("}") + + +def _parse_pin_inline(line: str, pin: Pin): + """Parse pin attributes from a single-line group like: pin (X) { direction : input; }""" + m = re.search(r'direction\s*:\s*(\w+)', line) + if m: + pin.direction = m.group(1) + m = re.search(r'(? int: + """Skip a brace-delimited group.""" + i = start + depth = 1 + while i < len(lines) and depth > 0: + line = lines[i].strip() + depth += line.count("{") - line.count("}") + i += 1 + return i + + +def liberty_to_verilog(expr: str) -> str: + """Convert a liberty boolean expression to Verilog. + + Liberty uses: * (AND), + (OR), ! (NOT), ^ (XOR) + Verilog uses: & (AND), | (OR), ~ (NOT), ^ (XOR) + """ + result = [] + i = 0 + while i < len(expr): + ch = expr[i] + if ch == "*": + result.append("&") + elif ch == "+": + result.append("|") + elif ch == "!": + result.append("~") + elif ch == "&": + # liberty uses & for AND in some contexts (e.g. state_function) + result.append("&") + else: + result.append(ch) + i += 1 + return "".join(result) + + +def _extract_signal_from_expr(expr: str) -> tuple[str, bool]: + """Extract signal name and polarity from a simple liberty expression. + + Returns (signal_name, is_negated). + e.g. "!SETN" -> ("SETN", True), "CLK" -> ("CLK", False) + """ + expr = expr.strip() + if expr.startswith("!"): + return expr[1:], True + return expr, False + + +def generate_verilog(cell: Cell) -> str: + """Generate behavioral Verilog for a cell.""" + if cell.bundles: + return _generate_bundle_dff(cell) + if cell.clock_gating: + return _generate_icg(cell) + if cell.ff: + return _generate_ff(cell) + if cell.latch: + return _generate_latch(cell) + # Combinational + return _generate_combinational(cell) + + +def _get_io_pins(cell: Cell) -> tuple[list[Pin], list[Pin]]: + """Get (input_pins, output_pins) excluding power/internal.""" + inputs = [] + outputs = [] + for pin in cell.pins.values(): + if pin.direction == "input": + inputs.append(pin) + elif pin.direction == "output": + outputs.append(pin) + return inputs, outputs + + +def _module_header(cell: Cell, inputs: list[str], outputs: list[str], + reg_outputs: list[str] | None = None) -> list[str]: + """Generate module header lines.""" + all_ports = outputs + inputs + lines = [ + f"module {cell.name} ({', '.join(all_ports)});", + ] + if outputs: + if reg_outputs: + reg_out = [p for p in outputs if p in reg_outputs] + wire_out = [p for p in outputs if p not in reg_outputs] + if reg_out: + lines.append(f" output reg {', '.join(reg_out)};") + if wire_out: + lines.append(f" output {', '.join(wire_out)};") + else: + lines.append(f" output {', '.join(outputs)};") + if inputs: + lines.append(f" input {', '.join(inputs)};") + return lines + + +def _generate_combinational(cell: Cell) -> str: + inputs, outputs = _get_io_pins(cell) + in_names = [p.name for p in inputs] + out_names = [p.name for p in outputs] + + if not out_names: + # Physical-only cell (should not happen from lib, but guard) + return _generate_empty_module(cell.name, in_names) + + lines = _module_header(cell, in_names, out_names) + for pin in outputs: + if pin.function: + vexpr = liberty_to_verilog(pin.function) + lines.append(f" assign {pin.name} = {vexpr};") + lines.append("endmodule") + return "\n".join(lines) + + +def _generate_ff(cell: Cell) -> str: + ff = cell.ff + inputs, outputs = _get_io_pins(cell) + in_names = [p.name for p in inputs] + out_names = [p.name for p in outputs] + + # Determine clock edge + clk_signal, clk_negated = _extract_signal_from_expr(ff.clocked_on) + edge = "negedge" if clk_negated else "posedge" + + # Build sensitivity list + sens = [f"{edge} {clk_signal}"] + + # Async clear/preset + clear_signal = clear_neg = None + preset_signal = preset_neg = None + if ff.clear: + clear_signal, clear_neg = _extract_signal_from_expr(ff.clear) + clear_edge = "negedge" if clear_neg else "posedge" + sens.append(f"{clear_edge} {clear_signal}") + if ff.preset: + preset_signal, preset_neg = _extract_signal_from_expr(ff.preset) + preset_edge = "negedge" if preset_neg else "posedge" + sens.append(f"{preset_edge} {preset_signal}") + + # State variable + state_var = ff.var1 + next_state_verilog = liberty_to_verilog(ff.next_state) + + # Output mapping: output pins reference state variables via function + lines = _module_header(cell, in_names, out_names) + lines.append(f" reg {state_var};") + + lines.append(f" always @({' or '.join(sens)}) begin") + if ff.clear: + cond = f"~{clear_signal}" if clear_neg else clear_signal + lines.append(f" if ({cond})") + lines.append(f" {state_var} <= 1'b0;") + if ff.preset: + pcond = f"~{preset_signal}" if preset_neg else preset_signal + lines.append(f" else if ({pcond})") + lines.append(f" {state_var} <= 1'b1;") + lines.append(" else") + lines.append(f" {state_var} <= {next_state_verilog};") + elif ff.preset: + pcond = f"~{preset_signal}" if preset_neg else preset_signal + lines.append(f" if ({pcond})") + lines.append(f" {state_var} <= 1'b1;") + lines.append(" else") + lines.append(f" {state_var} <= {next_state_verilog};") + else: + lines.append(f" {state_var} <= {next_state_verilog};") + lines.append(" end") + + # Output assignments + for pin in outputs: + if pin.function: + vexpr = liberty_to_verilog(pin.function) + lines.append(f" assign {pin.name} = {vexpr};") + + lines.append("endmodule") + return "\n".join(lines) + + +def _generate_latch(cell: Cell) -> str: + latch = cell.latch + inputs, outputs = _get_io_pins(cell) + in_names = [p.name for p in inputs] + out_names = [p.name for p in outputs] + + state_var = latch.var1 + enable_verilog = liberty_to_verilog(latch.enable) + data_verilog = liberty_to_verilog(latch.data_in) + + lines = _module_header(cell, in_names, out_names) + lines.append(f" reg {state_var};") + lines.append(f" always @* begin") + lines.append(f" if ({enable_verilog})") + lines.append(f" {state_var} = {data_verilog};") + lines.append(f" end") + + for pin in outputs: + if pin.function: + vexpr = liberty_to_verilog(pin.function) + lines.append(f" assign {pin.name} = {vexpr};") + + lines.append("endmodule") + return "\n".join(lines) + + +def _generate_icg(cell: Cell) -> str: + """Generate clock gating cell: latch + AND.""" + inputs, outputs = _get_io_pins(cell) + in_names = [p.name for p in inputs] + out_names = [p.name for p in outputs] + + # Find the enable and SE pins + ena_pin = None + se_pin = None + clk_pin = None + for pin in inputs: + if pin.clock: + clk_pin = pin + elif pin.clock_gate_enable_pin: + ena_pin = pin + elif pin.name == "SE": + se_pin = pin + + # Find internal pin for latch state + internal_pin = None + for pin in cell.pins.values(): + if pin.direction == "internal": + internal_pin = pin + break + + # Find output with state_function + out_pin = outputs[0] if outputs else None + + lines = _module_header(cell, in_names, out_names) + latch_var = internal_pin.name if internal_pin else "latch_out" + lines.append(f" reg {latch_var};") + + # Latch: transparent when CLK is low + latch_data_parts = [] + if ena_pin: + latch_data_parts.append(ena_pin.name) + if se_pin: + latch_data_parts.append(se_pin.name) + latch_data = " | ".join(latch_data_parts) if latch_data_parts else "1'b0" + + clk_name = clk_pin.name if clk_pin else "CLK" + lines.append(f" always @* begin") + lines.append(f" if (~{clk_name})") + lines.append(f" {latch_var} = {latch_data};") + lines.append(f" end") + + # Output: CLK & latch + if out_pin and out_pin.state_function: + vexpr = liberty_to_verilog(out_pin.state_function) + lines.append(f" assign {out_pin.name} = {vexpr};") + elif out_pin: + lines.append(f" assign {out_pin.name} = {clk_name} & {latch_var};") + + lines.append("endmodule") + return "\n".join(lines) + + +def _generate_bundle_dff(cell: Cell) -> str: + """Generate multi-bit DFF from FAKE lib bundle cells.""" + ff = cell.ff + if not ff: + # Shouldn't happen for bundle cells, but guard + return _generate_combinational(cell) + + clk_signal, clk_negated = _extract_signal_from_expr(ff.clocked_on) + edge = "negedge" if clk_negated else "posedge" + + # Separate bundles into input and output + in_bundle = None + out_bundle = None + for b in cell.bundles: + if b.direction == "input": + in_bundle = b + elif b.direction == "output": + out_bundle = b + + # Collect all port names + in_names = [clk_signal] + out_names = [] + d_members = [] + q_members = [] + + if in_bundle: + d_members = in_bundle.members + in_names.extend(d_members) + if out_bundle: + q_members = out_bundle.members + out_names.extend(q_members) + + # Also include non-bundle input pins + for pin in cell.pins.values(): + if pin.direction == "input" and pin.name not in in_names: + in_names.append(pin.name) + + lines = _module_header(cell, in_names, out_names, reg_outputs=q_members) + + # Determine the next_state transform + # e.g. "!D" means QNi <= ~Di + ns = ff.next_state.strip() + invert = ns.startswith("!") + + lines.append(f" always @({edge} {clk_signal}) begin") + for d, q in zip(d_members, q_members): + if invert: + lines.append(f" {q} <= ~{d};") + else: + lines.append(f" {q} <= {d};") + lines.append(" end") + lines.append("endmodule") + return "\n".join(lines) + + +def generate_empty_module(name: str) -> str: + """Generate an empty module for a physical-only cell.""" + return f"module {name};\nendmodule" + + +def _generate_empty_module(name: str, inputs: list[str]) -> str: + if inputs: + lines = [ + f"module {name} ({', '.join(inputs)});", + f" input {', '.join(inputs)};", + "endmodule", + ] + return "\n".join(lines) + return f"module {name};\nendmodule" + + +def parse_lef_physical_only(path: Path) -> list[str]: + """Extract MACRO names from a LEF file that have no signal pins. + + Physical-only cells (TAPCELL, FILLER, DECAP) have only POWER/GROUND + pins and no SIGNAL pins, so they need empty Verilog module stubs. + """ + names = [] + with open(path) as f: + content = f.read() + for m in re.finditer( + r"^MACRO\s+(\S+)\s*\n(.*?)^END\s+\1", + content, re.MULTILINE | re.DOTALL + ): + name = m.group(1) + body = m.group(2) + has_signal_pin = bool(re.search(r"USE\s+SIGNAL\s*;", body)) + if not has_signal_pin: + names.append(name) + return names + + +def find_physical_only_cells(lef_dir: Path, lib_cells: set[str]) -> list[str]: + """Find physical-only cells in LEF (no signal pins, not in any lib).""" + physical = [] + for lef_path in sorted(lef_dir.glob("asap7sc7p5t_*.lef")): + for name in parse_lef_physical_only(lef_path): + if name not in lib_cells: + physical.append(name) + return sorted(physical) + + +def main(): + parser = argparse.ArgumentParser( + description="Generate behavioral Verilog from Liberty (.lib) files" + ) + parser.add_argument( + "lib_files", nargs="+", type=Path, + help="Input .lib or .lib.gz files" + ) + parser.add_argument( + "-o", "--output", type=Path, default=None, + help="Output .v file (default: stdout)" + ) + parser.add_argument( + "--lef-dir", type=Path, default=None, + help="LEF directory to scan for physical-only cells (TAPCELL, FILLER, DECAP)" + ) + args = parser.parse_args() + + all_cells = [] + seen_names = set() + + for lib_path in args.lib_files: + content = read_lib(lib_path) + cells = parse_lib(content) + for cell in cells: + if cell.name not in seen_names: + all_cells.append(cell) + seen_names.add(cell.name) + + # Generate verilog + modules = [] + for cell in all_cells: + modules.append(generate_verilog(cell)) + + # Physical-only cells from LEF + if args.lef_dir: + physical_cells = find_physical_only_cells(args.lef_dir, seen_names) + for name in physical_cells: + modules.append(generate_empty_module(name)) + + output = "\n\n".join(modules) + "\n" + + if args.output: + args.output.write_text(output) + print(f"Wrote {len(all_cells)} cells to {args.output}", file=sys.stderr) + else: + print(output) + + +if __name__ == "__main__": + main() diff --git a/flow/scripts/test_lib2v.py b/flow/scripts/test_lib2v.py new file mode 100644 index 0000000000..04e3980adc --- /dev/null +++ b/flow/scripts/test_lib2v.py @@ -0,0 +1,649 @@ +"""Tests for lib2v.py - Liberty to behavioral Verilog generator.""" + +import os +import textwrap +import unittest +from pathlib import Path + +try: + from lib2v import ( + Cell, + FFInfo, + LatchInfo, + BundleInfo, + Pin, + generate_verilog, + generate_empty_module, + liberty_to_verilog, + parse_lib, + parse_lef_physical_only, + ) +except ModuleNotFoundError: + from flow.scripts.lib2v import ( + Cell, + FFInfo, + LatchInfo, + BundleInfo, + Pin, + generate_verilog, + generate_empty_module, + liberty_to_verilog, + parse_lib, + parse_lef_physical_only, + ) + + +class TestLibertyToVerilog(unittest.TestCase): + """Test liberty expression to verilog conversion.""" + + def test_and(self): + self.assertEqual(liberty_to_verilog("(A * B)"), "(A & B)") + + def test_or(self): + self.assertEqual(liberty_to_verilog("(A) + (B)"), "(A) | (B)") + + def test_not(self): + self.assertEqual(liberty_to_verilog("!A"), "~A") + + def test_complex_ao(self): + self.assertEqual( + liberty_to_verilog("(A1 * A2) + (B)"), + "(A1 & A2) | (B)", + ) + + def test_complex_nand(self): + self.assertEqual( + liberty_to_verilog("(!A * !B)"), + "(~A & ~B)", + ) + + def test_xor(self): + self.assertEqual( + liberty_to_verilog("(A * !B) + (!A * B)"), + "(A & ~B) | (~A & B)", + ) + + def test_ampersand_passthrough(self): + """Liberty state_function uses & directly.""" + self.assertEqual(liberty_to_verilog("CLK & IQ"), "CLK & IQ") + + def test_constant_zero(self): + self.assertEqual(liberty_to_verilog("0"), "0") + + def test_constant_one(self): + self.assertEqual(liberty_to_verilog("1"), "1") + + +class TestParseLib(unittest.TestCase): + """Test liberty file parsing.""" + + def test_combinational_cell(self): + lib = textwrap.dedent("""\ + library (test) { + cell (AND2x1_TEST) { + pin (Y) { + direction : output; + function : "(A * B)"; + } + pin (A) { + direction : input; + } + pin (B) { + direction : input; + } + } + } + """) + cells = parse_lib(lib) + self.assertEqual(len(cells), 1) + c = cells[0] + self.assertEqual(c.name, "AND2x1_TEST") + self.assertIn("Y", c.pins) + self.assertEqual(c.pins["Y"].direction, "output") + self.assertEqual(c.pins["Y"].function, "(A * B)") + self.assertIn("A", c.pins) + self.assertIn("B", c.pins) + self.assertIsNone(c.ff) + self.assertIsNone(c.latch) + + def test_ff_cell(self): + lib = textwrap.dedent("""\ + library (test) { + cell (DFFHQNx1_TEST) { + ff (IQN,IQNN) { + clocked_on : "CLK"; + next_state : "!D"; + } + pin (QN) { + direction : output; + function : "IQN"; + } + pin (CLK) { + direction : input; + } + pin (D) { + direction : input; + } + } + } + """) + cells = parse_lib(lib) + self.assertEqual(len(cells), 1) + c = cells[0] + self.assertEqual(c.name, "DFFHQNx1_TEST") + self.assertIsNotNone(c.ff) + self.assertEqual(c.ff.var1, "IQN") + self.assertEqual(c.ff.var2, "IQNN") + self.assertEqual(c.ff.clocked_on, "CLK") + self.assertEqual(c.ff.next_state, "!D") + self.assertEqual(c.ff.clear, "") + self.assertEqual(c.ff.preset, "") + + def test_ff_with_async(self): + lib = textwrap.dedent("""\ + library (test) { + cell (DFFASRx1_TEST) { + ff (IQN,IQNN) { + clocked_on : "CLK"; + next_state : "!D"; + clear : "!SETN"; + preset : "!RESETN"; + } + pin (QN) { + direction : output; + function : "IQN"; + } + pin (CLK) { + direction : input; + } + pin (D) { + direction : input; + } + pin (RESETN) { + direction : input; + } + pin (SETN) { + direction : input; + } + } + } + """) + cells = parse_lib(lib) + c = cells[0] + self.assertEqual(c.ff.clear, "!SETN") + self.assertEqual(c.ff.preset, "!RESETN") + + def test_falling_edge_ff(self): + lib = textwrap.dedent("""\ + library (test) { + cell (DFFLQNx1_TEST) { + ff (IQN,IQNN) { + clocked_on : "!CLK"; + next_state : "!D"; + } + pin (QN) { + direction : output; + function : "IQN"; + } + pin (CLK) { + direction : input; + } + pin (D) { + direction : input; + } + } + } + """) + cells = parse_lib(lib) + c = cells[0] + self.assertEqual(c.ff.clocked_on, "!CLK") + + def test_latch_cell(self): + lib = textwrap.dedent("""\ + library (test) { + cell (DHLx1_TEST) { + latch (IQ,IQN) { + enable : "CLK"; + data_in : "D"; + } + pin (Q) { + direction : output; + function : "IQ"; + } + pin (CLK) { + direction : input; + } + pin (D) { + direction : input; + } + } + } + """) + cells = parse_lib(lib) + c = cells[0] + self.assertIsNotNone(c.latch) + self.assertEqual(c.latch.var1, "IQ") + self.assertEqual(c.latch.enable, "CLK") + self.assertEqual(c.latch.data_in, "D") + + def test_ff_bank(self): + lib = textwrap.dedent("""\ + library (test) { + cell (DFFV2Xx1_TEST) { + pin (CLK) { + clock : true; + direction : input; + } + ff_bank (IQN, IQNN, 2) { + clocked_on : "CLK"; + next_state : "!D"; + } + bundle (D) { + members (D0, D1); + direction : input; + pin (D0) { + } + pin (D1) { + } + } + bundle (QN) { + members (QN0, QN1); + direction : output; + function : "IQN"; + pin (QN0) { + } + pin (QN1) { + } + } + } + } + """) + cells = parse_lib(lib) + c = cells[0] + self.assertIsNotNone(c.ff) + self.assertEqual(c.ff.var1, "IQN") + self.assertEqual(c.ff.clocked_on, "CLK") + self.assertEqual(c.ff.next_state, "!D") + self.assertEqual(len(c.bundles), 2) + + def test_icg_cell(self): + lib = textwrap.dedent("""\ + library (test) { + cell (ICGx1_TEST) { + clock_gating_integrated_cell : latch_posedge_precontrol; + pin (IQ) { + direction : internal; + } + pin (GCLK) { + direction : output; + state_function : "CLK & IQ"; + } + pin (CLK) { + clock : true; + direction : input; + } + pin (ENA) { + clock_gate_enable_pin : true; + direction : input; + } + pin (SE) { + direction : input; + } + } + } + """) + cells = parse_lib(lib) + c = cells[0] + self.assertEqual(c.clock_gating, "latch_posedge_precontrol") + self.assertIn("IQ", c.pins) + self.assertEqual(c.pins["IQ"].direction, "internal") + self.assertTrue(c.pins["CLK"].clock) + self.assertTrue(c.pins["ENA"].clock_gate_enable_pin) + + def test_multiple_cells(self): + lib = textwrap.dedent("""\ + library (test) { + cell (A) { + pin (Y) { direction : output; function : "X"; } + pin (X) { direction : input; } + } + cell (B) { + pin (Y) { direction : output; function : "X"; } + pin (X) { direction : input; } + } + } + """) + cells = parse_lib(lib) + self.assertEqual(len(cells), 2) + self.assertEqual(cells[0].name, "A") + self.assertEqual(cells[1].name, "B") + + def test_power_down_function_ignored(self): + """power_down_function should not be captured as pin function.""" + lib = textwrap.dedent("""\ + library (test) { + cell (BUFx1_TEST) { + pin (Y) { + direction : output; + function : "A"; + power_down_function : "(!VDD) + (VSS)"; + } + pin (A) { + direction : input; + } + } + } + """) + cells = parse_lib(lib) + self.assertEqual(cells[0].pins["Y"].function, "A") + + +class TestGenerateVerilog(unittest.TestCase): + """Test verilog generation for different cell types.""" + + def test_combinational(self): + cell = Cell(name="AND2x1_TEST") + cell.pins["Y"] = Pin(name="Y", direction="output", function="(A * B)") + cell.pins["A"] = Pin(name="A", direction="input") + cell.pins["B"] = Pin(name="B", direction="input") + v = generate_verilog(cell) + self.assertIn("module AND2x1_TEST", v) + self.assertIn("assign Y = (A & B);", v) + self.assertIn("output Y;", v) + self.assertIn("input A, B;", v) + self.assertIn("endmodule", v) + + def test_dff_posedge(self): + cell = Cell(name="DFFHQNx1_TEST") + cell.ff = FFInfo(var1="IQN", var2="IQNN", clocked_on="CLK", next_state="!D") + cell.pins["QN"] = Pin(name="QN", direction="output", function="IQN") + cell.pins["CLK"] = Pin(name="CLK", direction="input") + cell.pins["D"] = Pin(name="D", direction="input") + v = generate_verilog(cell) + self.assertIn("always @(posedge CLK)", v) + self.assertIn("IQN <= ~D;", v) + self.assertIn("assign QN = IQN;", v) + + def test_dff_negedge(self): + cell = Cell(name="DFFLQNx1_TEST") + cell.ff = FFInfo(var1="IQN", var2="IQNN", clocked_on="!CLK", next_state="!D") + cell.pins["QN"] = Pin(name="QN", direction="output", function="IQN") + cell.pins["CLK"] = Pin(name="CLK", direction="input") + cell.pins["D"] = Pin(name="D", direction="input") + v = generate_verilog(cell) + self.assertIn("always @(negedge CLK)", v) + + def test_dff_non_inverting(self): + cell = Cell(name="DFFHQx4_TEST") + cell.ff = FFInfo(var1="IQ", var2="IQN", clocked_on="CLK", next_state="D") + cell.pins["Q"] = Pin(name="Q", direction="output", function="IQ") + cell.pins["CLK"] = Pin(name="CLK", direction="input") + cell.pins["D"] = Pin(name="D", direction="input") + v = generate_verilog(cell) + self.assertIn("IQ <= D;", v) + self.assertIn("assign Q = IQ;", v) + + def test_dff_async_clear_preset(self): + cell = Cell(name="DFFASRx1_TEST") + cell.ff = FFInfo( + var1="IQN", var2="IQNN", + clocked_on="CLK", next_state="!D", + clear="!SETN", preset="!RESETN", + ) + cell.pins["QN"] = Pin(name="QN", direction="output", function="IQN") + cell.pins["CLK"] = Pin(name="CLK", direction="input") + cell.pins["D"] = Pin(name="D", direction="input") + cell.pins["RESETN"] = Pin(name="RESETN", direction="input") + cell.pins["SETN"] = Pin(name="SETN", direction="input") + v = generate_verilog(cell) + self.assertIn("negedge SETN", v) + self.assertIn("negedge RESETN", v) + self.assertIn("if (~SETN)", v) + self.assertIn("IQN <= 1'b0;", v) + self.assertIn("else if (~RESETN)", v) + self.assertIn("IQN <= 1'b1;", v) + + def test_latch(self): + cell = Cell(name="DHLx1_TEST") + cell.latch = LatchInfo(var1="IQ", var2="IQN", enable="CLK", data_in="D") + cell.pins["Q"] = Pin(name="Q", direction="output", function="IQ") + cell.pins["CLK"] = Pin(name="CLK", direction="input") + cell.pins["D"] = Pin(name="D", direction="input") + v = generate_verilog(cell) + self.assertIn("always @*", v) + self.assertIn("if (CLK)", v) + self.assertIn("IQ = D;", v) + self.assertIn("assign Q = IQ;", v) + + def test_latch_neg_enable(self): + cell = Cell(name="DLLx1_TEST") + cell.latch = LatchInfo(var1="IQ", var2="IQN", enable="!CLK", data_in="D") + cell.pins["Q"] = Pin(name="Q", direction="output", function="IQ") + cell.pins["CLK"] = Pin(name="CLK", direction="input") + cell.pins["D"] = Pin(name="D", direction="input") + v = generate_verilog(cell) + self.assertIn("if (~CLK)", v) + + def test_icg(self): + cell = Cell(name="ICGx1_TEST") + cell.clock_gating = "latch_posedge_precontrol" + cell.pins["GCLK"] = Pin(name="GCLK", direction="output", state_function="CLK & IQ") + cell.pins["CLK"] = Pin(name="CLK", direction="input", clock=True) + cell.pins["ENA"] = Pin(name="ENA", direction="input", clock_gate_enable_pin=True) + cell.pins["SE"] = Pin(name="SE", direction="input") + cell.pins["IQ"] = Pin(name="IQ", direction="internal") + v = generate_verilog(cell) + self.assertIn("reg IQ;", v) + self.assertIn("if (~CLK)", v) + self.assertIn("IQ = ENA | SE;", v) + self.assertIn("assign GCLK = CLK & IQ;", v) + + def test_bundle_dff(self): + cell = Cell(name="DFFV2Xx1_TEST") + cell.ff = FFInfo(var1="IQN", var2="IQNN", clocked_on="CLK", next_state="!D") + cell.pins["CLK"] = Pin(name="CLK", direction="input") + cell.bundles = [ + BundleInfo(name="D", members=["D0", "D1"], direction="input"), + BundleInfo(name="QN", members=["QN0", "QN1"], direction="output", function="IQN"), + ] + v = generate_verilog(cell) + self.assertIn("output reg QN0, QN1;", v) + self.assertIn("input CLK, D0, D1;", v) + self.assertIn("QN0 <= ~D0;", v) + self.assertIn("QN1 <= ~D1;", v) + + def test_bundle_dff_4bit(self): + cell = Cell(name="DFFV4Xx1_TEST") + cell.ff = FFInfo(var1="IQN", var2="IQNN", clocked_on="CLK", next_state="!D") + cell.pins["CLK"] = Pin(name="CLK", direction="input") + cell.bundles = [ + BundleInfo(name="D", members=["D0", "D1", "D2", "D3"], direction="input"), + BundleInfo(name="QN", members=["QN0", "QN1", "QN2", "QN3"], direction="output", function="IQN"), + ] + v = generate_verilog(cell) + self.assertIn("QN0 <= ~D0;", v) + self.assertIn("QN3 <= ~D3;", v) + + def test_scan_dff(self): + cell = Cell(name="SDFHx1_TEST") + cell.ff = FFInfo( + var1="IQN", var2="IQNN", + clocked_on="CLK", + next_state="(!D * !SE) + (!D * !SI) + (SE * !SI)", + ) + cell.pins["QN"] = Pin(name="QN", direction="output", function="IQN") + cell.pins["CLK"] = Pin(name="CLK", direction="input") + cell.pins["D"] = Pin(name="D", direction="input") + cell.pins["SE"] = Pin(name="SE", direction="input") + cell.pins["SI"] = Pin(name="SI", direction="input") + v = generate_verilog(cell) + self.assertIn("(~D & ~SE) | (~D & ~SI) | (SE & ~SI)", v) + + def test_empty_module(self): + v = generate_empty_module("TAPCELL_TEST") + self.assertEqual(v, "module TAPCELL_TEST;\nendmodule") + + +class TestParseLef(unittest.TestCase): + """Test LEF parsing for physical-only cells.""" + + def test_physical_only_detection(self, tmp_path=None): + """Physical-only cells have no SIGNAL pins.""" + import tempfile + with tempfile.NamedTemporaryFile(mode="w", suffix=".lef", delete=False) as f: + f.write(textwrap.dedent("""\ + MACRO TAPCELL_TEST + CLASS CORE WELLTAP ; + PIN VDD + DIRECTION INOUT ; + USE POWER ; + END VDD + PIN VSS + DIRECTION INOUT ; + USE GROUND ; + END VSS + END TAPCELL_TEST + + MACRO AND2_TEST + CLASS CORE ; + PIN A + DIRECTION INPUT ; + USE SIGNAL ; + END A + PIN Y + DIRECTION OUTPUT ; + USE SIGNAL ; + END Y + END AND2_TEST + """)) + f.flush() + names = parse_lef_physical_only(Path(f.name)) + os.unlink(f.name) + self.assertEqual(names, ["TAPCELL_TEST"]) + + +def _find_platform_dir(): + """Find the ASAP7 platform directory, works in Bazel runfiles and locally.""" + # Try relative to this file (local execution) + local = Path(__file__).parent / "../platforms/asap7" + if local.exists(): + return local + # Try Bazel runfiles + runfiles = Path(os.environ.get("TEST_SRCDIR", "")) / os.environ.get("TEST_WORKSPACE", "") + bazel = runfiles / "flow/platforms/asap7" + if bazel.exists(): + return bazel + return None + + +class TestEndToEnd(unittest.TestCase): + """End-to-end tests on actual ASAP7 lib files if available.""" + + @classmethod + def setUpClass(cls): + platform = _find_platform_dir() + if platform: + cls.LIB_DIR = platform / "lib/NLDM" + cls.LEF_DIR = platform / "lef" + else: + cls.LIB_DIR = None + cls.LEF_DIR = None + + def _lib(self, name): + if not self.LIB_DIR: + self.skipTest("ASAP7 platform not found") + p = self.LIB_DIR / name + if not p.exists(): + self.skipTest(f"{name} not found") + return p + + def test_seq_rvt_dff_count(self): + """SEQ RVT should produce DFF, latch, ICG, and scan modules.""" + try: + from lib2v import read_lib + except ModuleNotFoundError: + from flow.scripts.lib2v import read_lib + content = read_lib(self._lib("asap7sc7p5t_SEQ_RVT_TT_nldm_220123.lib")) + cells = parse_lib(content) + names = [c.name for c in cells] + self.assertIn("DFFHQNx1_ASAP7_75t_R", names) + self.assertIn("DFFASRHQNx1_ASAP7_75t_R", names) + self.assertIn("DHLx1_ASAP7_75t_R", names) + self.assertIn("ICGx1_ASAP7_75t_R", names) + self.assertIn("SDFHx1_ASAP7_75t_R", names) + + def test_seq_lvt_cell_suffix(self): + """LVT cells should have _L suffix.""" + try: + from lib2v import read_lib + except ModuleNotFoundError: + from flow.scripts.lib2v import read_lib + content = read_lib(self._lib("asap7sc7p5t_SEQ_LVT_TT_nldm_220123.lib")) + cells = parse_lib(content) + for c in cells: + self.assertTrue(c.name.endswith("_L"), f"{c.name} doesn't end with _L") + + def test_seq_slvt_cell_suffix(self): + """SLVT cells should have _SL suffix.""" + try: + from lib2v import read_lib + except ModuleNotFoundError: + from flow.scripts.lib2v import read_lib + content = read_lib(self._lib("asap7sc7p5t_SEQ_SLVT_TT_nldm_220123.lib")) + cells = parse_lib(content) + for c in cells: + self.assertTrue(c.name.endswith("_SL"), f"{c.name} doesn't end with _SL") + + def test_simple_rvt_combinational(self): + """SIMPLE RVT should produce combinational cells.""" + try: + from lib2v import read_lib + except ModuleNotFoundError: + from flow.scripts.lib2v import read_lib + content = read_lib(self._lib("asap7sc7p5t_SIMPLE_RVT_TT_nldm_211120.lib.gz")) + cells = parse_lib(content) + names = [c.name for c in cells] + self.assertIn("AND2x2_ASAP7_75t_R", names) + # All should be combinational (no ff/latch) + for c in cells: + self.assertIsNone(c.ff, f"{c.name} has unexpected ff group") + self.assertIsNone(c.latch, f"{c.name} has unexpected latch group") + + def test_fake_v2x_bundle(self): + """FAKE V2X should parse ff_bank and bundles.""" + try: + from lib2v import read_lib + except ModuleNotFoundError: + from flow.scripts.lib2v import read_lib + content = read_lib(self._lib("asap7sc7p5t_DFFHQNV2X_RVT_TT_nldm_FAKE.lib")) + cells = parse_lib(content) + self.assertTrue(len(cells) > 0) + c = cells[0] + self.assertIsNotNone(c.ff) + self.assertEqual(len(c.bundles), 2) + v = generate_verilog(c) + self.assertIn("QN0 <= ~D0;", v) + + def test_physical_only_from_lef(self): + """LEF scan should find TAPCELL/FILLER/DECAP cells.""" + if not self.LEF_DIR or not self.LEF_DIR.exists(): + self.skipTest("LEF dir not found") + try: + from lib2v import find_physical_only_cells + except ModuleNotFoundError: + from flow.scripts.lib2v import find_physical_only_cells + physical = find_physical_only_cells(self.LEF_DIR, set()) + phy_names = [n for n in physical if "TAPCELL" in n or "FILLER" in n or "DECAP" in n] + self.assertTrue(len(phy_names) > 0, "No physical-only cells found") + # Should include all Vt variants + suffixes = set() + for n in phy_names: + for suffix in ["_R", "_L", "_SL", "_SRAM"]: + if n.endswith(suffix): + suffixes.add(suffix) + self.assertIn("_R", suffixes) + self.assertIn("_L", suffixes) + + +if __name__ == "__main__": + unittest.main()