xactflow-rtl-gen 0.3.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.
@@ -0,0 +1,116 @@
1
+ __version__ = "0.3.0"
2
+
3
+ from pathlib import Path
4
+ from typing import List, Sequence, Union
5
+
6
+ import ipxact
7
+ from xactflow import Exporter, Library, LinkedDesign, link
8
+
9
+ from .top_writer import GENERATED_MARKER, file_list, generate_files, generate_top
10
+
11
+ __all__ = ["RtlExporter", "__version__", "file_list", "generate_files", "generate_top"]
12
+
13
+
14
+ def _names(value: Union[str, Sequence[str]]) -> List[str]:
15
+ """A list from Python, or the comma-separated form the CLI's --option passes."""
16
+ items = value.split(",") if isinstance(value, str) else value
17
+ return [item.strip() for item in items if item.strip()]
18
+
19
+
20
+ class RtlExporter(Exporter):
21
+ """Write the SystemVerilog of a design into output_dir: <module>.sv, plus an address map package
22
+ if the design records address windows, and the modules of any hierarchical instances.
23
+
24
+ Exports the ipxact.Design that is a target of the library: the file given to `xactflow rtl-gen`,
25
+ or the design an importer added. It is linked here against that library, which has to hold the
26
+ components and bus definitions the design refers to (the CLI's --lib). A design configuration
27
+ that is a target as well configures it (the CLI's --config). From Python, a LinkedDesign is
28
+ accepted in place of the library, for a design linked another way.
29
+
30
+ Options:
31
+ common: input port names to share across instances, as one top-level port each (clocks,
32
+ resets). A comma-separated string or a list.
33
+ top: the VLNV of the hierarchical component to take the module's name and ports from.
34
+ Needed only when more than one component holds the design.
35
+ unconnected: what to do with a port the design connects to nothing, in a module whose ports a
36
+ component defines: an instance's input, or an output of the module. `refuse`, the
37
+ default, or `open`, which leaves it as the design has it.
38
+ filelist: the name of a file to write next to the modules, listing what was generated in an
39
+ order that compiles, for a compiler's -F.
40
+ socgen_package: the name of one more package to write, such as `soc_addr_map_pkg`: the address
41
+ windows of every module generated, in PeakRDL-socgen's layout, for files written
42
+ against that tool's package.
43
+ socgen_names: what socgen calls the decoders and targets in that package, as `instance:name`
44
+ pairs, comma-separated, or a dict. An instance not given goes by its own name.
45
+ """
46
+
47
+ name = "rtl-gen"
48
+
49
+ def export(self, library: Union[Library, LinkedDesign], output_dir: Path, **options: object) -> None:
50
+ common = _names(options.pop("common", ()))
51
+ if "lib" in options:
52
+ raise TypeError(
53
+ "xactflow-rtl-gen: the lib option is gone. Since XactFlow 0.4 the library comes with the "
54
+ "export: give its folders to the command with --lib, or add the documents to the Library"
55
+ )
56
+ top = options.pop("top", None)
57
+ unconnected = options.pop("unconnected", "refuse")
58
+ filelist = options.pop("filelist", None)
59
+ socgen_package = options.pop("socgen_package", None)
60
+ socgen_names = options.pop("socgen_names", None)
61
+ if options:
62
+ raise TypeError(f"xactflow-rtl-gen got unknown options: {', '.join(sorted(options))}")
63
+ if filelist is not None and (
64
+ not isinstance(filelist, str) or not filelist.strip() or Path(filelist).name != filelist or filelist in (".", "..")
65
+ ):
66
+ raise TypeError(f"xactflow-rtl-gen: the filelist option is a file name in the output folder, got {filelist!r}")
67
+
68
+ files = generate_files(self._linked(library), common, top, unconnected, socgen_package, socgen_names)
69
+ if filelist is not None:
70
+ if filelist in files:
71
+ raise ValueError(f"the file list cannot be called {filelist}: a generated module has that file")
72
+ files[filelist] = file_list(files)
73
+
74
+ output_dir = Path(output_dir)
75
+ for name in files: # before writing anything, so a refusal leaves no partial output
76
+ _check_overwrite(output_dir / name)
77
+ output_dir.mkdir(parents=True, exist_ok=True)
78
+ for name, text in files.items():
79
+ (output_dir / name).write_text(text, encoding="utf-8")
80
+
81
+ @staticmethod
82
+ def _linked(library: Union[Library, LinkedDesign]) -> LinkedDesign:
83
+ """The one design to export, linked against the library it came in (D44)."""
84
+ if isinstance(library, LinkedDesign):
85
+ return library
86
+ if not isinstance(library, Library):
87
+ raise TypeError(
88
+ f"xactflow-rtl-gen exports the design that is a target of a Library, or a LinkedDesign, "
89
+ f"got {type(library).__name__}"
90
+ )
91
+ designs = list(library.targets(ipxact.Design))
92
+ if not designs:
93
+ raise TypeError("xactflow-rtl-gen needs an ipxact.Design target in the library")
94
+ if len(designs) > 1:
95
+ names = ", ".join(str(design.vlnv) for design in designs)
96
+ raise ValueError(f"xactflow-rtl-gen exports one design at a time, and the library has {len(designs)} as targets: {names}")
97
+ configurations = list(library.targets(ipxact.DesignConfiguration))
98
+ if len(configurations) > 1:
99
+ names = ", ".join(str(configuration.vlnv) for configuration in configurations)
100
+ raise ValueError(f"xactflow-rtl-gen takes one design configuration, and the library has {len(configurations)} as targets: {names}")
101
+ return link(designs[0], library, configurations[0] if configurations else None)
102
+
103
+
104
+ _FORMER_MARKER = "// Generated by xactflow-rtl " # its header under its former name, so that output can be regenerated (D30)
105
+
106
+
107
+ def _check_overwrite(path: Path) -> None:
108
+ """Regenerating our own output is fine. Never replace a file a person may have written."""
109
+ if not path.exists():
110
+ return
111
+ if path.is_dir():
112
+ raise FileExistsError(f"{path} already exists and is a folder")
113
+ with path.open(encoding="utf-8", errors="replace") as file:
114
+ first_line = file.readline()
115
+ if not first_line.startswith((GENERATED_MARKER, _FORMER_MARKER)):
116
+ raise FileExistsError(f"{path} already exists and was not generated by xactflow-rtl-gen")
@@ -0,0 +1,391 @@
1
+ """The address map of a design, as a SystemVerilog package with one rule table per decoder.
2
+
3
+ The rule shape, an index with a start address and an exclusive end address, is the one PULP's
4
+ crossbars and common_cells' addr_decode take, so a table can be handed to them directly.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections import Counter
11
+ from dataclasses import dataclass, field
12
+ from typing import Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Union
13
+
14
+ import ipxact
15
+ from xactflow import ExpressionError, LinkedDesign, evaluate, parameter_resolver
16
+
17
+ from .keywords import SYSTEMVERILOG_KEYWORDS
18
+
19
+ _ATTRIBUTE = re.compile(r"""(baseAddr|size)=["']([^"']+)["']""")
20
+ _DEFAULT_WIDTH = 32
21
+ _OUTBOUND = (ipxact.InterfaceMode.INITIATOR, ipxact.InterfaceMode.MIRRORED_TARGET) # what a decoder sends through
22
+ _INBOUND = (ipxact.InterfaceMode.TARGET, ipxact.InterfaceMode.MIRRORED_INITIATOR) # what brings it addresses
23
+ _IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_$]*")
24
+
25
+
26
+ def for_view(items: Iterable, view: Optional[ipxact.View]) -> List:
27
+ """What applies to a view: an item with no viewRef applies to all of them."""
28
+ if view is None:
29
+ return list(items)
30
+ return [item for item in items if not item.view_refs or view.name in {getattr(ref, "value", ref) for ref in item.view_refs}]
31
+
32
+
33
+ def address_window(interface: object) -> Optional[Dict[str, str]]:
34
+ """The <xactflow:addressMapping> attributes on an active interface, as written, if any."""
35
+ for extension in getattr(interface, "vendor_extensions", []):
36
+ if "addressMapping" in str(extension):
37
+ return dict(_ATTRIBUTE.findall(str(extension)))
38
+ return None
39
+
40
+
41
+ @dataclass
42
+ class Rule:
43
+ decoder: str # the instance that decodes the address
44
+ index: int # which of its initiator interfaces the window is reached through
45
+ interface: str # that interface's name
46
+ target: str # "<instance>.<bus interface>" of the target
47
+ base: int
48
+ size: int
49
+ width: Optional[int] = None # of this window's own bus, when its abstraction says
50
+ name: str = "" # what its constants are called
51
+ from_outside: bool = False # reached through the module's own interface, not decoded by an instance
52
+
53
+ @property
54
+ def end(self) -> int:
55
+ return self.base + self.size
56
+
57
+
58
+ @dataclass
59
+ class AddressMap:
60
+ module: str
61
+ package: str
62
+ width: int
63
+ tables: Dict[str, List[Rule]]
64
+ hosts: Dict[str, int] = field(default_factory=dict) # how many of each decoder's interfaces that take addresses in are connected
65
+
66
+ def constant(self, decoder: str, what: str) -> str:
67
+ return f"{_constant_name(decoder)}_{what}"
68
+
69
+
70
+ def _constant_name(*parts: str) -> str:
71
+ return "_".join(re.sub(r"\W", "_", part).upper() for part in parts)
72
+
73
+
74
+ def _abstraction_width(linked: LinkedDesign, bus_interface: ipxact.BusInterface, view: Optional[ipxact.View]) -> Optional[int]:
75
+ """The width of the logical port the abstraction of this view marks as the address, when it says."""
76
+ for abstraction_type in for_view(bus_interface.abstraction_types, view):
77
+ definition = linked.library.get_abstraction_definition(abstraction_type.abstraction_ref.vlnv)
78
+ for port in definition.ports if definition is not None else []:
79
+ wire = port.wire
80
+ if wire is None or wire.qualifier is None or not wire.qualifier.is_address:
81
+ continue
82
+ for mode in (wire.on_initiator, wire.on_target):
83
+ if mode is not None and mode.width is not None:
84
+ try:
85
+ return int(evaluate(str(mode.width), parameter_resolver(definition.parameters)))
86
+ except ExpressionError:
87
+ return None
88
+ return None
89
+
90
+
91
+ def _index_of(interface: ipxact.BusInterface, component: ipxact.Component) -> int:
92
+ """Which of a decoder's interfaces this is, counted in the order the component declares them,
93
+ among the ones that send addresses out. They need not all have the same mode."""
94
+ modes = _OUTBOUND if interface.mode in _OUTBOUND else (interface.mode,)
95
+ return [b.name for b in component.bus_interfaces if b.mode in modes].index(interface.name)
96
+
97
+
98
+ def _rule(linked: LinkedDesign, module: str, top_component: Optional[ipxact.Component], view_of: Callable, connection, endpoint) -> Rule:
99
+ where = f"interconnection {connection.name!r}"
100
+ this_end = f"{endpoint.instance.instance_name}.{endpoint.bus_interface.name}"
101
+ window = address_window(endpoint.source)
102
+ if "baseAddr" not in window or "size" not in window:
103
+ raise ValueError(f"{where}: the address window of {this_end} needs both baseAddr and size")
104
+ try:
105
+ base, size = int(window["baseAddr"], 0), int(window["size"], 0)
106
+ except ValueError as exc:
107
+ raise ValueError(f"{where}: the address window of {this_end} is not a number: {exc}") from exc
108
+ if size < 1 or base < 0:
109
+ raise ValueError(f"{where}: the address window of {this_end} has base {base} and size {size}")
110
+
111
+ width = _abstraction_width(linked, endpoint.bus_interface, view_of(endpoint.instance.instance_name))
112
+ others = [e for e in connection.endpoints if e is not endpoint]
113
+ outbound = [e for e in others if e.bus_interface.mode in _OUTBOUND]
114
+ hier = [h.bus_ref for h in connection.source.hier_interfaces]
115
+ if outbound: # at most one: link() checks that an interface of these modes only connects to targets
116
+ decoder, target = outbound[0], this_end
117
+ elif endpoint.bus_interface.mode in _OUTBOUND and (others or hier):
118
+ # The window is on the decoder's own side, and the target is the other end.
119
+ ends = [*(f"{e.instance.instance_name}.{e.bus_interface.name}" for e in others), *(f"{module}.{name}" for name in hier)]
120
+ if len(ends) > 1:
121
+ raise ValueError(f"{where}: cannot tell which of {', '.join(ends)} the address window on {this_end} belongs to")
122
+ decoder, target = endpoint, ends[0]
123
+ elif not others:
124
+ # Reached from outside this module, through one of its own interfaces.
125
+ declared = [b.name for b in top_component.bus_interfaces] if top_component is not None else []
126
+ index = declared.index(hier[0]) if hier and hier[0] in declared else 0
127
+ return Rule(module, index, connection.name, this_end, base, size, width, from_outside=True)
128
+ elif len(others) == 1:
129
+ decoder, target = others[0], this_end
130
+ else:
131
+ names = ", ".join(f"{e.instance.instance_name}.{e.bus_interface.name}" for e in others)
132
+ raise ValueError(f"{where}: cannot tell which of {names} decodes the address window of {this_end}")
133
+ index = _index_of(decoder.bus_interface, decoder.instance.component)
134
+ return Rule(decoder.instance.instance_name, index, decoder.bus_interface.name, target, base, size, width)
135
+
136
+
137
+ def _name_constants(tables: Dict[str, List[Rule]]) -> None:
138
+ """Name each window's constants, refusing names that come out the same: they are upper case, and
139
+ SystemVerilog names may differ only in case."""
140
+ owners: Dict[str, str] = {}
141
+
142
+ def claim(name: str, owner: str) -> None:
143
+ if owners.setdefault(name, owner) != owner:
144
+ raise ValueError(f"{owners[name]} and {owner} would both define the constant {name} in the address map package")
145
+
146
+ for decoder, rules in tables.items():
147
+ for what in ("NUM_RULES", "ADDR_RULES", "ADDR_PAIRS"):
148
+ claim(f"{_constant_name(decoder)}_{what}", decoder)
149
+ behind = Counter(rule.interface for rule in rules)
150
+ for rule in rules:
151
+ parts = (decoder, rule.interface) if behind[rule.interface] == 1 else (decoder, rule.interface, rule.target)
152
+ rule.name = _constant_name(*parts)
153
+ claim(rule.name, f"{decoder}.{rule.interface}" if behind[rule.interface] == 1 else f"{decoder}.{rule.interface} to {rule.target}")
154
+
155
+
156
+ def build_address_map(
157
+ linked: LinkedDesign, module: str, top_component: Optional[ipxact.Component] = None, view_of: Callable = lambda name: None
158
+ ) -> Optional[AddressMap]:
159
+ """The design's address map, or None when it records no address window. `view_of` gives an instance's view."""
160
+ tables: Dict[str, List[Rule]] = {}
161
+ for connection in linked.interconnections:
162
+ for endpoint in connection.endpoints:
163
+ if address_window(endpoint.source) is None:
164
+ continue
165
+ rule = _rule(linked, module, top_component, view_of, connection, endpoint)
166
+ table = tables.setdefault(rule.decoder, [])
167
+ if table and table[0].from_outside != rule.from_outside:
168
+ raise ValueError(f"instance {module!r} has the name of its module, and the address map cannot tell their windows apart")
169
+ table.append(rule)
170
+ if not tables:
171
+ return None
172
+
173
+ rules_of_all = [rule for rules in tables.values() for rule in rules]
174
+ widths = {rule.width for rule in rules_of_all if rule.width is not None}
175
+ unsaid = [rule for rule in rules_of_all if rule.width is None] # a window whose bus doesn't say how wide it is
176
+ if unsaid:
177
+ widths.add(64 if max(rule.end for rule in unsaid) > 1 << _DEFAULT_WIDTH else _DEFAULT_WIDTH)
178
+ width = max(widths)
179
+
180
+ for decoder, rules in tables.items():
181
+ rules.sort(key=lambda rule: (rule.index, rule.base))
182
+ by_address = sorted(rules, key=lambda rule: rule.base)
183
+ for rule in by_address:
184
+ limit = rule.width if rule.width is not None else width
185
+ if rule.end > 1 << limit:
186
+ raise ValueError(
187
+ f"the address window of {rule.target} ends at {rule.end:#x}, past the {limit}-bit address space"
188
+ )
189
+ for lower, upper in zip(by_address, by_address[1:]):
190
+ if lower.end > upper.base:
191
+ raise ValueError(
192
+ f"the address windows of {lower.target} and {upper.target} overlap: "
193
+ f"{lower.base:#x}-{lower.end:#x} and {upper.base:#x}-{upper.end:#x}, both decoded by {decoder}"
194
+ )
195
+ _name_constants(tables)
196
+ hosts = {decoder: 0 for decoder in tables}
197
+ taken = {
198
+ (endpoint.instance.instance_name, endpoint.bus_interface.name)
199
+ for connection in linked.interconnections
200
+ for endpoint in connection.endpoints
201
+ if endpoint.bus_interface.mode in _INBOUND
202
+ }
203
+ for instance, _ in taken:
204
+ if instance in hosts:
205
+ hosts[instance] += 1
206
+ return AddressMap(module, f"{module}_addr_map_pkg", width, tables, hosts)
207
+
208
+
209
+ def render_address_map(address_map: AddressMap, header: str) -> str:
210
+ width = address_map.width
211
+ digits = (width + 3) // 4
212
+
213
+ def literal(value: int) -> str:
214
+ # A window that reaches the very top ends at 2**width, which wraps to 0 here. Decoders that
215
+ # take this rule shape read an end of 0 as the end of the address space. On a narrower bus in
216
+ # a wider table, the true end is kept: 0 would claim all the addresses above it as well.
217
+ return f"{width}'h{value & ((1 << width) - 1):0{digits}x}"
218
+
219
+ lines = [
220
+ header,
221
+ "",
222
+ f"package {address_map.package};",
223
+ "",
224
+ " typedef struct packed {",
225
+ " int unsigned idx; // which initiator interface of the decoder the window is behind",
226
+ f" logic [{width - 1}:0] start_addr;",
227
+ f" logic [{width - 1}:0] end_addr; // exclusive, and 0 means the end of the address space",
228
+ " } addr_rule_t;",
229
+ "",
230
+ ]
231
+ for decoder, rules in address_map.tables.items():
232
+ if decoder == address_map.module:
233
+ lines.append(f" // Reached from outside {decoder}, through its own interfaces")
234
+ else:
235
+ lines.append(f" // Decoded by {decoder}")
236
+ for rule in rules:
237
+ name = rule.name
238
+ lines.append(f" // {decoder}.{rule.interface} reaches {rule.target}")
239
+ lines.append(f" localparam logic [{width - 1}:0] {name}_BASE = {literal(rule.base)};")
240
+ lines.append(f" localparam logic [{width - 1}:0] {name}_END = {literal(rule.end)};")
241
+ if rule.size >> width: # the whole address space, one bit more than an address has
242
+ lines.append(f" localparam logic [{width}:0] {name}_SIZE = {width + 1}'h{rule.size:x};")
243
+ else:
244
+ lines.append(f" localparam logic [{width - 1}:0] {name}_SIZE = {literal(rule.size)};")
245
+ count = address_map.constant(decoder, "NUM_RULES")
246
+ table = address_map.constant(decoder, "ADDR_RULES")
247
+ lines.append(f" localparam int unsigned {count} = {len(rules)};")
248
+ # A concatenation of {idx, start_addr, end_addr}, the highest rule first: Icarus Verilog does
249
+ # not read an assignment pattern on a packed array. The cast keeps slang from warning that
250
+ # the bits are converted implicitly.
251
+ table_type = f"{table}_t"
252
+ lines.append(f" typedef addr_rule_t [{count}-1:0] {table_type};")
253
+ lines.append(f" localparam {table_type} {table} = {table_type}'({{")
254
+ entries = [f" {{32'd{rule.index}, {literal(rule.base)}, {literal(rule.end)}}}" for rule in reversed(rules)]
255
+ lines.append(",\n".join(entries))
256
+ lines.append(" });")
257
+ # The same windows as a flat vector, for a decoder that takes them that way.
258
+ pairs = ", ".join(f"{literal(rule.base)}, {literal(rule.end)}" for rule in rules)
259
+ lines.append(" // Start and end of each window, rule 0 in the most significant bits")
260
+ lines.append(f" localparam logic [{2 * width * len(rules) - 1}:0] {address_map.constant(decoder, 'ADDR_PAIRS')} = {{{pairs}}};")
261
+ lines.append("")
262
+ lines.append("endpackage")
263
+ return "\n".join(lines) + "\n"
264
+
265
+
266
+ # PeakRDL-socgen's layout of an address map package, for files written against its package: what its
267
+ # output looks like, not its code (a GPL-3 template). An interconnect's constants start with its name, with
268
+ # "interconnect" shortened to "intc", and a window's with the name of what it reaches, then the interconnect's.
269
+ SOCGEN_WIDTH = 32
270
+
271
+
272
+ def socgen_names(value: Union[str, Mapping[str, str], Sequence[str], None]) -> Dict[str, str]:
273
+ """The socgen_names option: what socgen calls an instance, as `instance:name` pairs, comma-separated
274
+ from the CLI, or a dict or list of pairs from Python."""
275
+ if value is None:
276
+ return {}
277
+ if isinstance(value, Mapping):
278
+ pairs = list(value.items())
279
+ else:
280
+ items = value.split(",") if isinstance(value, str) else list(value)
281
+ pairs = []
282
+ for item in (item.strip() for item in items):
283
+ if not item:
284
+ continue
285
+ if item.count(":") != 1:
286
+ raise TypeError(f"xactflow-rtl-gen: socgen_names takes instance:name pairs, got {item!r}")
287
+ instance, name = (part.strip() for part in item.split(":"))
288
+ pairs.append((instance, name))
289
+ names: Dict[str, str] = {}
290
+ for instance, name in pairs:
291
+ for what, text in (("instance", instance), ("name", name)):
292
+ if not isinstance(text, str) or not _IDENTIFIER.fullmatch(text):
293
+ raise TypeError(f"xactflow-rtl-gen: socgen_names: {what} {text!r} is not an identifier")
294
+ if names.setdefault(instance, name) != name:
295
+ raise TypeError(f"xactflow-rtl-gen: socgen_names gives {instance} two names, {names[instance]} and {name}")
296
+ return names
297
+
298
+
299
+ def render_socgen_package(address_maps: Sequence[AddressMap], package: str, names: Mapping[str, str], header: str) -> str:
300
+ """The windows of every module generated, in one package with PeakRDL-socgen's layout.
301
+
302
+ Per interconnect: <INTC>_NMASTER, the interfaces that bring it addresses and are connected; <INTC>_NSLAVE,
303
+ its windows; <INTC>_BASE_ADDRESS, where the lowest of them starts (socgen writes the base of the subsystem,
304
+ the same whenever its first window is at offset 0); and <INTC>_ADDR_RULES, the rule table, its first
305
+ window in the highest element. Per window: <NAME>_<INTC>_START_ADDRESS, _SIZE, _END_ADDRESS and _IDX.
306
+ Its addresses are 32 bits, like socgen's, so a wider map is refused."""
307
+ if not _IDENTIFIER.fullmatch(package) or package in SYSTEMVERILOG_KEYWORDS:
308
+ raise TypeError(f"xactflow-rtl-gen: socgen_package {package!r} is not a package name")
309
+ owners: Dict[str, str] = {}
310
+
311
+ def claim(name: str, owner: str) -> str:
312
+ if owners.setdefault(name, owner) != owner:
313
+ raise ValueError(f"in the socgen package, {owners[name]} and {owner} would both define {name}: give one another name with socgen_names")
314
+ return name
315
+
316
+ def literal(value: int) -> str:
317
+ return f"32'h{value & 0xFFFF_FFFF:08x}"
318
+
319
+ known = set()
320
+ declarations: List[str] = []
321
+ tables: List[str] = []
322
+ for address_map in address_maps:
323
+ if address_map.width > SOCGEN_WIDTH:
324
+ raise ValueError(f"module {address_map.module}: its address map is {address_map.width} bits wide, and the socgen package's addresses are {SOCGEN_WIDTH}")
325
+ for decoder, rules in address_map.tables.items():
326
+ if rules[0].from_outside:
327
+ raise ValueError(f"module {address_map.module}: windows reached from outside it, through its own interfaces, have no place in the socgen package")
328
+ known.add(decoder)
329
+ where = f"{decoder} in {address_map.module}"
330
+ intc = _constant_name(names.get(decoder, decoder).replace("interconnect", "intc"))
331
+ base = min(rule.base for rule in rules)
332
+ declarations += [
333
+ f" // Decoded by {where}",
334
+ f" localparam {claim(f'{intc}_NMASTER', where)} = {address_map.hosts.get(decoder, 0)};",
335
+ f" localparam {claim(f'{intc}_NSLAVE', where)} = {len(rules)};",
336
+ f" localparam {claim(f'{intc}_BASE_ADDRESS', where)} = {literal(base)};",
337
+ "",
338
+ ]
339
+ entries = []
340
+ for rule in rules:
341
+ if rule.size > 0xFFFF_FFFF:
342
+ raise ValueError(f"the address window of {rule.target}, decoded by {where}, is {rule.size:#x} bytes, which 32 bits cannot hold")
343
+ target = rule.target.split(".")[0]
344
+ known.add(target)
345
+ prefix = _constant_name(names.get(target, target), intc)
346
+ owner = f"the window of {rule.target}, decoded by {where}"
347
+ start, size, end, idx = (claim(f"{prefix}_{what}", owner) for what in ("START_ADDRESS", "SIZE", "END_ADDRESS", "IDX"))
348
+ declarations += [
349
+ f" // {decoder}.{rule.interface} reaches {rule.target}",
350
+ f" localparam logic [31:0] {start} = {intc}_BASE_ADDRESS + {literal(rule.base - base)};",
351
+ f" localparam logic [31:0] {size} = {literal(rule.size)};",
352
+ f" localparam logic [31:0] {end} = {start} + {size};",
353
+ f" localparam logic [31:0] {idx} = 32'd{rule.index};",
354
+ "",
355
+ ]
356
+ entries.append(f" {{{idx}, {start}, {end}}}")
357
+ table = claim(f"{intc}_ADDR_RULES", where)
358
+ table_type = claim(f"{table}_t", where)
359
+ # A concatenation, the first window in the highest element as in socgen's, for the reason
360
+ # render_address_map gives. The cast keeps slang from warning.
361
+ tables += [
362
+ f" typedef addr_map_rule_t [{intc}_NSLAVE-1:0] {table_type};",
363
+ f" localparam {table_type} {table} = {table_type}'({{",
364
+ ",\n".join(entries),
365
+ " });",
366
+ "",
367
+ ]
368
+ if not declarations:
369
+ raise ValueError(f"the socgen_package option asks for {package}, and no module generated here has an address window")
370
+ unknown = sorted(set(names) - known)
371
+ if unknown:
372
+ raise ValueError(f"socgen_names names {', '.join(unknown)}, which no address window here is decoded by or reaches")
373
+ claim("addr_map_rule_t", "the rule type")
374
+ lines = [
375
+ header,
376
+ "// The address windows of every module generated with this one, in PeakRDL-socgen's layout, for files",
377
+ "// written against its package. The modules themselves take theirs from their own <module>_addr_map_pkg.",
378
+ "",
379
+ f"package {package};",
380
+ "",
381
+ " typedef struct packed {",
382
+ " logic [31:0] idx;",
383
+ " logic [31:0] start_addr;",
384
+ " logic [31:0] end_addr; // exclusive: start_addr + size",
385
+ " } addr_map_rule_t;",
386
+ "",
387
+ *declarations,
388
+ *tables,
389
+ "endpackage",
390
+ ]
391
+ return "\n".join(lines) + "\n"
@@ -0,0 +1,28 @@
1
+ """The reserved words of SystemVerilog (IEEE 1800-2017 Annex B), which cannot name anything."""
2
+
3
+ SYSTEMVERILOG_KEYWORDS = frozenset(
4
+ """
5
+ accept_on alias always always_comb always_ff always_latch and assert assign assume automatic
6
+ before begin bind bins binsof bit break buf bufif0 bufif1 byte case casex casez cell chandle
7
+ checker class clocking cmos config const constraint context continue cover covergroup
8
+ coverpoint cross deassign default defparam design disable dist do edge else end endcase
9
+ endchecker endclass endclocking endconfig endfunction endgenerate endgroup endinterface
10
+ endmodule endpackage endprimitive endprogram endproperty endspecify endsequence endtable
11
+ endtask enum event eventually expect export extends extern final first_match for force
12
+ foreach forever fork forkjoin function generate genvar global highz0 highz1 if iff ifnone
13
+ ignore_bins illegal_bins implements implies import incdir include initial inout input inside
14
+ instance int integer interconnect interface intersect join join_any join_none large let
15
+ liblist library local localparam logic longint macromodule matches medium modport module nand
16
+ negedge nettype new nexttime nmos nor noshowcancelled not notif0 notif1 null or output package
17
+ packed parameter pmos posedge primitive priority program property protected pull0 pull1
18
+ pulldown pullup pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence
19
+ rcmos real realtime ref reg reject_on release repeat restrict return rnmos rpmos rtran
20
+ rtranif0 rtranif1 s_always s_eventually s_nexttime s_until s_until_with scalared sequence
21
+ shortint shortreal showcancelled signed small soft solve specify specparam static string
22
+ strong strong0 strong1 struct super supply0 supply1 sync_accept_on sync_reject_on table tagged
23
+ task this throughout time timeprecision timeunit tran tranif0 tranif1 tri tri0 tri1 triand
24
+ trior trireg type typedef union unique unique0 unsigned until until_with untyped use uwire var
25
+ vectored virtual void wait wait_order wand weak weak0 weak1 while wildcard wire with within
26
+ wor xnor xor
27
+ """.split()
28
+ )
File without changes