diff --git a/MODULE.bazel b/MODULE.bazel index a36173378f..bd817bce80 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -101,7 +101,7 @@ bazel_dep(name = "bazel-orfs", version = "0.0.1") bazel_dep(name = "bazel-orfs-verilog", dev_dependency = True) -BAZEL_ORFS_COMMIT = "3342596c1f7017b9fda5b4a55a25a54ff2aaedf8" +BAZEL_ORFS_COMMIT = "6ebadeb4be5c9ada103081c9a5e668c014126616" BAZEL_ORFS_REMOTE = "https://github.com/The-OpenROAD-Project/bazel-orfs.git" @@ -131,6 +131,17 @@ git_override( remote = "https://github.com/povik/yosys-slang.git", ) +bazel_dep(name = "fakeram", dev_dependency = True) +git_override( + module_name = "fakeram", + commit = "6f62c655952b683cda679d80850cb557cc3c262e", + patch_strip = 1, + patches = [ + "//patches/fakeram:0001-Add-ORFS-ASAP7-backend.patch", + ], + remote = "https://github.com/The-OpenROAD-Project/FakeRAM2.0.git", +) + # --- Extensions --- register_toolchains( diff --git a/docs/toc.yml b/docs/toc.yml index 722c933ca5..be479807e0 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -19,6 +19,8 @@ entries: title: Build Using WSL - file: user/FlowVariables.md title: Flow Variables + - file: user/AutoMemories.md + title: Generated Memory Macros (AUTO_MEMORIES) - file: contrib/Metrics.md title: Metrics - file: user/InstructionsForAutoTuner.md diff --git a/docs/user/AutoMemories.md b/docs/user/AutoMemories.md new file mode 100644 index 0000000000..eddde0e660 --- /dev/null +++ b/docs/user/AutoMemories.md @@ -0,0 +1,164 @@ +# AUTO_MEMORIES: generated memory macros + +**Experimental.** AUTO_MEMORIES detects memories in a design's RTL +before synthesis and generates abstract `.lib`/`.lef` macro views for +them, so an existing design gets macro-based synthesis and physical +design results — including RTL-MP macro placement — without a memory +compiler or hand-maintained fakeram files. + +The intended audience is flows built on top of ORFS (for example +bazel-orfs based in-house flows) that need early, reasonable physical +results on designs whose memories exist only as behavioral RTL. Support +posture: if it works for you, great; if it needs fixing, the report is +itself a welcome signal that someone is using it. + +## What it does + +With `AUTO_MEMORIES=1`, a pre-synthesis step runs +`scripts/memories/gen_memories.py` over `VERILOG_FILES` and writes: + +| File | Content | +| --- | --- | +| `$(RESULTS_DIR)/memories.json` | Inventory of every detected memory: geometry, full pin list with pin functions, behavioral model, and whether it was converted (`idiomatic`) with a reason. | +| `$(RESULTS_DIR)/memories/.lib` | Generated Liberty view per converted memory. | +| `$(RESULTS_DIR)/memories/_pre_layout.lib` | Ideal-clock (zero clock-tree insertion) variant for pre-CTS consumers that select lib files themselves. The Makefile flow uses `.lib` throughout. | +| `$(RESULTS_DIR)/memories/.lef` | Abstract LEF per converted memory. | +| `$(RESULTS_DIR)/memories/blackboxes.txt` | Names of the converted modules — what synthesis blackboxes. | + +Synthesis (canonicalization) blackboxes the converted modules so the +liberty view wins over their behavioral bodies; floorplan through final +read the generated `.lib`/`.lef` alongside `ADDITIONAL_LIBS`/ +`ADDITIONAL_LEFS`. Everything downstream keys off the files above — +nothing else passes between the generator and the flow. That file-based +handoff is what lets build systems (e.g. bazel-orfs) declare the +generated artifacts as ordinary stage outputs and transitive +dependencies of the remaining stages. + +Memories that are *not* converted stay in the netlist and synthesize to +flip-flops, like any other RTL. + +## How memories are detected + +Detection is a fast Python scan (`scripts/memories/detect.py`) for +modules whose entire port list follows the firtool (CIRCT) memory port +convention: every port named `_`, e.g. `R0_addr`, +`W0_en`, `RW0_wdata`, including the subword-split forms `RW0_wdata_3` / +`W0_mask_2`. This is what Chisel/firtool emits for module-separated +memories, and what the rocket-chip generation of Chisel emitted (the +in-tree tinyRocket design). + +Two consequences, documented as deliberate scope: + +- **Module boundary only.** A memory embedded inside a larger module + (a bare `reg [7:0] mem [0:255]` next to other logic) is not detected. + Yosys's memory-inference pass sees those; FPGA tools extract them + into block RAMs. Wiring yosys up as the detector — or growing such a + pass in OpenROAD SYN, which currently has no memory inference and + therefore cannot be leaned on here either — is future work; this + feature punts on it with the simple scanner. +- **No banking.** Each detected memory maps to exactly one macro. A + memory too wide, too deep, or too ported for a single sensible macro + is not decomposed across several macros — a future extension. + +## The idiomatic gate + +Not every detected memory should be a macro. `scripts/memories/ +idiomatic.py` applies simple floors (minimum depth 16, minimum capacity +256 bits, at most 4 ports); memories below them are cheaper as +flip-flops than as a macro paying the fixed control/decode/sense-amp +floor. Rejected memories are kept in `memories.json` with +`"idiomatic": false` and a reason. + +To overrule the gate, list a `.memories` file in `ADDITIONAL_MEMORIES`: + +```json +{ + "version": 1, + "memories": [ + { + "name": "tag_array", + "idiomatic": true, + "reason": "forced: the RTL provides no behavioral fallback" + } + ] +} +``` + +Entries merge by name onto the detected set: fields the override +carries win, everything else (geometry, pins) is kept from detection. A +`.memories` entry naming a module the scanner never found is taken +whole — it must then describe its pins itself. The +`designs/asap7/tinyRocket` design demonstrates the forced-conversion +case: its `tag_array` wrapper is 4 entries deep (rejected by the gate) +but instantiates a module the sources never define, so flops are not an +option and the design forces conversion. + +## Generated views + +The `.lib` mirrors the structural shape OpenROAD's abstract writer +produces for hardened blocks: `bus()` groups **with per-bit `pin()` +records** (a bus without per-bit siblings makes yosys silently drop bit +connections at parent instances), per-port clock pins with +`min/max_clock_tree_path` arcs, setup/hold constraints on inputs, +clock-to-out arcs on outputs, and `internal_power()` records under a +`power_lut_template` so SAIF-driven power reporting is non-zero. + +The `.lef` is an abstract following the conventions of the platform's +fakeram abstracts: `CLASS BLOCK`, per-bit signal pin pads stacked along +the macro edge, interleaved horizontal power/ground straps the +platform's PDN macro grid connects to, and a full-footprint multi-layer +`OBS`. + +Timing and area come from simple parametric models +(`scripts/memories/liberty.py`, `scripts/memories/sram_area_model.py`): +log2(rows) decode depth and √bits bit-line scaling for timing; an area +model anchored to published 7 nm SP-SRAM figures (Suzuki et al., ISSCC +2018). These are budgetary models — good enough to make floorplanning, +placement, and timing behave representatively; not sign-off numbers. + +## Platform support + +**asap7 only.** The emitters are split into general structure +(`liberty.py`, `lef.py`, parameterized by a `PdkParams`) and platform +constants (`pdk_asap7.py`: pins and power straps on M4 — where the +platform's PDN macro grid connects — pin pad/pitch, strap geometry, +OBS layers, nominal voltage). Generalizing to other PDKs means +providing their `PdkParams` — the code seam exists, the calibration +work does not. `AUTO_MEMORIES=1` on any other platform fails with a +clear error. + +## Trying it + +```shell +# Unit tests (fast, no EDA tools): +bazelisk test //flow:memories_tests + +# The demo design: +make DESIGN_CONFIG=designs/asap7/tinyRocket/config.mk synth floorplan +``` + +The generator can also be run standalone to inspect what it would do: + +```shell +python3 flow/scripts/memories/gen_memories.py \ + --platform asap7 --out-dir /tmp/mems --json /tmp/memories.json \ + --verilog flow/designs/src/tinyRocket/freechips.rocketchip.system.TinyConfig.v +``` + +## Consuming from bazel-orfs + +Everything downstream keys off generated files, so a build system can +declare them as ordinary stage outputs and transitive dependencies. In +bazel-orfs each stage runs in a sandbox where only declared outputs +survive, so it additionally needs to declare `memories.json` plus the +`memories/` directory (a directory artifact — the per-memory file +names are only known at run time) as canonicalize outputs and stage +them into every downstream stage's sandbox. The bazel-orfs change that +does this is carried alongside this feature as +`flow/scripts/memories/bazel-orfs-auto-memories.patch`, to be +upstreamed to bazel-orfs once the feature lands here. + +## Variables + +- [AUTO_MEMORIES](FlowVariables.md#AUTO_MEMORIES) +- [ADDITIONAL_MEMORIES](FlowVariables.md#ADDITIONAL_MEMORIES) diff --git a/docs/user/FlowVariables.md b/docs/user/FlowVariables.md index 221406f855..d3ed2fae97 100644 --- a/docs/user/FlowVariables.md +++ b/docs/user/FlowVariables.md @@ -100,8 +100,10 @@ configuration file. | ADDITIONAL_GDS| Hardened macro GDS files listed here.| | | ADDITIONAL_LEFS| Hardened macro LEF view files listed here. The LEF information of the macros is immutable and used throughout all stages. Stored in the .odb file.| | | ADDITIONAL_LIBS| Hardened macro library files listed here. The library information is immutable and used throughout all stages. Not stored in the .odb file.| | +| ADDITIONAL_MEMORIES| Experimental. Space-separated list of user-supplied `.memories` files (the memories.json JSON schema) merged onto the set AUTO_MEMORIES detects — to force-convert a memory the idiomatic gate rejects, or to describe one the scanner cannot find. See docs/user/AutoMemories.md.| | | ADDITIONAL_SITES| Passed as -additional_sites to initialize_floorplan.| | | ASAP7_USE_VT| A space separated list of VT options to use with the ASAP7 standard cell library: RVT, LVT, SLVT.| RVT| +| AUTO_MEMORIES| Experimental. When set to 1, memory-shaped modules in the RTL (firtool/CIRCT `R*/W*/RW*_` port convention, module boundary only) are detected pre-synthesis, inventoried in `$(RESULTS_DIR)/memories.json`, and — when idiomatic as an SRAM macro — given generated .lib/.lef views under `$(RESULTS_DIR)/memories/`. Synthesis blackboxes those modules and all later stages read the generated views, so an existing design gets macro-based results without a memory compiler. Supported for the asap7 platform only. See docs/user/AutoMemories.md.| 0| | BALANCE_ROWS| Balance rows during placement.| 0| | BLOCKS| Blocks used as hard macros in a hierarchical flow. Do note that you have to specify block-specific inputs file in the directory mentioned by Makefile.| | | BUFFER_PORTS_ARGS| Specify arguments to the buffer_ports call during placement. Only used if DONT_BUFFER_PORTS=0.| | @@ -340,6 +342,7 @@ configuration file. - [ABC_DRIVER_CELL](#ABC_DRIVER_CELL) - [ABC_LOAD_IN_FF](#ABC_LOAD_IN_FF) - [ADDER_MAP_FILE](#ADDER_MAP_FILE) +- [ADDITIONAL_MEMORIES](#ADDITIONAL_MEMORIES) - [CACHED_REPORTS](#CACHED_REPORTS) - [CLKGATE_MAP_FILE](#CLKGATE_MAP_FILE) - [DFF_LIB_FILE](#DFF_LIB_FILE) @@ -627,6 +630,7 @@ configuration file. - [ADDITIONAL_FILES](#ADDITIONAL_FILES) - [ADDITIONAL_LEFS](#ADDITIONAL_LEFS) - [ADDITIONAL_LIBS](#ADDITIONAL_LIBS) +- [AUTO_MEMORIES](#AUTO_MEMORIES) - [BLOCKS](#BLOCKS) - [CAP_MARGIN](#CAP_MARGIN) - [CDL_FILES](#CDL_FILES) diff --git a/flow/BUILD b/flow/BUILD index 9b6aeb9b64..4f57af10d8 100644 --- a/flow/BUILD +++ b/flow/BUILD @@ -1,4 +1,5 @@ load("@bazel-orfs//:openroad.bzl", "orfs_pdk") +load("@rules_python//python:defs.bzl", "py_library", "py_test") # Expose every individual file under platforms/ as a public source-file # target, so designs in other packages can refer to e.g. @@ -23,13 +24,7 @@ exports_files( # instead of vendoring its own (drifting) copy at the bazel-orfs repo # root. See bazel-orfs `private/rules.bzl`. exports_files( - [ - "scripts/synth.tcl", - # Expose variables.yaml as an addressable source label so the - # orfs-vars MCP server (//tools/orfs_mcp) can data-dep the ORFS - # variable catalogue pinned to this commit. - "scripts/variables.yaml", - ], + ["scripts/synth.tcl"], visibility = ["//visibility:public"], ) @@ -37,23 +32,31 @@ exports_files( MAKEFILE_SHARED = [ "scripts/variables.json", "scripts/*.py", + "scripts/memories/*.py", "scripts/*.sh", "scripts/*.yaml", "scripts/*.mk", ] +MAKEFILE_SHARED_EXCLUDE = [ + "scripts/memories/*_test.py", +] + # makefile and scripts used by script/synth.sh steps filegroup( name = "makefile_yosys", srcs = ["Makefile"], - data = glob(MAKEFILE_SHARED + [ - "scripts/*.script", - "scripts/*.v", - "scripts/util.tcl", - "scripts/synth*.tcl", - "scripts/synth*.v", - "platforms/common/**/*.v", - ]) + [ + data = glob( + MAKEFILE_SHARED + [ + "scripts/*.script", + "scripts/*.v", + "scripts/util.tcl", + "scripts/synth*.tcl", + "scripts/synth*.v", + "platforms/common/**/*.v", + ], + exclude = MAKEFILE_SHARED_EXCLUDE, + ) + [ "//flow/util:makefile_yosys", ], visibility = ["//visibility:public"], @@ -63,10 +66,13 @@ filegroup( filegroup( name = "makefile", srcs = ["Makefile"], - data = glob(MAKEFILE_SHARED + [ - "scripts/*.tcl", - "platforms/common/**/*.v", - ]) + [ + data = glob( + MAKEFILE_SHARED + [ + "scripts/*.tcl", + "platforms/common/**/*.v", + ], + exclude = MAKEFILE_SHARED_EXCLUDE, + ) + [ "//flow/util:makefile", ], visibility = ["//visibility:public"], @@ -179,3 +185,47 @@ filegroup( "sky130hd", "sky130hs", ]] + +# AUTO_MEMORIES: pre-synthesis memory detection and .lib/.lef macro view +# generation. See docs/user/AutoMemories.md. The unit tests are the +# feature's test coverage — run with `bazelisk test //flow:memories_tests`. +py_library( + name = "memories", + srcs = glob( + ["scripts/memories/*.py"], + exclude = ["scripts/memories/*_test.py"], + ), + imports = ["scripts/memories"], + data = ["@fakeram//:all_files"], +) + +# Test fixtures (Verilog snippets) live in detect_test.py and are +# imported by the other tests. +py_library( + name = "memories_test_fixtures", + srcs = ["scripts/memories/detect_test.py"], + imports = ["scripts/memories"], + deps = [":memories"], +) + +MEMORIES_TESTS = [ + "detect_test", + "gen_memories_test", + "idiomatic_test", + "schema_test", +] + +[py_test( + name = "memories_" + test, + srcs = ["scripts/memories/{}.py".format(test)], + main = "scripts/memories/{}.py".format(test), + deps = [ + ":memories", + ":memories_test_fixtures", + ], +) for test in MEMORIES_TESTS] + +test_suite( + name = "memories_tests", + tests = ["memories_" + test for test in MEMORIES_TESTS], +) diff --git a/flow/Makefile b/flow/Makefile index d3472ee015..5db5c5db6a 100644 --- a/flow/Makefile +++ b/flow/Makefile @@ -261,6 +261,33 @@ $(SDC_FILE_CLOCK_PERIOD): $(SDC_FILE) .PHONY: yosys-dependencies yosys-dependencies: $(YOSYS_DEPENDENCIES) +# AUTO_MEMORIES: detect memories in the RTL pre-synthesis and generate +# .lib/.lef macro views for them. Experimental; see +# docs/user/AutoMemories.md. +ifeq ($(AUTO_MEMORIES),1) +$(RESULTS_DIR)/memories_inferred.json: $(VERILOG_FILES) $(SCRIPTS_DIR)/memories/extract_memories.tcl + mkdir -p $(RESULTS_DIR) $(LOG_DIR) + $(SCRIPTS_DIR)/synth.sh $(SCRIPTS_DIR)/memories/extract_memories.tcl $(LOG_DIR)/memories_extract.log + +.PHONY: do-auto-memories +do-auto-memories: $(RESULTS_DIR)/memories_inferred.json + mkdir -p $(RESULTS_DIR) + $(PYTHON_EXE) $(SCRIPTS_DIR)/memories/gen_memories.py \ + --platform $(PLATFORM) \ + --yosys-json $(RESULTS_DIR)/memories_inferred.json \ + --out-dir $(RESULTS_DIR)/memories \ + --json $(RESULTS_DIR)/memories.json \ + $(foreach file,$(VERILOG_FILES),--verilog $(file)) \ + $(foreach file,$(ADDITIONAL_MEMORIES),--memories $(file)) + +$(RESULTS_DIR)/memories.json: $(RESULTS_DIR)/memories_inferred.json $(ADDITIONAL_MEMORIES) \ + $(wildcard $(SCRIPTS_DIR)/memories/*.py) + $(UNSET_AND_MAKE) do-auto-memories + +yosys-dependencies: $(RESULTS_DIR)/memories.json +$(RESULTS_DIR)/1_1_yosys_canonicalize.rtlil: $(RESULTS_DIR)/memories.json +endif + .PHONY: do-yosys do-yosys: yosys-dependencies $(SCRIPTS_DIR)/synth.sh $(SYNTH_SCRIPT) $(LOG_DIR)/1_2_yosys.log @@ -278,6 +305,7 @@ $(RESULTS_DIR)/1_2_yosys.v $(RESULTS_DIR)/1_2_yosys.sdc: $(RESULTS_DIR)/1_1_yosy .PHONY: clean_synth clean_synth: rm -f $(RESULTS_DIR)/1_* $(RESULTS_DIR)/mem*.json + rm -rf $(RESULTS_DIR)/memories rm -f $(REPORTS_DIR)/synth_* rm -f $(LOG_DIR)/1_* rm -f $(SYNTH_STATS) diff --git a/flow/designs/asap7/tinyRocket/BUILD b/flow/designs/asap7/tinyRocket/BUILD new file mode 100644 index 0000000000..527d6542e1 --- /dev/null +++ b/flow/designs/asap7/tinyRocket/BUILD @@ -0,0 +1,3 @@ +load("//flow/designs:design.bzl", "design") + +design(config = "config.mk") diff --git a/flow/designs/asap7/tinyRocket/config.mk b/flow/designs/asap7/tinyRocket/config.mk new file mode 100644 index 0000000000..1d2ac6962a --- /dev/null +++ b/flow/designs/asap7/tinyRocket/config.mk @@ -0,0 +1,30 @@ +export DESIGN_NICKNAME = tinyRocket +export DESIGN_NAME = RocketTile +export PLATFORM = asap7 + +# The generic tinyRocket sources only: unlike the nangate45 tinyRocket +# there is no hand-written platform memory-mapping file and no +# checked-in fakeram .lib/.lef — AUTO_MEMORIES detects the memory +# wrapper modules and generates macro views for them instead. +export VERILOG_FILES = $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/AsyncResetReg.v \ + $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/ClockDivider2.v \ + $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/ClockDivider3.v \ + $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/plusarg_reader.v \ + $(DESIGN_HOME)/src/$(DESIGN_NICKNAME)/freechips.rocketchip.system.TinyConfig.v + +export SDC_FILE = $(DESIGN_HOME)/$(PLATFORM)/$(DESIGN_NICKNAME)/constraint.sdc + +export AUTO_MEMORIES = 1 +# tag_array (4x25) falls below the idiomatic-macro floors, but this RTL +# provides no behavioral fallback (the wrapper instantiates a +# tag_array_ext module the sources never define), so its conversion is +# forced via a .memories override. +export ADDITIONAL_MEMORIES = $(DESIGN_HOME)/$(PLATFORM)/$(DESIGN_NICKNAME)/tag_array.memories + +export CORE_UTILIZATION = 40 +export CORE_MARGIN = 2 + +export PLACE_DENSITY_LB_ADDON = 0.10 +export MACRO_PLACE_HALO = 2 2 + +export TNS_END_PERCENT = 100 diff --git a/flow/designs/asap7/tinyRocket/constraint.sdc b/flow/designs/asap7/tinyRocket/constraint.sdc new file mode 100644 index 0000000000..9eb2521bb4 --- /dev/null +++ b/flow/designs/asap7/tinyRocket/constraint.sdc @@ -0,0 +1,3 @@ +current_design RocketTile + +create_clock -name core_clock -period 1600 [get_ports {clock}] diff --git a/flow/designs/asap7/tinyRocket/tag_array.memories b/flow/designs/asap7/tinyRocket/tag_array.memories new file mode 100644 index 0000000000..fc03b36d73 --- /dev/null +++ b/flow/designs/asap7/tinyRocket/tag_array.memories @@ -0,0 +1,10 @@ +{ + "version": 1, + "memories": [ + { + "name": "tag_array", + "idiomatic": true, + "reason": "forced: the RTL provides no behavioral fallback for this wrapper" + } + ] +} diff --git a/flow/scripts/load.tcl b/flow/scripts/load.tcl index 6d946198d9..1b3a6c4632 100644 --- a/flow/scripts/load.tcl +++ b/flow/scripts/load.tcl @@ -23,6 +23,13 @@ proc load_design { design_file sdc_file } { read_lef $lef } } + # AUTO_MEMORIES: abstract LEFs generated pre-synthesis; globbed + # because the file names are only known at run time. + if { [env_var_equals AUTO_MEMORIES 1] } { + foreach lef [glob -nocomplain $::env(RESULTS_DIR)/memories/*.lef] { + read_lef $lef + } + } read_verilog $::env(RESULTS_DIR)/$design_file log_cmd link_design {*}[hier_options] $::env(DESIGN_NAME) } elseif { $ext == ".odb" } { diff --git a/flow/scripts/memories/bazel-orfs-auto-memories.patch b/flow/scripts/memories/bazel-orfs-auto-memories.patch new file mode 100644 index 0000000000..408c274a9b --- /dev/null +++ b/flow/scripts/memories/bazel-orfs-auto-memories.patch @@ -0,0 +1,170 @@ +From 43f2d13a2669cc590d3af06c4e74647321f68095 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?=C3=98yvind=20Harboe?= +Date: Sun, 19 Jul 2026 18:36:34 +0200 +Subject: [PATCH] rules: declare and propagate AUTO_MEMORIES stage artifacts +MIME-Version: 1.0 +Content-Type: text/plain; charset=UTF-8 +Content-Transfer-Encoding: 8bit + +ORFS's experimental AUTO_MEMORIES flow generates results/memories.json +plus a memories/ directory of generated .lib/.lef macro views during +canonicalization, and every later stage reads them from the results +dir at tcl run time. In bazel-orfs each stage runs in a sandbox where +only declared outputs survive, so without this change the generated +views are discarded after synthesis and floorplan fails to link the +blackboxed memory modules. + +Declare memories.json and the memories/ directory (a directory +artifact: the per-memory file names are only known at run time) as +canonicalize outputs when AUTO_MEMORIES=1, carry them on the new +OrfsInfo.memories field, and stage them into every downstream stage's +sandbox via source_inputs(). AUTO_MEMORIES is rejected with +SYNTH_USE_SYN, which has no yosys canonicalize step. + +User-supplied ADDITIONAL_MEMORIES files need no new machinery: they +reach the synth sandbox like any other sources= entry. + +Signed-off-by: Øyvind Harboe +--- + private/environment.bzl | 8 ++++++++ + private/providers.bzl | 1 + + private/rules.bzl | 29 ++++++++++++++++++++++++++--- + 3 files changed, 35 insertions(+), 3 deletions(-) + +diff --git a/private/environment.bzl b/private/environment.bzl +index f643501..f69359b 100644 +--- a/private/environment.bzl ++++ b/private/environment.bzl +@@ -229,6 +229,11 @@ def source_inputs(ctx): + ctx.attr.src[OrfsInfo].additional_lefs, + ctx.attr.src[OrfsInfo].additional_libs, + ctx.attr.src[OrfsInfo].additional_libs_pre_layout, ++ # AUTO_MEMORIES artifacts (memories.json + the generated ++ # .lib/.lef directory): later stages glob them from the ++ # results dir at tcl run time, so they must be staged in ++ # every downstream stage's sandbox. ++ ctx.attr.src[OrfsInfo].memories, + ctx.attr.src[PdkInfo].files, + ctx.attr.src[PdkInfo].libs, + # Accumulate all JSON reports, so depend on previous stage. +@@ -604,6 +609,9 @@ def _artifact_name(ctx, category, name = None): + def declare_artifact(ctx, category, name): + return ctx.actions.declare_file(_artifact_name(ctx, category, name)) + ++def declare_directory_artifact(ctx, category, name): ++ return ctx.actions.declare_directory(_artifact_name(ctx, category, name)) ++ + def declare_artifacts(ctx, category, names): + """Declares multiple artifacts in one call. + +diff --git a/private/providers.bzl b/private/providers.bzl +index e2eabb2..8c3e5bf 100644 +--- a/private/providers.bzl ++++ b/private/providers.bzl +@@ -17,6 +17,7 @@ OrfsInfo = provider( + "additional_libs", + "additional_libs_pre_layout", + "arguments", ++ "memories", + ], + ) + PdkInfo = provider( +diff --git a/private/rules.bzl b/private/rules.bzl +index 6f0e502..e8379ef 100644 +--- a/private/rules.bzl ++++ b/private/rules.bzl +@@ -21,6 +21,7 @@ load( + "data_inputs", + "declare_artifact", + "declare_artifacts", ++ "declare_directory_artifact", + "deps_inputs", + "environment_string", + "extensionless_basename", +@@ -262,6 +263,7 @@ def _macro_impl(ctx): + additional_lefs = depset([]), + additional_libs = depset([]), + additional_libs_pre_layout = depset([]), ++ memories = depset([]), + arguments = depset([]), + ), + TopInfo( +@@ -519,6 +521,7 @@ def _arguments_impl(ctx): + additional_lefs = src_info.additional_lefs, + additional_libs = src_info.additional_libs, + additional_libs_pre_layout = src_info.additional_libs_pre_layout, ++ memories = src_info.memories, + arguments = depset( + [computed_json], + transitive = [src_info.arguments], +@@ -1353,6 +1356,22 @@ def _yosys_impl(ctx): + # come through arguments/stage_arguments, not extra_arguments .json files. + use_syn = all_arguments.get("SYNTH_USE_SYN") == "1" + ++ # AUTO_MEMORIES: the canonicalize step generates memories.json plus a ++ # directory of .lib/.lef macro views (file names are only known at run ++ # time, hence a directory artifact). Declared as canonicalize outputs ++ # and threaded to every later stage via OrfsInfo.memories / ++ # source_inputs(), matching where the flow's tcl globs them. ++ auto_memories = all_arguments.get("AUTO_MEMORIES") == "1" ++ if auto_memories and use_syn: ++ fail("AUTO_MEMORIES is not supported with SYNTH_USE_SYN in " + ++ str(ctx.label)) ++ memories_outputs = [] ++ if auto_memories: ++ memories_outputs = [ ++ declare_artifact(ctx, "results", "memories.json"), ++ declare_directory_artifact(ctx, "results", "memories"), ++ ] ++ + canon_logs = declare_artifacts(ctx, "logs", ["1_1_yosys_canonicalize.log"]) + + canon_output = declare_artifact(ctx, "results", CANON_OUTPUT) +@@ -1393,7 +1412,7 @@ def _yosys_impl(ctx): + canon_deps, + ], + ), +- outputs = [canon_output] + canon_logs, ++ outputs = [canon_output] + canon_logs + memories_outputs, + tools = yosys_inputs(ctx), + progress_message = "Canonicalizing RTL for %s" % module_top(ctx), + ) +@@ -1513,7 +1532,8 @@ def _yosys_impl(ctx): + config_environment(config), + ), + inputs = depset( +- [canon_output, config] + ctx.files.extra_configs, ++ [canon_output, config] + memories_outputs + ++ ctx.files.extra_configs, + transitive = [ + data_inputs(ctx), + pdk_inputs(ctx), +@@ -1553,7 +1573,8 @@ def _yosys_impl(ctx): + tools = depset(transitive = [flow_inputs(ctx)]), + ) + +- outputs = [canon_output, variables] + synth_outputs.values() ++ outputs = [canon_output, variables] + synth_outputs.values() + \ ++ memories_outputs + + # Write synth's data_arguments to a JSON so downstream stages + # inherit synth-time variables (SDC_FILE, VERILOG_FILES, SYNTH_*) +@@ -1721,6 +1742,7 @@ def _yosys_impl(ctx): + if (dep[OrfsInfo].lib_pre_layout or dep[OrfsInfo].lib) + ], + ), ++ memories = depset(memories_outputs), + arguments = depset([synth_args_json]), + ), + ctx.attr.pdk[PdkInfo], +@@ -2098,6 +2120,7 @@ def _make_impl( + additional_lefs = ctx.attr.src[OrfsInfo].additional_lefs, + additional_libs = ctx.attr.src[OrfsInfo].additional_libs, + additional_libs_pre_layout = ctx.attr.src[OrfsInfo].additional_libs_pre_layout, ++ memories = ctx.attr.src[OrfsInfo].memories, + arguments = depset( + [stage_json], + transitive = [ctx.attr.src[OrfsInfo].arguments] + +-- +2.53.0 + diff --git a/flow/scripts/memories/detect.py b/flow/scripts/memories/detect.py new file mode 100644 index 0000000000..c67862150e --- /dev/null +++ b/flow/scripts/memories/detect.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""Detect memory modules in Yosys netlist JSON outputs ($mem_v2 cells). + +Processes the JSON netlist emitted by Yosys after `proc; memory -nomap`. +Extracts memory parameters (depth, width, read/write port counts, write-enable +masks) and checks clock net equivalence across ports to determine whether all +ports share a single clock domain. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import schema + + +def parse_param_int(val) -> int: + """Parse an integer parameter from Yosys JSON (handles ints and binary strings).""" + if isinstance(val, int): + return val + if isinstance(val, str): + if val.startswith("0x"): + return int(val, 16) + try: + return int(val, 2) + except ValueError: + return int(val) + return int(val) + + +def scan_yosys_json(data: dict | str | Path) -> list[schema.Memory]: + """Extract memory modules from a Yosys netlist JSON output ($mem_v2 cells).""" + if isinstance(data, (str, Path)): + p = Path(data) + if not p.is_file(): + return [] + data = json.loads(p.read_text()) + + out: list[schema.Memory] = [] + modules = data.get("modules", {}) + + for mod_name, mod_info in modules.items(): + clean_mod_name = mod_name[1:] if mod_name.startswith("\\") else mod_name + cells = mod_info.get("cells", {}) + for cell_name, cell_info in cells.items(): + cell_type = cell_info.get("type", "") + if cell_type not in ("$mem_v2", "$mem"): + continue + + params = cell_info.get("parameters", {}) + conn = cell_info.get("connections", {}) + + size = parse_param_int(params.get("SIZE", 0)) + width = parse_param_int(params.get("WIDTH", 0)) + rd_ports = parse_param_int(params.get("RD_PORTS", 0)) + wr_ports = parse_param_int(params.get("WR_PORTS", 0)) + + if size == 0 or width == 0: + continue + + addr_w = (size - 1).bit_length() if size > 1 else 1 + + # Clock net tracking & single-clock validation across ports + rd_clks = conn.get("RD_CLK", []) + wr_clks = conn.get("WR_CLK", []) + all_clk_bits = [ + c for c in rd_clks + wr_clks if str(c) not in ("0", "1", "x", "z") + ] + single_clock = len(set(all_clk_bits)) <= 1 + + # Write enable mask lanes + wr_en_bits = conn.get("WR_EN", []) + mask_lanes = 0 + if wr_ports > 0 and len(wr_en_bits) > wr_ports: + mask_lanes = len(wr_en_bits) // wr_ports + + pins: list[schema.Pin] = [] + + for i in range(rd_ports): + port_id = f"R{i}" + pins.extend( + [ + schema.Pin( + name=f"{port_id}_clk", + direction="input", + width=1, + port_id=port_id, + function="clk", + ), + schema.Pin( + name=f"{port_id}_addr", + direction="input", + width=addr_w, + port_id=port_id, + function="addr", + ), + schema.Pin( + name=f"{port_id}_en", + direction="input", + width=1, + port_id=port_id, + function="en", + ), + schema.Pin( + name=f"{port_id}_data", + direction="output", + width=width, + port_id=port_id, + function="data_out", + ), + ] + ) + + for i in range(wr_ports): + port_id = f"W{i}" + pins.extend( + [ + schema.Pin( + name=f"{port_id}_clk", + direction="input", + width=1, + port_id=port_id, + function="clk", + ), + schema.Pin( + name=f"{port_id}_addr", + direction="input", + width=addr_w, + port_id=port_id, + function="addr", + ), + schema.Pin( + name=f"{port_id}_en", + direction="input", + width=1, + port_id=port_id, + function="en", + ), + schema.Pin( + name=f"{port_id}_data", + direction="input", + width=width, + port_id=port_id, + function="data_in", + ), + ] + ) + if mask_lanes > 0: + pins.append( + schema.Pin( + name=f"{port_id}_mask", + direction="input", + width=mask_lanes, + port_id=port_id, + function="mask", + ) + ) + + clean_cell = cell_name[1:] if cell_name.startswith("\\") else cell_name + mem_name = clean_mod_name if len(cells) == 1 else clean_cell + + mem = schema.Memory( + name=mem_name, + rows=size, + bits=width, + addr_w=addr_w, + read_ports=rd_ports, + write_ports=wr_ports, + rw_ports=0, + mask_lanes=mask_lanes, + pins=pins, + behavioral_model={"module": clean_mod_name}, + reason=f"Yosys inferred $mem_v2 ({'single-clock' if single_clock else 'multi-clock'})", + ) + out.append(mem) + + return out + + +def scan_files(paths: list[Path]) -> list[schema.Memory]: + """Scan Yosys netlist JSON files; later definitions of a name win.""" + found: dict[str, schema.Memory] = {} + for path in paths: + for memory in scan_yosys_json(path): + found[memory.name] = memory + return list(found.values()) diff --git a/flow/scripts/memories/detect_test.py b/flow/scripts/memories/detect_test.py new file mode 100644 index 0000000000..d378d11de1 --- /dev/null +++ b/flow/scripts/memories/detect_test.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import detect + + +class DetectTest(unittest.TestCase): + def test_scan_yosys_json_single_clock(self): + yosys_json = { + "modules": { + "\\sram_256x32": { + "cells": { + "\\$mem_0": { + "type": "$mem_v2", + "parameters": { + "SIZE": "00000000000000000000000100000000", # 256 + "WIDTH": "00000000000000000000000000100000", # 32 + "RD_PORTS": 1, + "WR_PORTS": 1, + }, + "connections": { + "RD_CLK": [10], + "WR_CLK": [10], + "RD_EN": [11], + "WR_EN": [12, 13, 14, 15], # 4 mask lanes + "RD_ADDR": [16, 17, 18, 19, 20, 21, 22, 23], + "WR_ADDR": [16, 17, 18, 19, 20, 21, 22, 23], + "RD_DATA": list(range(24, 56)), + "WR_DATA": list(range(56, 88)), + }, + } + } + } + } + } + mems = detect.scan_yosys_json(yosys_json) + self.assertEqual(len(mems), 1) + m = mems[0] + self.assertEqual( + (m.name, m.rows, m.bits, m.addr_w), ("sram_256x32", 256, 32, 8) + ) + self.assertEqual((m.read_ports, m.write_ports, m.mask_lanes), (1, 1, 4)) + self.assertIn("single-clock", m.reason) + + def test_scan_yosys_json_multi_clock(self): + yosys_json = { + "modules": { + "\\async_ram_512x16": { + "cells": { + "\\$mem_0": { + "type": "$mem_v2", + "parameters": { + "SIZE": 512, + "WIDTH": 16, + "RD_PORTS": 1, + "WR_PORTS": 1, + }, + "connections": { + "RD_CLK": [100], + "WR_CLK": [200], # Different clock net ID + "RD_EN": [101], + "WR_EN": [201], + "RD_ADDR": list(range(102, 111)), + "WR_ADDR": list(range(202, 211)), + "RD_DATA": list(range(111, 127)), + "WR_DATA": list(range(211, 227)), + }, + } + } + } + } + } + mems = detect.scan_yosys_json(yosys_json) + self.assertEqual(len(mems), 1) + m = mems[0] + self.assertEqual( + (m.name, m.rows, m.bits, m.addr_w), ("async_ram_512x16", 512, 16, 9) + ) + self.assertIn("multi-clock", m.reason) + + def test_scan_yosys_json_empty_or_non_memory(self): + yosys_json = { + "modules": { + "\\counter": { + "cells": { + "\\$add_0": { + "type": "$add", + "parameters": {"A_WIDTH": 8, "B_WIDTH": 8}, + "connections": {}, + } + } + } + } + } + self.assertEqual(detect.scan_yosys_json(yosys_json), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/scripts/memories/extract_memories.tcl b/flow/scripts/memories/extract_memories.tcl new file mode 100644 index 0000000000..1bf12eff30 --- /dev/null +++ b/flow/scripts/memories/extract_memories.tcl @@ -0,0 +1,22 @@ +# Yosys pre-synthesis pass for memory extraction. +# Elaborates RTL and collects inferred memory arrays into $mem_v2 primitives. +# tclint-disable command-args + +source $::env(SCRIPTS_DIR)/synth_preamble.tcl + +# Read all RTL sources using active frontend (all frontends) +read_design_sources + +# Elaborate hierarchy +hierarchy -top $::env(DESIGN_NAME) + +# Run process execution and memory collection +proc +memory -nomap + +# Write netlist JSON containing inferred $mem_v2 primitives +set out_json "$::env(RESULTS_DIR)/memories_inferred.json" +file mkdir [file dirname $out_json] +write_json $out_json + +exit diff --git a/flow/scripts/memories/gen_memories.py b/flow/scripts/memories/gen_memories.py new file mode 100644 index 0000000000..d6d6d12965 --- /dev/null +++ b/flow/scripts/memories/gen_memories.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""AUTO_MEMORIES driver: detect memories, judge them, emit macro views. + +Run pre-synthesis (before canonicalization). Scans the design's Verilog +for memory-shaped modules, merges user-supplied `.memories` files +(ADDITIONAL_MEMORIES), applies the idiomatic-macro gate, then writes: + + full inventory, converted or not (memories.json) + /.lib Liberty view per converted memory + /_pre_layout.lib ideal-clock variant for pre-CTS consumers + /.lef abstract LEF per converted memory + /blackboxes.txt converted module names, one per line — + what synthesis blackboxes + +Everything downstream consumes these files; nothing else is passed +between the generator and the flow. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import subprocess +import os + +import detect # noqa: E402 +import idiomatic # noqa: E402 +import schema # noqa: E402 + + +def find_fakeram_run() -> str | None: + fakeram_run = os.environ.get("FAKERAM_RUN_PY") + if fakeram_run and os.path.isfile(fakeram_run): + return fakeram_run + runfiles_dir = os.environ.get("RUNFILES_DIR") + if runfiles_dir: + for p in Path(runfiles_dir).rglob("run.py"): + if "fakeram" in p.parts[-2]: + return str(p) + return None + + +def run( + verilog: list[Path], + memories_files: list[Path], + platform: str, + out_dir: Path, + json_path: Path, + yosys_json: Path | None = None, +) -> int: + if platform != "asap7": + sys.stderr.write(f"gen_memories: unsupported platform {platform}\n") + return 1 + + if yosys_json and yosys_json.is_file(): + found = detect.scan_yosys_json(yosys_json) + else: + found = detect.scan_files(verilog) + + idiomatic.apply(found) + + overrides: list[schema.Memory] = [] + for path in memories_files: + overrides.extend(schema.load(path)) + memories = schema.merge(found, overrides) + + out_dir.mkdir(parents=True, exist_ok=True) + json_path.parent.mkdir(parents=True, exist_ok=True) + schema.dump(memories, json_path, platform) + + converted = sorted((m for m in memories if m.idiomatic), key=lambda m: m.name) + for mem in converted: + schema.validate_emittable(mem) + + fakeram_run = find_fakeram_run() + if not fakeram_run: + sys.stderr.write( + "gen_memories: FAKERAM_RUN_PY not set and FakeRAM run.py not found.\n" + ) + return 1 + + subprocess.check_call( + [ + sys.executable, + fakeram_run, + "--orfs_asap7_backend", + "--output_dir", + str(out_dir), + str(json_path), + ] + ) + + for mem in sorted(memories, key=lambda m: m.name): + verdict = "macro" if mem.idiomatic else "flops" + sys.stderr.write( + f"gen_memories: {mem.name} {mem.rows}x{mem.bits} " + f"R={mem.read_ports} W={mem.write_ports} RW={mem.rw_ports} " + f"mask_lanes={mem.mask_lanes} -> {verdict} ({mem.reason})\n" + ) + if not memories: + sys.stderr.write("gen_memories: no memory-shaped modules found\n") + return 0 + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument( + "--verilog", + action="append", + default=[], + type=Path, + help="Verilog source file to scan (repeatable).", + ) + p.add_argument( + "--yosys-json", + type=Path, + default=None, + help="Yosys netlist JSON file containing $mem_v2 primitives.", + ) + p.add_argument( + "--memories", + action="append", + default=[], + type=Path, + help="User-supplied .memories file merged onto the " + "detected set (repeatable).", + ) + p.add_argument("--platform", required=True) + p.add_argument( + "--out-dir", + required=True, + type=Path, + help="Directory for generated .lib/.lef/blackboxes.txt.", + ) + p.add_argument( + "--json", + required=True, + type=Path, + help="Path of the memories.json inventory to write.", + ) + args = p.parse_args(argv) + return run( + args.verilog, + args.memories, + args.platform, + args.out_dir, + args.json, + args.yosys_json, + ) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/flow/scripts/memories/gen_memories_test.py b/flow/scripts/memories/gen_memories_test.py new file mode 100644 index 0000000000..96cb1fad2a --- /dev/null +++ b/flow/scripts/memories/gen_memories_test.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import gen_memories + +# Setup FAKERAM_RUN_PY using runfiles if available, otherwise assume a relative path +if "TEST_WORKSPACE" in os.environ: + # Bazel test execution + runfiles_dir = Path(os.environ.get("RUNFILES_DIR", ".")) + candidates = list(runfiles_dir.glob("**/fakeram*/run.py")) + list( + runfiles_dir.glob("**/run.py") + ) + fakeram_run = candidates[0] if candidates else runfiles_dir / "fakeram" / "run.py" +else: + fakeram_run = ( + Path(__file__).resolve().parent.parent.parent.parent + / "tools" + / "FakeRAM2.0" + / "run.py" + ) + +os.environ["FAKERAM_RUN_PY"] = str(fakeram_run) + +SAMPLE_YOSYS_NETLIST = { + "modules": { + "\\mem_128x32": { + "cells": { + "\\$mem_0": { + "type": "$mem_v2", + "parameters": { + "SIZE": 128, + "WIDTH": 32, + "RD_PORTS": 1, + "WR_PORTS": 1, + }, + "connections": { + "RD_CLK": [10], + "WR_CLK": [10], + "RD_EN": [11], + "WR_EN": [12, 13, 14, 15], + "RD_ADDR": list(range(16, 23)), + "WR_ADDR": list(range(16, 23)), + "RD_DATA": list(range(24, 56)), + "WR_DATA": list(range(56, 88)), + }, + } + } + }, + "\\cache_tags": { + "cells": { + "\\$mem_0": { + "type": "$mem_v2", + "parameters": { + "SIZE": 4, + "WIDTH": 25, + "RD_PORTS": 1, + "WR_PORTS": 1, + }, + "connections": { + "RD_CLK": [10], + "WR_CLK": [10], + "RD_EN": [11], + "WR_EN": [12], + "RD_ADDR": [13, 14], + "WR_ADDR": [13, 14], + "RD_DATA": list(range(15, 40)), + "WR_DATA": list(range(40, 65)), + }, + } + } + }, + } +} + +FORCE_TAGS = """\ +{ + "version": 1, + "memories": [ + { + "name": "cache_tags", + "idiomatic": true, + "reason": "forced: RTL provides no behavioral fallback" + } + ] +} +""" + + +class GenMemoriesTest(unittest.TestCase): + def run_generator(self, memories_files=(), platform="asap7"): + d = Path(self.tmp.name) + netlist_json = d / "memories_inferred.json" + netlist_json.write_text(json.dumps(SAMPLE_YOSYS_NETLIST)) + argv = [ + "--platform", + platform, + "--out-dir", + str(d / "memories"), + "--json", + str(d / "memories.json"), + "--yosys-json", + str(netlist_json), + ] + for f in memories_files: + argv += ["--memories", str(f)] + return gen_memories.main(argv), d + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + + def test_flow_contract(self): + code, d = self.run_generator() + self.assertEqual(code, 0) + + doc = json.loads((d / "memories.json").read_text()) + by_name = {m["name"]: m for m in doc["memories"]} + self.assertEqual(set(by_name), {"mem_128x32", "cache_tags"}) + self.assertTrue(by_name["mem_128x32"]["idiomatic"]) + self.assertFalse(by_name["cache_tags"]["idiomatic"]) + self.assertIn("depth 4", by_name["cache_tags"]["reason"]) + + mems_dir = d / "memories" + self.assertEqual( + sorted(p.name for p in mems_dir.iterdir()), + [ + "blackboxes.txt", + "mem_128x32.lef", + "mem_128x32.lib", + "mem_128x32_pre_layout.lib", + ], + ) + self.assertEqual((mems_dir / "blackboxes.txt").read_text(), "mem_128x32\n") + + def test_additional_memories_forces_conversion(self): + force = Path(self.tmp.name) / "force.memories" + force.write_text(FORCE_TAGS) + code, d = self.run_generator(memories_files=[force]) + self.assertEqual(code, 0) + blackboxes = (d / "memories" / "blackboxes.txt").read_text().split() + self.assertEqual(sorted(blackboxes), ["cache_tags", "mem_128x32"]) + self.assertTrue((d / "memories" / "cache_tags.lib").exists()) + self.assertTrue((d / "memories" / "cache_tags.lef").exists()) + doc = json.loads((d / "memories.json").read_text()) + tags = next(m for m in doc["memories"] if m["name"] == "cache_tags") + self.assertTrue(tags["idiomatic"]) + self.assertIn("forced", tags["reason"]) + + def test_unsupported_platform_fails_clearly(self): + code, _d = self.run_generator(platform="nangate45") + self.assertEqual(code, 1) + + def test_bad_memories_file_fails(self): + bad = Path(self.tmp.name) / "bad.memories" + bad.write_text("{not json") + with self.assertRaises(json.JSONDecodeError): + self.run_generator(memories_files=[bad]) + + def test_no_memories_still_writes_contract_files(self): + d = Path(self.tmp.name) + empty_netlist = d / "empty.json" + empty_netlist.write_text(json.dumps({"modules": {}})) + code = gen_memories.main( + [ + "--platform", + "asap7", + "--out-dir", + str(d / "memories"), + "--json", + str(d / "memories.json"), + "--yosys-json", + str(empty_netlist), + ] + ) + self.assertEqual(code, 0) + self.assertEqual(json.loads((d / "memories.json").read_text())["memories"], []) + self.assertEqual((d / "memories" / "blackboxes.txt").read_text(), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/scripts/memories/idiomatic.py b/flow/scripts/memories/idiomatic.py new file mode 100644 index 0000000000..e32221eaf4 --- /dev/null +++ b/flow/scripts/memories/idiomatic.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Decide which detected memories are idiomatic as ASAP7 SRAM macros. + +A memory below these floors is cheaper as flip-flops than as an SRAM +macro (the macro pays a fixed control/decode/sense-amp floor), and a +memory with too many ports has no single-macro implementation in +ordinary SRAM compilers. Rejected memories keep `idiomatic: false` plus +a reason in memories.json and synthesize as flops. + +The thresholds are deliberately simple, first-pass policy. Banking and +multi-port decomposition (splitting a too-wide/too-ported memory across +several macros) are not handled — a future extension. A user who wants +a rejected memory converted anyway overrides it via a `.memories` file +listed in ADDITIONAL_MEMORIES. +""" + +from __future__ import annotations + +import schema + +MIN_ROWS = 16 +MIN_BITS_TOTAL = 256 +MAX_TOTAL_PORTS = 4 + + +def judge(mem: schema.Memory) -> tuple[bool, str]: + """Return (idiomatic, reason).""" + if mem.bits < 1: + return False, "no data pins" + if mem.rows < MIN_ROWS: + return False, f"depth {mem.rows} below macro floor {MIN_ROWS}" + total_bits = mem.rows * mem.bits + if total_bits < MIN_BITS_TOTAL: + return ( + False, + f"capacity {total_bits} bits below macro floor " f"{MIN_BITS_TOTAL}", + ) + if mem.total_ports() > MAX_TOTAL_PORTS: + return ( + False, + f"{mem.total_ports()} ports exceeds single-macro " + f"limit {MAX_TOTAL_PORTS}", + ) + return True, "meets ASAP7 macro floors" + + +def apply(memories: list[schema.Memory]) -> None: + for mem in memories: + mem.idiomatic, mem.reason = judge(mem) diff --git a/flow/scripts/memories/idiomatic_test.py b/flow/scripts/memories/idiomatic_test.py new file mode 100644 index 0000000000..d26fbfc040 --- /dev/null +++ b/flow/scripts/memories/idiomatic_test.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import idiomatic +import schema + + +def mem(rows, bits, read_ports=1, write_ports=1, rw_ports=0): + return schema.Memory( + name="m", + rows=rows, + bits=bits, + read_ports=read_ports, + write_ports=write_ports, + rw_ports=rw_ports, + ) + + +class IdiomaticTest(unittest.TestCase): + def test_accepts_macro_sized_memory(self): + ok, reason = idiomatic.judge(mem(64, 32)) + self.assertTrue(ok, reason) + + def test_rejects_shallow_memory(self): + ok, reason = idiomatic.judge(mem(4, 25)) + self.assertFalse(ok) + self.assertIn("depth 4", reason) + + def test_rejects_small_capacity(self): + # 16 rows x 8 bits = 128 bits: deep enough, too small overall. + ok, reason = idiomatic.judge(mem(16, 8)) + self.assertFalse(ok) + self.assertIn("capacity 128", reason) + + def test_rejects_too_many_ports(self): + ok, reason = idiomatic.judge(mem(256, 32, read_ports=4, write_ports=2)) + self.assertFalse(ok) + self.assertIn("ports", reason) + + def test_apply_sets_fields(self): + memories = [mem(64, 32), mem(4, 25)] + idiomatic.apply(memories) + self.assertTrue(memories[0].idiomatic) + self.assertFalse(memories[1].idiomatic) + self.assertTrue(memories[1].reason) + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/scripts/memories/schema.py b/flow/scripts/memories/schema.py new file mode 100644 index 0000000000..060cf277c8 --- /dev/null +++ b/flow/scripts/memories/schema.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""The `.memories` file format: a JSON inventory of memory macros. + +One `.memories` file (and the flow-generated `memories.json`) describes +memories at the module boundary: geometry, the full pin list with each +pin's function, the behavioral model the RTL provides, and whether the +memory is converted to a macro (`idiomatic`). + +The file-based handoff is deliberate: everything downstream — synthesis +blackboxing, liberty/LEF consumption in later stages, build systems that +declare flow artifacts as transitive dependencies — keys off these files +rather than off in-process state. +""" + +from __future__ import annotations + +import json +from dataclasses import asdict, dataclass, field +from pathlib import Path + +SCHEMA_VERSION = 1 + +PIN_FUNCTIONS = ("addr", "en", "wmode", "mask", "data_in", "data_out", "clk") +DIRECTIONS = ("input", "output") + + +class SchemaError(ValueError): + pass + + +@dataclass +class Pin: + name: str + direction: str # "input" / "output" + width: int + port_id: str # "R0", "W1", "RW0", ... + function: str # one of PIN_FUNCTIONS + + +@dataclass +class Memory: + name: str + rows: int = 0 + bits: int = 0 + addr_w: int = 0 + read_ports: int = 0 + write_ports: int = 0 + rw_ports: int = 0 + # Total width of the per-port write mask, 0 if unmasked. Subword-split + # mask pins (`W0_mask_0..3`) contribute one lane each. + mask_lanes: int = 0 + pins: list[Pin] = field(default_factory=list) + # The module whose RTL body simulates this memory: {"file", "module"}. + behavioral_model: dict | None = None + # True when the memory is converted to a macro (.lib/.lef emitted and + # the module blackboxed); False leaves it to synthesize as flops. + idiomatic: bool = False + reason: str = "" + + def total_ports(self) -> int: + return self.read_ports + self.write_ports + self.rw_ports + + def to_dict(self) -> dict: + return asdict(self) + + +def _pin_from_dict(d: dict) -> Pin: + if not isinstance(d, dict): + raise SchemaError("expected a dictionary for pin record") + try: + pin = Pin( + name=d["name"], + direction=d["direction"], + width=int(d["width"]), + port_id=d["port_id"], + function=d["function"], + ) + except KeyError as e: + raise SchemaError(f"pin record missing field {e}") from e + if pin.direction not in DIRECTIONS: + raise SchemaError(f"pin {pin.name}: bad direction '{pin.direction}'") + if pin.function not in PIN_FUNCTIONS: + raise SchemaError( + f"pin {pin.name}: unknown function " + f"'{pin.function}' (expected one of " + f"{', '.join(PIN_FUNCTIONS)})" + ) + if pin.width < 1: + raise SchemaError(f"pin {pin.name}: width must be >= 1") + if not pin.port_id: + raise SchemaError(f"pin {pin.name}: empty port_id") + return pin + + +def memory_from_dict(d: dict) -> Memory: + if not isinstance(d, dict): + raise SchemaError("expected a dictionary for memory record") + if "name" not in d: + raise SchemaError("memory record missing 'name'") + mem = Memory(name=d["name"]) + for key in ( + "rows", + "bits", + "addr_w", + "read_ports", + "write_ports", + "rw_ports", + "mask_lanes", + ): + if key in d: + setattr(mem, key, int(d[key])) + if "pins" in d: + mem.pins = [_pin_from_dict(p) for p in d["pins"]] + if "behavioral_model" in d: + mem.behavioral_model = d["behavioral_model"] + if "idiomatic" in d: + mem.idiomatic = bool(d["idiomatic"]) + if "reason" in d: + mem.reason = str(d["reason"]) + return mem + + +def load(path: Path) -> list[Memory]: + """Load a .memories / memories.json file. + + We expect the JSON file to be valid and readable. If it is not, + uncaught exceptions (e.g. FileNotFoundError, JSONDecodeError) provide + full detailed stack traces and debug information. + """ + doc = json.loads(path.read_text()) + if not isinstance(doc, dict) or "memories" not in doc: + raise SchemaError(f"{path}: expected an object with a 'memories' list") + version = doc.get("version", SCHEMA_VERSION) + if version != SCHEMA_VERSION: + raise SchemaError(f"{path}: unsupported schema version {version}") + return [memory_from_dict(m) for m in doc["memories"]] + + +def dump(memories: list[Memory], path: Path, platform: str) -> None: + doc = { + "version": SCHEMA_VERSION, + "platform": platform, + "memories": [m.to_dict() for m in sorted(memories, key=lambda m: m.name)], + } + path.write_text(json.dumps(doc, indent=2) + "\n") + + +def merge(detected: list[Memory], overrides: list[Memory]) -> list[Memory]: + """Merge user-supplied entries onto the detected set. + + An override naming a detected memory replaces only the fields it + carries (geometry and pins are kept from detection unless the + override provides its own). An override naming an unknown memory is + taken whole — it must then carry pins and geometry itself to be + emittable. + """ + by_name = {m.name: m for m in detected} + for o in overrides: + base = by_name.get(o.name) + if base is None: + by_name[o.name] = o + continue + if o.pins: + base.pins = o.pins + for key in ( + "rows", + "bits", + "addr_w", + "read_ports", + "write_ports", + "rw_ports", + "mask_lanes", + ): + value = getattr(o, key) + if value: + setattr(base, key, value) + if o.behavioral_model is not None: + base.behavioral_model = o.behavioral_model + if o.idiomatic: + base.idiomatic = True + if o.reason: + base.reason = o.reason + return list(by_name.values()) + + +def validate_emittable(mem: Memory) -> None: + """Raise SchemaError unless `mem` carries enough to emit .lib/.lef.""" + if not mem.pins: + raise SchemaError(f"memory {mem.name}: no pins") + if mem.rows < 1 or mem.bits < 1: + raise SchemaError( + f"memory {mem.name}: rows ({mem.rows}) and bits ({mem.bits}) " + f"must be >= 1" + ) + port_ids = {p.port_id for p in mem.pins} + for port_id in port_ids: + functions = {p.function for p in mem.pins if p.port_id == port_id} + if "clk" not in functions: + raise SchemaError(f"memory {mem.name}: port {port_id} has no clk pin") + if "addr" not in functions: + raise SchemaError(f"memory {mem.name}: port {port_id} has no addr pin") + if not functions & {"data_in", "data_out"}: + raise SchemaError(f"memory {mem.name}: port {port_id} has no data pin") diff --git a/flow/scripts/memories/schema_test.py b/flow/scripts/memories/schema_test.py new file mode 100644 index 0000000000..31775f1b01 --- /dev/null +++ b/flow/scripts/memories/schema_test.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import schema + + +def sample_memory(name="mem_64x32") -> schema.Memory: + return schema.Memory( + name=name, + rows=64, + bits=32, + addr_w=6, + read_ports=1, + write_ports=1, + pins=[ + schema.Pin("R0_addr", "input", 6, "R0", "addr"), + schema.Pin("R0_en", "input", 1, "R0", "en"), + schema.Pin("R0_clk", "input", 1, "R0", "clk"), + schema.Pin("R0_data", "output", 32, "R0", "data_out"), + schema.Pin("W0_addr", "input", 6, "W0", "addr"), + schema.Pin("W0_en", "input", 1, "W0", "en"), + schema.Pin("W0_clk", "input", 1, "W0", "clk"), + schema.Pin("W0_data", "input", 32, "W0", "data_in"), + ], + behavioral_model={"file": "mems.v", "module": name}, + idiomatic=True, + reason="meets ASAP7 macro floors", + ) + + +class SchemaTest(unittest.TestCase): + def test_round_trip(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "memories.json" + schema.dump([sample_memory()], path, platform="asap7") + loaded = schema.load(path) + self.assertEqual(len(loaded), 1) + self.assertEqual(loaded[0].to_dict(), sample_memory().to_dict()) + + def test_dump_is_sorted_and_versioned(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "memories.json" + schema.dump( + [sample_memory("zz"), sample_memory("aa")], path, platform="asap7" + ) + doc = json.loads(path.read_text()) + self.assertEqual(doc["version"], schema.SCHEMA_VERSION) + self.assertEqual(doc["platform"], "asap7") + self.assertEqual([m["name"] for m in doc["memories"]], ["aa", "zz"]) + + def test_merge_partial_override(self): + detected = [sample_memory()] + detected[0].idiomatic = False + detected[0].reason = "depth 4 below macro floor 16" + override = schema.Memory( + name="mem_64x32", idiomatic=True, reason="forced: no behavioral fallback" + ) + merged = schema.merge(detected, [override]) + self.assertEqual(len(merged), 1) + m = merged[0] + self.assertTrue(m.idiomatic) + self.assertEqual(m.reason, "forced: no behavioral fallback") + # Geometry and pins kept from detection. + self.assertEqual((m.rows, m.bits), (64, 32)) + self.assertEqual(len(m.pins), 8) + + def test_merge_new_entry_taken_whole(self): + extra = sample_memory("mem_extra") + merged = schema.merge([sample_memory()], [extra]) + self.assertEqual(sorted(m.name for m in merged), ["mem_64x32", "mem_extra"]) + + def test_load_rejects_bad_documents(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "bad.memories" + path.write_text("[]") + with self.assertRaises(schema.SchemaError): + schema.load(path) + path.write_text('{"version": 99, "memories": []}') + with self.assertRaises(schema.SchemaError): + schema.load(path) + path.write_text('{"memories": [{"rows": 4}]}') + with self.assertRaises(schema.SchemaError): + schema.load(path) + path.write_text( + '{"memories": [{"name": "m", "pins": ' + '[{"name": "p", "direction": "input", "width": 1, ' + '"port_id": "R0", "function": "banana"}]}]}' + ) + with self.assertRaises(schema.SchemaError): + schema.load(path) + + def test_validate_emittable(self): + good = sample_memory() + schema.validate_emittable(good) # no raise + with self.assertRaises(schema.SchemaError): + schema.validate_emittable(schema.Memory(name="empty")) + clkless = sample_memory() + clkless.pins = [p for p in clkless.pins if p.function != "clk"] + with self.assertRaises(schema.SchemaError): + schema.validate_emittable(clkless) + addrless = sample_memory() + addrless.pins = [p for p in addrless.pins if p.function != "addr"] + with self.assertRaises(schema.SchemaError): + schema.validate_emittable(addrless) + dataless = sample_memory() + dataless.pins = [ + p for p in dataless.pins if p.function not in ("data_in", "data_out") + ] + with self.assertRaises(schema.SchemaError): + schema.validate_emittable(dataless) + + +if __name__ == "__main__": + unittest.main() diff --git a/flow/scripts/read_liberty.tcl b/flow/scripts/read_liberty.tcl index 14f8f06e7a..1c013611dd 100644 --- a/flow/scripts/read_liberty.tcl +++ b/flow/scripts/read_liberty.tcl @@ -16,3 +16,23 @@ if { [env_var_exists_and_non_empty CORNERS] } { log_cmd read_liberty $libFile } } + +# AUTO_MEMORIES: liberty views generated pre-synthesis by +# scripts/memories/gen_memories.py. The file names are only known at +# run time, so they are globbed here rather than threaded through +# LIB_FILES. The _pre_layout variants (ideal clock) are for pre-CTS +# consumers that select lib files themselves. +if { [env_var_equals AUTO_MEMORIES 1] } { + foreach libFile [glob -nocomplain $::env(RESULTS_DIR)/memories/*.lib] { + if { [string match *_pre_layout.lib $libFile] } { + continue + } + if { [env_var_exists_and_non_empty CORNERS] } { + foreach corner $::env(CORNERS) { + log_cmd read_liberty -corner $corner $libFile + } + } else { + log_cmd read_liberty $libFile + } + } +} diff --git a/flow/scripts/synth_preamble.tcl b/flow/scripts/synth_preamble.tcl index 18e27b4aa5..87555037e9 100644 --- a/flow/scripts/synth_preamble.tcl +++ b/flow/scripts/synth_preamble.tcl @@ -29,6 +29,25 @@ proc read_checkpoint { file } { } } +# AUTO_MEMORIES: memory modules whose generated liberty view replaces +# their behavioral body during synthesis. The list is produced by +# scripts/memories/gen_memories.py before canonicalization; see +# docs/user/AutoMemories.md. +proc auto_memories_blackboxes { } { + if { ![env_var_equals AUTO_MEMORIES 1] } { + return {} + } + set f "$::env(RESULTS_DIR)/memories/blackboxes.txt" + if { ![file exists $f] } { + error "AUTO_MEMORIES=1 but $f is missing;\ + the do-auto-memories step must run before synthesis" + } + set fh [open $f r] + set content [string map {\r ""} [read $fh]] + close $fh + return [regexp -all -inline {\S+} $content] +} + proc read_design_sources { } { # We are reading Verilog sources source $::env(SCRIPTS_DIR)/synth_stdcells.tcl @@ -80,6 +99,12 @@ proc read_design_sources { } { } } + # Blackbox AUTO_MEMORIES-detected memory modules so their generated + # liberty view wins over their behavioral bodies. + foreach m [auto_memories_blackboxes] { + lappend slang_args --blackboxed-module "$m" + } + # Add user arguments lappend slang_args {*}$::env(SYNTH_SLANG_ARGS) @@ -105,6 +130,9 @@ proc read_design_sources { } { if { [env_var_exists_and_non_empty SYNTH_BLACKBOXES] } { error "Non-empty SYNTH_BLACKBOXES unsupported with HDL frontend \"verific\"" } + if { [llength [auto_memories_blackboxes]] > 0 } { + error "AUTO_MEMORIES unsupported with HDL frontend \"$::env(SYNTH_HDL_FRONTEND)\"" + } } elseif { ![env_var_exists_and_non_empty SYNTH_HDL_FRONTEND] } { verilog_defaults -push if { [env_var_exists_and_non_empty VERILOG_DEFINES] } { @@ -124,6 +152,18 @@ proc read_design_sources { } { chparam -set $key $value $::env(DESIGN_NAME) } + # AUTO_MEMORIES blackboxing runs before `hierarchy -check`: a + # memory wrapper may instantiate modules the sources never define + # (the behavioral body is being discarded anyway), so the check is + # only meaningful after the bodies are gone. + set auto_blackboxes [auto_memories_blackboxes] + if { [llength $auto_blackboxes] > 0 } { + hierarchy -top $::env(DESIGN_NAME) + foreach m $auto_blackboxes { + blackbox $m + } + hierarchy -check -top $::env(DESIGN_NAME) + } if { [env_var_exists_and_non_empty SYNTH_BLACKBOXES] } { hierarchy -check -top $::env(DESIGN_NAME) foreach m $::env(SYNTH_BLACKBOXES) { diff --git a/flow/scripts/variables.json b/flow/scripts/variables.json index d0d8d0dbbf..2752a53174 100644 --- a/flow/scripts/variables.json +++ b/flow/scripts/variables.json @@ -51,6 +51,12 @@ "ADDITIONAL_LIBS": { "description": "Hardened macro library files listed here. The library information is immutable and used throughout all stages. Not stored in the .odb file.\n" }, + "ADDITIONAL_MEMORIES": { + "description": "Experimental. Space-separated list of user-supplied `.memories` files (the memories.json JSON schema) merged onto the set AUTO_MEMORIES detects \u2014 to force-convert a memory the idiomatic gate rejects, or to describe one the scanner cannot find. See docs/user/AutoMemories.md.\n", + "stages": [ + "synth" + ] + }, "ADDITIONAL_SITES": { "description": "Passed as -additional_sites to initialize_floorplan.\n", "stages": [ @@ -64,6 +70,10 @@ "All stages" ] }, + "AUTO_MEMORIES": { + "default": 0, + "description": "Experimental. When set to 1, memory-shaped modules in the RTL (firtool/CIRCT `R*/W*/RW*_` port convention, module boundary only) are detected pre-synthesis, inventoried in `$(RESULTS_DIR)/memories.json`, and \u2014 when idiomatic as an SRAM macro \u2014 given generated .lib/.lef views under `$(RESULTS_DIR)/memories/`. Synthesis blackboxes those modules and all later stages read the generated views, so an existing design gets macro-based results without a memory compiler. Supported for the asap7 platform only. See docs/user/AutoMemories.md.\n" + }, "BALANCE_ROWS": { "default": 0, "description": "Balance rows during placement.\n", diff --git a/flow/scripts/variables.yaml b/flow/scripts/variables.yaml index ae24b8359c..7e367f2009 100644 --- a/flow/scripts/variables.yaml +++ b/flow/scripts/variables.yaml @@ -189,6 +189,27 @@ SYNTH_USE_SYN: stages: - synth default: 0 +AUTO_MEMORIES: + description: > + Experimental. When set to 1, memory-shaped modules in the RTL + (firtool/CIRCT `R*/W*/RW*_` port convention, module boundary only) + are detected pre-synthesis, inventoried in + `$(RESULTS_DIR)/memories.json`, and — when idiomatic as an SRAM + macro — given generated .lib/.lef views under + `$(RESULTS_DIR)/memories/`. Synthesis blackboxes those modules and + all later stages read the generated views, so an existing design + gets macro-based results without a memory compiler. Supported for + the asap7 platform only. See docs/user/AutoMemories.md. + default: 0 +ADDITIONAL_MEMORIES: + description: > + Experimental. Space-separated list of user-supplied `.memories` + files (the memories.json JSON schema) merged onto the set + AUTO_MEMORIES detects — to force-convert a memory the idiomatic + gate rejects, or to describe one the scanner cannot find. See + docs/user/AutoMemories.md. + stages: + - synth SYNTH_MEMORY_MAX_BITS: description: > Maximum number of bits for memory synthesis. diff --git a/patches/fakeram/0001-Add-ORFS-ASAP7-backend.patch b/patches/fakeram/0001-Add-ORFS-ASAP7-backend.patch new file mode 100644 index 0000000000..d2ae3cd83a --- /dev/null +++ b/patches/fakeram/0001-Add-ORFS-ASAP7-backend.patch @@ -0,0 +1,169 @@ +diff --git a/BUILD.bazel b/BUILD.bazel +new file mode 100644 +index 0000000..16e9be4 +--- /dev/null ++++ b/BUILD.bazel +@@ -0,0 +1,5 @@ ++filegroup( ++ name = "all_files", ++ srcs = glob(["**/*"]), ++ visibility = ["//visibility:public"], ++) +diff --git a/MODULE.bazel b/MODULE.bazel +new file mode 100644 +index 0000000..f12bf1f +--- /dev/null ++++ b/MODULE.bazel +@@ -0,0 +1,4 @@ ++module( ++ name = "fakeram", ++ version = "2.0.0", ++) +diff --git a/orfs_asap7/__init__.py b/orfs_asap7/__init__.py +new file mode 100644 +index 0000000..edcf578 +--- /dev/null ++++ b/orfs_asap7/__init__.py +@@ -0,0 +1 @@ ++# ORFS ASAP7 package +diff --git a/orfs_asap7/generate.py b/orfs_asap7/generate.py +new file mode 100644 +index 0000000..58fef20 +--- /dev/null ++++ b/orfs_asap7/generate.py +@@ -0,0 +1,83 @@ ++import json ++import sys ++from pathlib import Path ++ ++from utils.class_process import Process ++from utils.memory_config import MemoryConfig ++from utils.memory_factory import MemoryFactory ++from utils.timing_data import TimingData ++from utils.ram_liberty_exporter import RAMLibertyExporter ++from utils.lef_exporter import LefExporter ++ ++ASAP7_PROCESS_CONFIG = { ++ "tech_nm": 7, ++ "voltage": 0.7, ++ "metal_prefix": "M", ++ "metal_layer": "M4", ++ "pin_width_nm": 24, ++ "pin_pitch_nm": 48, ++ "metal_track_pitch_nm": 48, ++ "manufacturing_grid_nm": 1, ++ "contacted_poly_pitch_nm": 54, ++ "fin_pitch_nm": 27, ++ "column_mux_factor": 1, ++ "snap_width_nm": 190, ++ "snap_height_nm": 1400, ++} ++ ++ASAP7_TIMING_CONFIG = { ++ "cycle_time": 1.0, ++ "access_time": 0.5, ++ "setup_time": 0.1, ++ "hold_time": 0.05, ++ "leakage": 0.001, ++} ++ ++def run_orfs_asap7(platform: str, out_dir: Path, json_path: Path): ++ if platform != "asap7": ++ sys.stderr.write(f"FakeRAM2.0 orfs_asap7: unsupported platform {platform}\n") ++ return 1 ++ ++ try: ++ data = json.loads(json_path.read_text()) ++ memories = data.get("memories", []) ++ except Exception as e: ++ sys.stderr.write(f"FakeRAM2.0 orfs_asap7: failed to read {json_path}: {e}\n") ++ return 1 ++ ++ out_dir.mkdir(parents=True, exist_ok=True) ++ converted = sorted((m for m in memories if m.get("idiomatic")), key=lambda m: m["name"]) ++ ++ process = Process(ASAP7_PROCESS_CONFIG) ++ timing_data = TimingData(ASAP7_TIMING_CONFIG) ++ ++ for m in converted: ++ name = m["name"] ++ bits = m.get("bits", 32) ++ rows = m.get("rows", 128) ++ ++ sram_dict = { ++ "name": name, ++ "width": bits, ++ "depth": rows, ++ "banks": 1, ++ } ++ mem_config = MemoryConfig.from_json(sram_dict) ++ ram = MemoryFactory.create(mem_config, "RAM", "SP", process, timing_data) ++ ++ # Export Liberty ++ lib_path = out_dir / f"{name}.lib" ++ with open(lib_path, "w") as f: ++ RAMLibertyExporter(ram).export(f) ++ ++ pre_lib_path = out_dir / f"{name}_pre_layout.lib" ++ with open(pre_lib_path, "w") as f: ++ RAMLibertyExporter(ram).export(f) ++ ++ # Export LEF ++ lef_path = out_dir / f"{name}.lef" ++ with open(lef_path, "w") as f: ++ LefExporter(ram).export(f) ++ ++ (out_dir / "blackboxes.txt").write_text("".join(f"{m['name']}\n" for m in converted)) ++ return 0 +diff --git a/run.py b/run.py +index f525c5f..06ae626 100755 +--- a/run.py ++++ b/run.py +@@ -8,6 +8,7 @@ from utils.class_process import Process + from utils.memory_config import MemoryConfig + from utils.memory_factory import MemoryFactory + from utils.timing_data import TimingData ++from orfs_asap7.generate import run_orfs_asap7 + + + def get_args() -> argparse.Namespace: +@@ -28,10 +29,19 @@ def get_args() -> argparse.Namespace: + required=False, + default="results", + ) ++ parser.add_argument( ++ "--orfs_asap7_backend", ++ action="store_true", ++ help="Use ORFS ASAP7 backend (expects JSON in memories.json format)", ++ ) + return parser.parse_args() + + + def main(args: argparse.Namespace): ++ if args.orfs_asap7_backend: ++ from pathlib import Path ++ return run_orfs_asap7(platform="asap7", out_dir=Path(args.output_dir), json_path=Path(args.config)) ++ + json_data = RunUtils.get_config(args.config) + # Create a process object (shared by all srams) + process = Process(json_data) +@@ -52,4 +62,4 @@ def main(args: argparse.Namespace): + ### Entry point + if __name__ == "__main__": + args = get_args() +- main(args) ++ sys.exit(main(args)) +diff --git a/utils/class_process.py b/utils/class_process.py +index e1cfac3..745285c 100644 +--- a/utils/class_process.py ++++ b/utils/class_process.py +@@ -119,6 +119,9 @@ class Process: + + total_height += additional_height + ++ min_height = max(3.5, self.snap_height_nm / 1000.0 if self.snap_height_nm else 0) ++ total_height = max(total_height, min_height) ++ + return (total_width, total_height) + + def get_tech_nm(self): diff --git a/patches/fakeram/BUILD.bazel b/patches/fakeram/BUILD.bazel new file mode 100644 index 0000000000..89af6bdfcc --- /dev/null +++ b/patches/fakeram/BUILD.bazel @@ -0,0 +1,3 @@ +"""FakeRAM2.0 patches carried for ORFS AUTO_MEMORIES support.""" + +exports_files(glob(["*.patch"]))