siliconize 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- siliconize/__init__.py +18 -0
- siliconize/__main__.py +7 -0
- siliconize/api.py +265 -0
- siliconize/asserts.py +116 -0
- siliconize/board_design.py +88 -0
- siliconize/boards/__init__.py +69 -0
- siliconize/boards/board_sim.py +344 -0
- siliconize/boards/bridge.py +1415 -0
- siliconize/boards/catalog.py +134 -0
- siliconize/boards/mojo_loader.py +81 -0
- siliconize/boards/mojo_v3.py +64 -0
- siliconize/boards/openfpgaloader.py +45 -0
- siliconize/boards/pins.py +355 -0
- siliconize/boards/protocol.py +214 -0
- siliconize/boards/spec.py +138 -0
- siliconize/cli.py +424 -0
- siliconize/cycle.py +1102 -0
- siliconize/device.py +316 -0
- siliconize/doctor.py +212 -0
- siliconize/export.py +198 -0
- siliconize/fit.py +93 -0
- siliconize/fixed.py +409 -0
- siliconize/fixed_lower.py +393 -0
- siliconize/frontend.py +1522 -0
- siliconize/hardware.py +173 -0
- siliconize/hdl/i2c_target_model.v +106 -0
- siliconize/host.py +858 -0
- siliconize/ir.py +565 -0
- siliconize/memory.py +472 -0
- siliconize/ml/__init__.py +127 -0
- siliconize/ml/codegen.py +323 -0
- siliconize/ml/data/iris.csv +151 -0
- siliconize/ml/datasets.py +57 -0
- siliconize/ml/digits.py +29 -0
- siliconize/ml/folded.py +100 -0
- siliconize/ml/graph.py +326 -0
- siliconize/ml/iris.py +28 -0
- siliconize/ml/jax_frontend.py +325 -0
- siliconize/ml/keras_frontend.py +175 -0
- siliconize/ml/onnx_frontend.py +204 -0
- siliconize/ml/quantize.py +374 -0
- siliconize/ml/report.py +65 -0
- siliconize/ml/sklearn_frontend.py +129 -0
- siliconize/ml/tflite_frontend.py +194 -0
- siliconize/ml/torch_frontend.py +320 -0
- siliconize/ml/trees.py +718 -0
- siliconize/np_lower.py +1006 -0
- siliconize/pipeline.py +530 -0
- siliconize/placement.py +312 -0
- siliconize/portability.py +205 -0
- siliconize/procs.py +405 -0
- siliconize/pytest_plugin.py +158 -0
- siliconize/scheduling.py +2225 -0
- siliconize/sequential.py +1561 -0
- siliconize/serve.py +1132 -0
- siliconize/sim.py +332 -0
- siliconize/srcmap.py +238 -0
- siliconize/steps.py +411 -0
- siliconize/stimulus.py +215 -0
- siliconize/stream.py +1026 -0
- siliconize/testbench.py +367 -0
- siliconize/timing.py +327 -0
- siliconize/tools.py +263 -0
- siliconize/types.py +172 -0
- siliconize/vendors/__init__.py +3 -0
- siliconize/vendors/flows.py +720 -0
- siliconize/vendors/ise.py +361 -0
- siliconize/vendors/yosys_netlist.py +299 -0
- siliconize/verilog.py +572 -0
- siliconize-0.1.0.dist-info/METADATA +436 -0
- siliconize-0.1.0.dist-info/RECORD +76 -0
- siliconize-0.1.0.dist-info/WHEEL +5 -0
- siliconize-0.1.0.dist-info/entry_points.txt +5 -0
- siliconize-0.1.0.dist-info/licenses/LICENSE +202 -0
- siliconize-0.1.0.dist-info/licenses/NOTICE +41 -0
- siliconize-0.1.0.dist-info/top_level.txt +1 -0
siliconize/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Hussain Khan and contributors
|
|
3
|
+
"""siliconize: compile Python functions to synthesizable Verilog for FPGAs."""
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
|
|
7
|
+
from .types import Array, ArrayType, Bool, HWType, SInt, UInt # noqa: E402
|
|
8
|
+
from .fixed import Fixed, FixedPoint, FixedType, SFixed, UFixed, saturate, wrap # noqa: E402
|
|
9
|
+
from .scheduling import schedule, share # noqa: E402
|
|
10
|
+
from .stream import Stream # noqa: E402
|
|
11
|
+
from .cycle import In, OpenDrain, Out, clock_hz # noqa: E402
|
|
12
|
+
from .procs import Channel, get, put # noqa: E402 (concurrent processes)
|
|
13
|
+
from .np_lower import NDArray # noqa: E402 (NumPy itself is only imported by programs that use it)
|
|
14
|
+
from .hardware import hardware # noqa: E402 (@siliconize.hardware(board=...))
|
|
15
|
+
from .api import compile # noqa: E402,A004 siliconize.compile(fn, example_args=...)
|
|
16
|
+
|
|
17
|
+
__all__ = ["UInt", "SInt", "Bool", "HWType", "Array", "ArrayType", "SFixed", "UFixed", "Fixed", "FixedType",
|
|
18
|
+
"FixedPoint", "saturate", "wrap", "schedule", "share", "Stream", "In", "Out", "OpenDrain", "clock_hz", "Channel", "put", "get", "NDArray", "compile", "hardware", "__version__"]
|
siliconize/__main__.py
ADDED
siliconize/api.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Hussain Khan and contributors
|
|
3
|
+
"""Python API: ``siliconize.compile(fn)``, including the *prototyping mode* with example inputs.
|
|
4
|
+
|
|
5
|
+
import siliconize
|
|
6
|
+
|
|
7
|
+
def scale(a: int, b: int):
|
|
8
|
+
return a * 3 - b
|
|
9
|
+
|
|
10
|
+
design = siliconize.compile(scale, example_args=[(0, 0), (100, -20), (255, 50)])
|
|
11
|
+
design.write("build/") # scale.v (+ testbench and golden vectors)
|
|
12
|
+
|
|
13
|
+
Annotated functions need nothing else: ``siliconize.compile(fn)`` compiles exactly what
|
|
14
|
+
``python -m siliconize file.py --top fn`` compiles.
|
|
15
|
+
|
|
16
|
+
**Prototyping mode (UNPROVEN).** Parameters annotated ``int`` (or not annotated) normally have
|
|
17
|
+
no hardware width. With ``example_args`` each such parameter gets the smallest width holding
|
|
18
|
+
every example value (plus ``margin`` extra bits), and an ``int``/missing return annotation
|
|
19
|
+
gets the exact width of the computed result. The hardware is still bit-exact with Python for
|
|
20
|
+
every input that fits those ports, but nothing proves that the real inputs will fit them: the
|
|
21
|
+
examples are a guess. So the result carries a warning (``UnprovenWidthWarning``, also in
|
|
22
|
+
``graph.warnings``, so ``--strict`` rejects it) and every generated file starts with an
|
|
23
|
+
``UNPROVEN`` comment. Annotate the parameters (``a: SInt[9]``) for a design you can trust.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import inspect
|
|
29
|
+
import warnings
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
from .types import HWType, type_for_range
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class UnprovenWidthWarning(UserWarning):
|
|
36
|
+
"""Port widths were inferred from example inputs instead of annotations."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def unproven_header(graph) -> str:
|
|
40
|
+
"""Comment lines for the top of every generated file of a design with inferred widths."""
|
|
41
|
+
notes = getattr(graph, "unproven", None)
|
|
42
|
+
if not notes:
|
|
43
|
+
return ""
|
|
44
|
+
lines = ["// UNPROVEN PORT WIDTHS (siliconize prototyping mode): inferred from example or observed inputs, not annotations:"]
|
|
45
|
+
lines += [f"// {n}" for n in notes]
|
|
46
|
+
lines.append("// The design is exact for every input that fits these ports, but nothing guarantees that real")
|
|
47
|
+
lines.append("// inputs fit them. Annotate the parameters (e.g. a: SInt[9]) for a checked design.")
|
|
48
|
+
return "\n".join(lines) + "\n"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def asserted_params(compiler, fdef, annotations: dict) -> set[str]:
|
|
52
|
+
"""Open parameters whose width the range asserts at the top of the body prove (no inference needed)."""
|
|
53
|
+
return {p for p, b in compiler.assert_bounds(fdef, annotations).items()
|
|
54
|
+
if annotations.get(p, int) is int and b[0] is not None and b[1] is not None}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def infer_arg_types(fn, params: list[str], annotations: dict, example_args, margin: int = 0, what: str = "examples",
|
|
58
|
+
skip=()):
|
|
59
|
+
"""{param: HWType} for the ``int``/unannotated parameters, from example calls; and notes.
|
|
60
|
+
`what` names the source of the calls in the notes ("examples", "N observed calls")."""
|
|
61
|
+
if not isinstance(margin, int) or isinstance(margin, bool) or margin < 0:
|
|
62
|
+
raise ValueError(f"margin must be a non-negative number of extra bits, got {margin!r}")
|
|
63
|
+
examples = [tuple(ex) if isinstance(ex, (tuple, list)) else (ex,) for ex in example_args]
|
|
64
|
+
if not examples:
|
|
65
|
+
raise ValueError("example_args needs at least one example call, e.g. [(1, 2), (300, -5)]")
|
|
66
|
+
for ex in examples:
|
|
67
|
+
if len(ex) != len(params):
|
|
68
|
+
raise ValueError(f"example {ex!r} has {len(ex)} argument(s); {fn.__name__} takes {len(params)}")
|
|
69
|
+
overrides, notes = {}, []
|
|
70
|
+
for i, p in enumerate(params):
|
|
71
|
+
ann = annotations.get(p)
|
|
72
|
+
if p in skip or (ann is not None and ann is not int):
|
|
73
|
+
continue
|
|
74
|
+
values = [ex[i] for ex in examples]
|
|
75
|
+
if not all(isinstance(v, int) for v in values):
|
|
76
|
+
bad = next(v for v in values if not isinstance(v, int))
|
|
77
|
+
raise ValueError(f"parameter {p!r}: example value {bad!r} is not a Python int; annotate the parameter "
|
|
78
|
+
"instead (e.g. np.int8 or SInt[8])")
|
|
79
|
+
lo, hi = min(values), max(values)
|
|
80
|
+
base = type_for_range(lo, hi)
|
|
81
|
+
t = HWType(base.width + margin, base.signed)
|
|
82
|
+
overrides[p] = t
|
|
83
|
+
notes.append(f"{p}: {t} ({what} span [{lo}, {hi}]{f', +{margin} bit margin' if margin else ''}; "
|
|
84
|
+
f"representable [{t.min}, {t.max}])")
|
|
85
|
+
for ex in examples: # the examples must run as Python (they are the golden model's first test)
|
|
86
|
+
try:
|
|
87
|
+
fn(*ex)
|
|
88
|
+
except Exception as exc: # noqa: BLE001
|
|
89
|
+
raise ValueError(f"{fn.__name__}{ex!r} raised {type(exc).__name__}: {exc}") from exc
|
|
90
|
+
return overrides, notes
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def apply_examples(compiler, top: str, example_args, margin: int = 0, what: str = "examples") -> list[str]:
|
|
94
|
+
"""Configure `compiler` for prototyping mode; returns the notes describing the inferred ports."""
|
|
95
|
+
fdef = compiler.functions.get(top)
|
|
96
|
+
fn = getattr(compiler.module, top, None)
|
|
97
|
+
if fdef is None or fn is None:
|
|
98
|
+
from .frontend import CompileError
|
|
99
|
+
|
|
100
|
+
raise CompileError(f"function {top!r} not found in {compiler.path}")
|
|
101
|
+
annotations = inspect.get_annotations(fn, eval_str=True)
|
|
102
|
+
params = [a.arg for a in fdef.args.args]
|
|
103
|
+
overrides, notes = infer_arg_types(fn, params, annotations, example_args, margin, what,
|
|
104
|
+
asserted_params(compiler, fdef, annotations))
|
|
105
|
+
compiler.arg_overrides = overrides
|
|
106
|
+
compiler.infer_return = True
|
|
107
|
+
if overrides and annotations.get("return", int) is int:
|
|
108
|
+
notes.append("result: the exact width of the computed values for those inputs")
|
|
109
|
+
return notes
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
DEFAULT_WIDTH = HWType(32, True) # a parameter with no annotation and no observed call: like `int`
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def observe_calls(path, top: str, extra=()) -> list[tuple]:
|
|
116
|
+
"""Run the user's program (`path` as ``__main__``, then each file in `extra`, also as ``__main__``)
|
|
117
|
+
and record the arguments of every call of the function `top` defined in `path`.
|
|
118
|
+
|
|
119
|
+
Only the files the user named are run, with their standard output discarded. A program that
|
|
120
|
+
raises or exits early still yields the calls seen before that; the calls are what is wanted."""
|
|
121
|
+
import contextlib
|
|
122
|
+
import io
|
|
123
|
+
import runpy
|
|
124
|
+
import sys
|
|
125
|
+
|
|
126
|
+
from .hardware import compiling
|
|
127
|
+
|
|
128
|
+
path = Path(path).resolve()
|
|
129
|
+
seen: list[tuple] = []
|
|
130
|
+
known: dict = {} # code-object filename -> is it the program?
|
|
131
|
+
|
|
132
|
+
def tracer(frame, event, _arg):
|
|
133
|
+
if event == "call" and frame.f_code.co_name == top:
|
|
134
|
+
code = frame.f_code
|
|
135
|
+
if known.setdefault(code.co_filename, Path(code.co_filename).resolve() == path):
|
|
136
|
+
seen.append(tuple(frame.f_locals[v] for v in code.co_varnames[:code.co_argcount]))
|
|
137
|
+
|
|
138
|
+
saved_path, previous = list(sys.path), sys.getprofile()
|
|
139
|
+
try:
|
|
140
|
+
for file in (path, *map(Path, extra)):
|
|
141
|
+
sys.path.insert(0, str(Path(file).resolve().parent))
|
|
142
|
+
sys.setprofile(tracer)
|
|
143
|
+
try:
|
|
144
|
+
with contextlib.redirect_stdout(io.StringIO()), compiling(): # never reaches for a board here
|
|
145
|
+
runpy.run_path(str(file), run_name="__main__")
|
|
146
|
+
except (Exception, SystemExit): # noqa: BLE001 - keep what was observed
|
|
147
|
+
pass
|
|
148
|
+
finally:
|
|
149
|
+
sys.setprofile(previous)
|
|
150
|
+
sys.path[:] = saved_path
|
|
151
|
+
finally:
|
|
152
|
+
sys.setprofile(previous)
|
|
153
|
+
return seen
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def infer_from_program(compiler, top: str, margin: int = 0, extra=(), observe: bool = True) -> list[str]:
|
|
157
|
+
"""Widths of the ``int``/unannotated parameters of `top` from the program's own calls, else a default.
|
|
158
|
+
|
|
159
|
+
Annotation > observed calls > default (`DEFAULT_WIDTH`, with a warning). Returns the notes of
|
|
160
|
+
the inferred ports for :func:`mark_unproven` (empty: every parameter was annotated, nothing
|
|
161
|
+
changes). The warnings of the default go to ``compiler.default_warnings``."""
|
|
162
|
+
fdef = compiler.functions.get(top)
|
|
163
|
+
fn = getattr(compiler.module, top, None)
|
|
164
|
+
if fdef is None or fn is None:
|
|
165
|
+
return []
|
|
166
|
+
annotations = inspect.get_annotations(fn, eval_str=True)
|
|
167
|
+
proven = asserted_params(compiler, fdef, annotations)
|
|
168
|
+
open_params = [a.arg for a in fdef.args.args if annotations.get(a.arg, int) is int and a.arg not in proven]
|
|
169
|
+
if not open_params:
|
|
170
|
+
return []
|
|
171
|
+
seen = observe_calls(compiler.path, top, extra) if observe else []
|
|
172
|
+
if seen:
|
|
173
|
+
return apply_examples(compiler, top, seen, margin, f"{len(seen)} observed call(s) span")
|
|
174
|
+
compiler.arg_overrides = {p: DEFAULT_WIDTH for p in open_params}
|
|
175
|
+
compiler.infer_return = True
|
|
176
|
+
compiler.default_warnings = [
|
|
177
|
+
f"parameter {p!r} has no annotation and the program never calls {top}(): using the default "
|
|
178
|
+
f"{DEFAULT_WIDTH}; annotate it (e.g. {p}: SInt[8]) or call {top}() in an `if __name__ == \"__main__\":` "
|
|
179
|
+
"block (or pass --examples FILE) so the width is inferred" for p in open_params]
|
|
180
|
+
return []
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def mark_unproven(graph, notes: list[str]):
|
|
184
|
+
graph.unproven = list(notes)
|
|
185
|
+
graph.warnings.insert(0, "UNPROVEN: port widths were inferred from example inputs (prototyping mode): "
|
|
186
|
+
+ "; ".join(notes) + ". Annotate the parameters for a checked design")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class CompiledFunction:
|
|
190
|
+
"""The result of :func:`compile`: the dataflow graph, Verilog text and the golden model."""
|
|
191
|
+
|
|
192
|
+
def __init__(self, graph, compiler, source: Path):
|
|
193
|
+
self.graph = graph
|
|
194
|
+
self.compiler = compiler
|
|
195
|
+
self.source = source
|
|
196
|
+
self.name = graph.name
|
|
197
|
+
self.fn = getattr(compiler.module, graph.name) # the golden model (the user's function)
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def unproven(self) -> bool:
|
|
201
|
+
return bool(getattr(self.graph, "unproven", None))
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def verilog(self) -> str:
|
|
205
|
+
from .verilog import emit_verilog
|
|
206
|
+
|
|
207
|
+
return unproven_header(self.graph) + emit_verilog(self.graph, f"{self.source.name}:{self.name}")
|
|
208
|
+
|
|
209
|
+
def source_map(self) -> list:
|
|
210
|
+
"""[(Verilog line number, net / register name, ((file, line), ...)), ...] of :attr:`verilog`: the Python
|
|
211
|
+
source of every line of the hardware that has one (siliconize.srcmap.SourceRef)."""
|
|
212
|
+
from . import srcmap
|
|
213
|
+
|
|
214
|
+
return srcmap.mapped(lambda: self.verilog)[1]
|
|
215
|
+
|
|
216
|
+
def write(self, out_dir, vectors: int = 1000, seed: int = 1) -> dict:
|
|
217
|
+
"""Write ``<name>.v``, a self-checking testbench and golden vectors from the Python function."""
|
|
218
|
+
from .testbench import emit_testbench, generate_inputs, golden_outputs, vector_file
|
|
219
|
+
|
|
220
|
+
out = Path(out_dir)
|
|
221
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
222
|
+
files = {"design": out / f"{self.name}.v", "testbench": out / f"tb_{self.name}.v",
|
|
223
|
+
"vectors": out / f"{self.name}_vectors.hex"}
|
|
224
|
+
files["design"].write_text(self.verilog)
|
|
225
|
+
inputs, _ = generate_inputs(self.graph, vectors, seed)
|
|
226
|
+
expected = golden_outputs(self.fn, self.graph, inputs)
|
|
227
|
+
files["vectors"].write_text(vector_file(self.graph, inputs, expected))
|
|
228
|
+
tb = emit_testbench(self.graph, len(inputs), files["vectors"].name, getattr(self.graph, "max_latency", None))
|
|
229
|
+
files["testbench"].write_text(unproven_header(self.graph) + tb)
|
|
230
|
+
return files
|
|
231
|
+
|
|
232
|
+
def simulate(self, out_dir, simulator: str = "auto", vcd: bool = False, vectors: int = 1000, seed: int = 1):
|
|
233
|
+
""":meth:`write` the files, then run the testbench: a :class:`siliconize.tools.ToolResult` (``ok``, ``summary``,
|
|
234
|
+
``output``). ``vcd=True`` also writes ``<name>.vcd`` (``result.vcd``): the waveforms of the whole run, so a
|
|
235
|
+
failing vector is in it."""
|
|
236
|
+
from .tools import simulate
|
|
237
|
+
|
|
238
|
+
files = self.write(out_dir, vectors, seed)
|
|
239
|
+
return simulate(Path(out_dir), files["design"].name, files["testbench"].name, self.graph.module, simulator, vcd)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def compile(fn, example_args=None, margin: int = 0, options: dict | None = None) -> CompiledFunction: # noqa: A001
|
|
243
|
+
"""Compile the Python function `fn` (defined in a source file) to hardware.
|
|
244
|
+
|
|
245
|
+
``example_args``: a list of example argument tuples; turns on the UNPROVEN prototyping mode
|
|
246
|
+
for ``int``/unannotated parameters (see the module docstring). ``margin``: extra bits for
|
|
247
|
+
each inferred port. ``options``: scheduling options, as on the command line.
|
|
248
|
+
"""
|
|
249
|
+
from .frontend import Compiler
|
|
250
|
+
|
|
251
|
+
fn = inspect.unwrap(fn)
|
|
252
|
+
src = inspect.getsourcefile(fn)
|
|
253
|
+
if src is None:
|
|
254
|
+
raise ValueError(f"{fn!r} has no source file; siliconize compiles functions defined in a .py file")
|
|
255
|
+
compiler = Compiler(src)
|
|
256
|
+
notes = (apply_examples(compiler, fn.__name__, example_args, margin) if example_args is not None
|
|
257
|
+
else infer_from_program(compiler, fn.__name__, margin, observe=False))
|
|
258
|
+
graph = compiler.compile(fn.__name__, options)
|
|
259
|
+
graph.warnings[:0] = compiler.default_warnings
|
|
260
|
+
for w in compiler.default_warnings:
|
|
261
|
+
warnings.warn(w, UserWarning, stacklevel=2)
|
|
262
|
+
if notes:
|
|
263
|
+
mark_unproven(graph, notes)
|
|
264
|
+
warnings.warn(graph.warnings[0], UnprovenWidthWarning, stacklevel=2)
|
|
265
|
+
return CompiledFunction(graph, compiler, Path(src))
|
siliconize/asserts.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Hussain Khan and contributors
|
|
3
|
+
"""Parameter ranges from plain Python asserts at the top of a function body.
|
|
4
|
+
|
|
5
|
+
def f(a, b):
|
|
6
|
+
assert 0 <= a < 1000 # a: UInt[10], proven
|
|
7
|
+
assert -50 <= b <= 50 # b: SInt[7], proven
|
|
8
|
+
|
|
9
|
+
Recognised: comparisons of a parameter with an integer constant (a literal, a module-level integer
|
|
10
|
+
constant, or an expression of those: ``2**10 - 1``), chained (``lo <= x < hi``) or joined with ``and``,
|
|
11
|
+
in the unbroken run of ``assert`` statements that starts the body (after a docstring). Several
|
|
12
|
+
asserts on one parameter intersect. Anything else is not recognised and is left to the frontend.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import ast
|
|
18
|
+
import operator
|
|
19
|
+
|
|
20
|
+
_BIN = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.FloorDiv: operator.floordiv,
|
|
21
|
+
ast.Mod: operator.mod, ast.LShift: operator.lshift, ast.RShift: operator.rshift, ast.Pow: operator.pow}
|
|
22
|
+
_FLIPPED = {ast.Lt: ast.Gt, ast.LtE: ast.GtE, ast.Gt: ast.Lt, ast.GtE: ast.LtE, ast.Eq: ast.Eq}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def const_int(e: ast.expr, namespace: dict):
|
|
26
|
+
"""The integer value of a constant expression, or None if `e` is not one."""
|
|
27
|
+
if isinstance(e, ast.Constant):
|
|
28
|
+
return e.value if type(e.value) is int else None
|
|
29
|
+
if isinstance(e, ast.Name):
|
|
30
|
+
v = namespace.get(e.id)
|
|
31
|
+
return v if type(v) is int else None
|
|
32
|
+
if isinstance(e, ast.UnaryOp) and isinstance(e.op, (ast.USub, ast.UAdd)):
|
|
33
|
+
v = const_int(e.operand, namespace)
|
|
34
|
+
return None if v is None else (-v if isinstance(e.op, ast.USub) else v)
|
|
35
|
+
if isinstance(e, ast.BinOp) and type(e.op) in _BIN:
|
|
36
|
+
a, b = const_int(e.left, namespace), const_int(e.right, namespace)
|
|
37
|
+
if a is None or b is None:
|
|
38
|
+
return None
|
|
39
|
+
if isinstance(e.op, (ast.Pow, ast.LShift)) and not 0 <= b <= 4096:
|
|
40
|
+
return None
|
|
41
|
+
if isinstance(e.op, (ast.FloorDiv, ast.Mod)) and b == 0 or isinstance(e.op, ast.RShift) and b < 0:
|
|
42
|
+
return None
|
|
43
|
+
return _BIN[type(e.op)](a, b)
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _compare_facts(cmp: ast.Compare, params, namespace):
|
|
48
|
+
"""[(param, lo, hi)] for one comparison chain, or None if any link is not `param <op> constant`."""
|
|
49
|
+
out = []
|
|
50
|
+
operands = [cmp.left, *cmp.comparators]
|
|
51
|
+
for left, op, right in zip(operands, cmp.ops, operands[1:]):
|
|
52
|
+
lp = left.id if isinstance(left, ast.Name) and left.id in params else None
|
|
53
|
+
rp = right.id if isinstance(right, ast.Name) and right.id in params else None
|
|
54
|
+
if lp and rp is None and (c := const_int(right, namespace)) is not None:
|
|
55
|
+
name, kind = lp, type(op)
|
|
56
|
+
elif rp and lp is None and (c := const_int(left, namespace)) is not None:
|
|
57
|
+
name, kind = rp, _FLIPPED.get(type(op)) # c < p is p > c
|
|
58
|
+
else:
|
|
59
|
+
return None
|
|
60
|
+
if kind is ast.Lt:
|
|
61
|
+
out.append((name, None, c - 1))
|
|
62
|
+
elif kind is ast.LtE:
|
|
63
|
+
out.append((name, None, c))
|
|
64
|
+
elif kind is ast.Gt:
|
|
65
|
+
out.append((name, c + 1, None))
|
|
66
|
+
elif kind is ast.GtE:
|
|
67
|
+
out.append((name, c, None))
|
|
68
|
+
elif kind is ast.Eq:
|
|
69
|
+
out.append((name, c, c))
|
|
70
|
+
else:
|
|
71
|
+
return None
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _facts(test: ast.expr, params, namespace):
|
|
76
|
+
if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And):
|
|
77
|
+
parts = [_facts(v, params, namespace) for v in test.values]
|
|
78
|
+
return None if any(p is None for p in parts) else [f for p in parts for f in p]
|
|
79
|
+
if isinstance(test, ast.Compare):
|
|
80
|
+
return _compare_facts(test, params, namespace)
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def leading_asserts(fdef: ast.FunctionDef) -> list[ast.Assert]:
|
|
85
|
+
body = fdef.body
|
|
86
|
+
i = 1 if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) else 0
|
|
87
|
+
run = []
|
|
88
|
+
while i < len(body) and isinstance(body[i], ast.Assert):
|
|
89
|
+
run.append(body[i])
|
|
90
|
+
i += 1
|
|
91
|
+
return run
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def parameter_bounds(fdef: ast.FunctionDef, params, namespace: dict, error):
|
|
95
|
+
"""({param: [lo|None, hi|None, [assert statements]]}, [recognised assert statements]).
|
|
96
|
+
|
|
97
|
+
`params`: the parameter names an assert may bound. `error(message, node)` builds the exception
|
|
98
|
+
raised for contradictory asserts."""
|
|
99
|
+
bounds: dict = {}
|
|
100
|
+
used = []
|
|
101
|
+
for stmt in leading_asserts(fdef):
|
|
102
|
+
facts = _facts(stmt.test, params, namespace)
|
|
103
|
+
if facts is None:
|
|
104
|
+
continue
|
|
105
|
+
used.append(stmt)
|
|
106
|
+
for name, lo, hi in facts:
|
|
107
|
+
b = bounds.setdefault(name, [None, None, []])
|
|
108
|
+
if lo is not None:
|
|
109
|
+
b[0] = lo if b[0] is None else max(b[0], lo)
|
|
110
|
+
if hi is not None:
|
|
111
|
+
b[1] = hi if b[1] is None else min(b[1], hi)
|
|
112
|
+
if stmt not in b[2]:
|
|
113
|
+
b[2].append(stmt)
|
|
114
|
+
if b[0] is not None and b[1] is not None and b[0] > b[1]:
|
|
115
|
+
raise error(f"the asserts on parameter {name!r} allow no value (lower bound {b[0]} > upper bound {b[1]})", stmt)
|
|
116
|
+
return bounds, used
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Hussain Khan and contributors
|
|
3
|
+
"""The design `siliconize SOURCE --board B` builds, as one function, so that everything that must agree with the
|
|
4
|
+
bitstream (the CLI, `siliconize.host --port sim`, the Device `fpga` target) builds the same Verilog: the same
|
|
5
|
+
compile options (the board's defaults, observed example calls), the same pipelining, hence the same design hash.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import boards, timing
|
|
13
|
+
from .frontend import compile_file
|
|
14
|
+
from .scheduling import DEVICES, is_multicycle
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def board_defaults(board_name: str) -> dict:
|
|
18
|
+
"""What a design built for a board gets unless the user says otherwise (no hand tuning): the board's clock as
|
|
19
|
+
the timing target, its family's delay model, and its device's DSP blocks as the multiplier budget."""
|
|
20
|
+
b = boards.get(board_name)
|
|
21
|
+
out = {"clock": b.clock_hz / 1e6, "family": delay_family(board_name)}
|
|
22
|
+
part = b.part.split("-")[0].lower() # (a part number goes on after the device: xc7a35t + icsg324)
|
|
23
|
+
device = next((d for d in DEVICES if part.startswith(d)), None)
|
|
24
|
+
if device:
|
|
25
|
+
out["fit"] = device
|
|
26
|
+
return out
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# Board catalog family -> delay model (siliconize.timing.FAMILIES), where the names differ.
|
|
30
|
+
_DELAY_MODELS = {"artix7": "xilinx7"}
|
|
31
|
+
FALLBACK_FAMILY = "spartan6" # the delays used for a family that has no model of its own
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def delay_family(board_name: str | None) -> str:
|
|
35
|
+
"""The delay model everything that schedules or reports timing for a board uses (the scheduler, the
|
|
36
|
+
pipeliner, the Verilog header, the estimates): the board family's own, else the fallback's delays, which
|
|
37
|
+
:func:`delay_model_label` then says. Without a board: the fallback."""
|
|
38
|
+
family = boards.get(board_name).family if board_name else None
|
|
39
|
+
family = _DELAY_MODELS.get(family, family)
|
|
40
|
+
return family if family in timing.FAMILIES else FALLBACK_FAMILY
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def delay_model_label(board_name: str | None) -> str:
|
|
44
|
+
"""How an estimate made with :func:`delay_family` is described: the model, and whether it was calibrated
|
|
45
|
+
against the vendor's timing report."""
|
|
46
|
+
fam = delay_family(board_name)
|
|
47
|
+
family = boards.get(board_name).family if board_name else fam
|
|
48
|
+
if _DELAY_MODELS.get(family, family) not in timing.FAMILIES:
|
|
49
|
+
return f"estimate (no calibrated model for {family}; {fam} delays)"
|
|
50
|
+
return f"{fam} model" if timing.FAMILIES[fam].calibrated else f"{fam} model, not calibrated"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def design_verilog(graph, compiler, source_name: str, clock_mhz: float | None = None, board_name: str | None = None):
|
|
54
|
+
"""(Verilog text, pipeline plan or None, clock in MHz or None) of a compiled design, as the CLI writes it.
|
|
55
|
+
|
|
56
|
+
`clock_mhz` is the explicit --clock; otherwise a function's own ``@schedule(clock=)``, else the board's.
|
|
57
|
+
Multi-cycle designs were scheduled for the clock by the compiler; single-cycle datapaths are pipelined here.
|
|
58
|
+
Stream designs come out of siliconize.stream, cycle-level designs are not handled (they have no dataflow graph)."""
|
|
59
|
+
from .api import unproven_header
|
|
60
|
+
from .pipeline import pipeline
|
|
61
|
+
from .verilog import emit_verilog
|
|
62
|
+
|
|
63
|
+
top = graph.name
|
|
64
|
+
fam = delay_family(board_name)
|
|
65
|
+
label = f"{source_name}:{top}"
|
|
66
|
+
if getattr(graph, "is_stream", False):
|
|
67
|
+
from .stream import emit_stream
|
|
68
|
+
|
|
69
|
+
graph.family = fam
|
|
70
|
+
verilog, plan = emit_stream(graph, label, clock_mhz or getattr(graph, "clock", None), fam)
|
|
71
|
+
return verilog, plan, clock_mhz or getattr(graph, "clock", None)
|
|
72
|
+
if clock_mhz is None:
|
|
73
|
+
own = getattr(getattr(compiler.module, top, None), "__siliconize_options__", {}).get("clock")
|
|
74
|
+
clock_mhz = own or (board_defaults(board_name).get("clock") if board_name else None)
|
|
75
|
+
plan = None
|
|
76
|
+
if clock_mhz is not None and not is_multicycle(graph):
|
|
77
|
+
plan = pipeline(graph, clock_mhz, fam, label)
|
|
78
|
+
return unproven_header(graph) + (plan.verilog() if plan else emit_verilog(graph, label)), plan, clock_mhz
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def compile_board_design(source: str | Path, top: str | None, board_name: str):
|
|
82
|
+
"""(graph, compiler, Verilog text) of `source` exactly as `siliconize SOURCE --top TOP --board B` builds it."""
|
|
83
|
+
source = Path(source)
|
|
84
|
+
graph, compiler = compile_file(source, top, {}, observe=True, option_defaults=board_defaults(board_name))
|
|
85
|
+
if getattr(graph, "is_cycle", False):
|
|
86
|
+
return graph, compiler, None
|
|
87
|
+
verilog, _, _ = design_verilog(graph, compiler, source.name, None, board_name)
|
|
88
|
+
return graph, compiler, verilog
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Hussain Khan and contributors
|
|
3
|
+
"""Board registry: ``siliconize.boards.get("icebreaker")``, ``siliconize.boards.names()``.
|
|
4
|
+
|
|
5
|
+
Boards are data (:class:`siliconize.boards.spec.Board`); see docs/BOARDS.md for how to add one.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from .spec import Board, Port # noqa: F401
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _registry() -> dict[str, Board]:
|
|
14
|
+
from . import catalog, mojo_v3
|
|
15
|
+
|
|
16
|
+
return {b.name: b for b in [mojo_v3.BOARD, *catalog.BOARDS]}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def names() -> list[str]:
|
|
20
|
+
return list(_registry())
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def get(name: str | Board) -> Board:
|
|
24
|
+
if isinstance(name, Board):
|
|
25
|
+
return name
|
|
26
|
+
reg = _registry()
|
|
27
|
+
if name not in reg:
|
|
28
|
+
raise ValueError(f"unknown board {name!r}; known boards: {', '.join(reg)}")
|
|
29
|
+
return reg[name]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def describe(b: Board) -> str:
|
|
33
|
+
from ..vendors import flows
|
|
34
|
+
|
|
35
|
+
tcs = ", ".join(f"{t}{'' if t in flows.TESTED else ' (untested)'}" for t in b.toolchains)
|
|
36
|
+
hw = "run on real hardware" if b.hardware_tested else "not run on real hardware yet"
|
|
37
|
+
return f"{b.name:<12} {b.title} - {b.part}, {b.clock_hz / 1e6:g} MHz, {b.baud} baud via {b.bridge}; " \
|
|
38
|
+
f"flows: {tcs}; {hw}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def load_bitstream(board: str | Board, bitstream, port: str | None = None, flash: bool = False, progress=None) -> None:
|
|
42
|
+
"""Load a bitstream into the board's FPGA with the board's loader: the Mojo's own (serial `port`) or
|
|
43
|
+
openFPGALoader. Volatile (RAM/SRAM) unless `flash`."""
|
|
44
|
+
b = get(board)
|
|
45
|
+
if b.loader == "mojo":
|
|
46
|
+
from . import mojo_loader
|
|
47
|
+
|
|
48
|
+
mojo_loader.load(bitstream, port, flash=flash, progress=progress)
|
|
49
|
+
return
|
|
50
|
+
if b.loader and b.loader.startswith("openfpgaloader:"):
|
|
51
|
+
from . import openfpgaloader
|
|
52
|
+
|
|
53
|
+
openfpgaloader.load(b.loader.split(":", 1)[1], bitstream, flash=flash)
|
|
54
|
+
return
|
|
55
|
+
raise NotImplementedError(
|
|
56
|
+
f"siliconize has no loader for the {b.title}; load the bitstream with the vendor's programmer or "
|
|
57
|
+
"openFPGALoader / iceprog / ecpprog first, then run without a bitstream (the board's design identity is "
|
|
58
|
+
"still checked)")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def find_ports(board: str | Board) -> list[str]:
|
|
62
|
+
"""Serial ports whose USB (vendor, product) id is one of the board's ``usb_ids``, sorted by name.
|
|
63
|
+
|
|
64
|
+
Needs pyserial (``ImportError`` without it). Only those ports are listed, never the others on the machine; a
|
|
65
|
+
board whose ids are unknown (``usb_ids == ()``) has none, so its port must be given explicitly."""
|
|
66
|
+
from serial.tools import list_ports
|
|
67
|
+
|
|
68
|
+
ids = set(get(board).usb_ids)
|
|
69
|
+
return sorted(p.device for p in list_ports.comports() if (p.vid, p.pid) in ids)
|