1 from abc
import abstractproperty
7 __all__
= ["LatticeICE40Platform"]
10 class LatticeICE40Platform(TemplatedPlatform
):
20 The environment is populated by running the script specified in the environment variable
21 ``NMIGEN_ENV_IceStorm``, if present.
24 * ``verbose``: enables logging of informational messages to standard error.
25 * ``read_verilog_opts``: adds options for ``read_verilog`` Yosys command.
26 * ``synth_opts``: adds options for ``synth_ice40`` Yosys command.
27 * ``script_after_read``: inserts commands after ``read_ilang`` in Yosys script.
28 * ``script_after_synth``: inserts commands after ``synth_ice40`` in Yosys script.
29 * ``yosys_opts``: adds extra options for ``yosys``.
30 * ``nextpnr_opts``: adds extra options for ``nextpnr-ice40``.
31 * ``add_pre_pack``: inserts commands at the end in pre-pack Python script.
32 * ``add_constraints``: inserts commands at the end in the PCF file.
35 * ``{{name}}.rpt``: Yosys log.
36 * ``{{name}}.json``: synthesized RTL.
37 * ``{{name}}.tim``: nextpnr log.
38 * ``{{name}}.asc``: ASCII bitstream.
39 * ``{{name}}.bin``: binary bitstream.
44 This toolchain comes in two variants: ``LSE-iCECube2`` and ``Synplify-iCECube2``.
50 The environment is populated by setting the necessary environment variables based on
51 ``NMIGEN_ENV_iCECube2``, which must point to the root of the iCECube2 installation, and
55 * ``verbose``: enables logging of informational messages to standard error.
56 * ``lse_opts``: adds options for LSE.
57 * ``script_after_add``: inserts commands after ``add_file`` in Synplify Tcl script.
58 * ``script_after_options``: inserts commands after ``set_option`` in Synplify Tcl script.
59 * ``add_constraints``: inserts commands in SDC file.
60 * ``script_after_flow``: inserts commands after ``run_sbt_backend_auto`` in SBT
64 * ``{{name}}_lse.log`` (LSE) or ``{{name}}_design/{{name}}.htm`` (Synplify): synthesis log.
65 * ``sbt/outputs/router/{{name}}_timing.rpt``: timing report.
66 * ``{{name}}.edf``: EDIF netlist.
67 * ``{{name}}.bin``: binary bitstream.
70 toolchain
= None # selected when creating platform
72 device
= abstractproperty()
73 package
= abstractproperty()
77 _nextpnr_device_options
= {
78 "iCE40LP384": "--lp384",
79 "iCE40LP1K": "--lp1k",
80 "iCE40LP4K": "--lp8k",
81 "iCE40LP8K": "--lp8k",
82 "iCE40HX1K": "--hx1k",
83 "iCE40HX4K": "--hx8k",
84 "iCE40HX8K": "--hx8k",
85 "iCE40UP5K": "--up5k",
86 "iCE40UP3K": "--up5k",
91 _nextpnr_package_options
= {
99 _icestorm_required_tools
= [
104 _icestorm_file_templates
= {
105 **TemplatedPlatform
.build_script_templates
,
108 {{emit_design("rtlil")}}
112 {% for file in platform.iter_extra_files(".v") -%}
113 read_verilog {{get_override("read_opts")|options}} {{file}}
115 {% for file in platform.iter_extra_files(".sv") -%}
116 read_verilog -sv {{get_override("read_opts")|options}} {{file}}
118 read_ilang {{name}}.il
119 {{get_override("script_after_read")|default("# (script_after_read placeholder)")}}
120 synth_ice40 {{get_override("synth_opts")|options}} -top {{name}}
121 {{get_override("script_after_synth")|default("# (script_after_synth placeholder)")}}
122 write_json {{name}}.json
124 "{{name}}_pre_pack.py": r
"""
126 {% for signal, frequency in platform.iter_clock_constraints() -%}
128 ctx.addClock("{{signal|hierarchy(".")}}", {{frequency/1000000}})
130 {{get_override("add_pre_pack")|default("# (add_pre_pack placeholder)")}}
134 {% for port_name, pin_name, attrs in platform.iter_port_constraints_bits() -%}
135 set_io {{port_name}} {{pin_name}}
137 {{get_override("add_constraints")|default("# (add_constraints placeholder)")}}
140 _icestorm_command_templates
= [
142 {{get_tool("yosys")}}
144 {{get_override("yosys_opts")|options}}
149 {{get_tool("nextpnr-ice40")}}
151 {{get_override("nextpnr_opts")|options}}
153 {{platform._nextpnr_device_options[platform.device]}}
155 {{platform.package|lower}}{{platform._nextpnr_package_options[platform.device]}}
158 --pre-pack {{name}}_pre_pack.py
162 {{get_tool("icepack")}}
171 _icecube2_required_tools
= [
176 _icecube2_file_templates
= {
177 **TemplatedPlatform
.build_script_templates
,
178 "build_{{name}}.sh": r
"""
180 set -e{{verbose("x")}}
181 if [ -n "${{platform._toolchain_env_var}}" ]; then
183 export LD_LIBRARY_PATH=${{platform._toolchain_env_var}}/LSE/bin/lin64:$LD_LIBRARY_PATH
184 export PATH=${{platform._toolchain_env_var}}/LSE/bin/lin64:$PATH
185 export FOUNDRY=${{platform._toolchain_env_var}}/LSE
186 # Synplify environment
187 export LD_LIBRARY_PATH=${{platform._toolchain_env_var}}/sbt_backend/bin/linux/opt/synpwrap:$LD_LIBRARY_PATH
188 export PATH=${{platform._toolchain_env_var}}/sbt_backend/bin/linux/opt/synpwrap:$PATH
189 export SYNPLIFY_PATH=${{platform._toolchain_env_var}}/synpbase
191 export SBT_DIR=${{platform._toolchain_env_var}}/sbt_backend
193 echo "Variable ${{platform._toolchain_env_var}} must be set" >&2; exit 1
195 {{emit_commands("sh")}}
198 /* {{autogenerated}} */
199 {{emit_design("verilog")}}
201 "{{name}}_lse.prj": r
"""
203 -a SBT{{platform.family}}
204 -d {{platform.device}}
205 -t {{platform.package}}
206 {{get_override("lse_opts")|options|default("# (lse_opts placeholder)")}}
207 {% for file in platform.iter_extra_files(".v") -%}
213 -output_edif {{name}}.edf
214 -logfile {{name}}_lse.log
216 "{{name}}_syn.prj": r
"""
218 {% for file in platform.iter_extra_files(".v", ".sv", ".vhd", ".vhdl") -%}
219 add_file -verilog {{file}}
221 add_file -verilog {{name}}.v
222 add_file -constraint {{name}}.sdc
223 {{get_override("script_after_add")|default("# (script_after_add placeholder)")}}
224 impl -add {{name}}_design -type fpga
225 set_option -technology SBT{{platform.family}}
226 set_option -part {{platform.device}}
227 set_option -package {{platform.package}}
228 {{get_override("script_after_options")|default("# (script_after_options placeholder)")}}
229 project -result_format edif
230 project -result_file {{name}}.edf
231 impl -active {{name}}_design
234 project -run fpga_mapper
235 file copy -force -- {{name}}_design/{{name}}.edf {{name}}.edf
239 {% for signal, frequency in platform.iter_clock_constraints() -%}
240 create_clock -name {{signal.name}} -period {{1000000000/frequency}} [get_nets {{signal|hierarchy("/")}}]
242 {{get_override("add_constraints")|default("# (add_constraints placeholder)")}}
246 set device {{platform.device}}-{{platform.package}}
247 set top_module {{name}}
250 set edif_file {{name}}
251 set tool_options ":edifparser -y {{name}}.pcf"
252 set sbt_root $::env(SBT_DIR)
253 append sbt_tcl $sbt_root "/tcl/sbt_backend_synpl.tcl"
255 run_sbt_backend_auto $device $top_module $proj_dir $output_dir $tool_options $edif_file
256 {{get_override("script_after_file")|default("# (script_after_file placeholder)")}}
257 file copy -force -- sbt/outputs/bitmap/{{name}}_bitmap.bin {{name}}.bin
262 {% for port_name, pin_name, attrs in platform.iter_port_constraints_bits() -%}
263 set_io {{port_name}} {{pin_name}}
267 _lse_icecube2_command_templates
= [
268 r
"""synthesis -f {{name}}_lse.prj""",
269 r
"""tclsh {{name}}.tcl""",
271 _synplify_icecube2_command_templates
= [
272 r
"""synpwrap -prj {{name}}_syn.prj -log {{name}}_syn.log""",
273 r
"""tclsh {{name}}.tcl""",
278 def __init__(self
, *, toolchain
="IceStorm"):
281 assert toolchain
in ("IceStorm", "LSE-iCECube2", "Synplify-iCECube2")
282 self
.toolchain
= toolchain
286 if self
.device
.startswith("iCE40"):
288 if self
.device
.startswith("iCE5"):
293 def _toolchain_env_var(self
):
294 if self
.toolchain
== "IceStorm":
295 return f
"NMIGEN_ENV_{self.toolchain}"
296 if self
.toolchain
in ("LSE-iCECube2", "Synplify-iCECube2"):
297 return f
"NMIGEN_ENV_iCECube2"
301 def required_tools(self
):
302 if self
.toolchain
== "IceStorm":
303 return self
._icestorm
_required
_tools
304 if self
.toolchain
in ("LSE-iCECube2", "Synplify-iCECube2"):
305 return self
._icecube
2_required
_tools
309 def file_templates(self
):
310 if self
.toolchain
== "IceStorm":
311 return self
._icestorm
_file
_templates
312 if self
.toolchain
in ("LSE-iCECube2", "Synplify-iCECube2"):
313 return self
._icecube
2_file
_templates
317 def command_templates(self
):
318 if self
.toolchain
== "IceStorm":
319 return self
._icestorm
_command
_templates
320 if self
.toolchain
== "LSE-iCECube2":
321 return self
._lse
_icecube
2_command
_templates
322 if self
.toolchain
== "Synplify-iCECube2":
323 return self
._synplify
_icecube
2_command
_templates
326 def create_missing_domain(self
, name
):
327 # For unknown reasons (no errata was ever published, and no documentation mentions this
328 # issue), iCE40 BRAMs read as zeroes for ~3 us after configuration and release of internal
329 # global reset. Note that this is a *time-based* delay, generated purely by the internal
330 # oscillator, which may not be observed nor influenced directly. For details, see links:
331 # * https://github.com/cliffordwolf/icestorm/issues/76#issuecomment-289270411
332 # * https://github.com/cliffordwolf/icotools/issues/2#issuecomment-299734673
334 # To handle this, it is necessary to have a global reset in any iCE40 design that may
335 # potentially instantiate BRAMs, and assert this reset for >3 us after configuration.
336 # (We add a margin of 5x to allow for PVT variation.) If the board includes a dedicated
337 # reset line, this line is ORed with the power on reset.
339 # The power-on reset timer counts up because the vendor tools do not support initialization
341 if name
== "sync" and self
.default_clk
is not None:
342 clk_i
= self
.request(self
.default_clk
).i
343 if self
.default_rst
is not None:
344 rst_i
= self
.request(self
.default_rst
).i
347 # Power-on-reset domain
348 m
.domains
+= ClockDomain("por", reset_less
=True, local
=True)
349 delay
= int(15e-6 * self
.default_clk_frequency
)
350 timer
= Signal(max=delay
)
352 m
.d
.comb
+= ClockSignal("por").eq(clk_i
)
353 with m
.If(timer
== delay
):
354 m
.d
.por
+= ready
.eq(1)
356 m
.d
.por
+= timer
.eq(timer
+ 1)
358 m
.domains
+= ClockDomain("sync")
359 m
.d
.comb
+= ClockSignal("sync").eq(clk_i
)
360 if self
.default_rst
is not None:
361 m
.d
.comb
+= ResetSignal("sync").eq(~ready | rst_i
)
363 m
.d
.comb
+= ResetSignal("sync").eq(~ready
)
366 def should_skip_port_component(self
, port
, attrs
, component
):
367 # On iCE40, a differential input is placed by only instantiating an SB_IO primitive for
368 # the pin with z=0, which is the non-inverting pin. The pinout unfortunately differs
369 # between LP/HX and UP series:
370 # * for LP/HX, z=0 is DPxxB (B is non-inverting, A is inverting)
371 # * for UP, z=0 is IOB_xxA (A is non-inverting, B is inverting)
372 if attrs
.get("IO_STANDARD", "SB_LVCMOS") == "SB_LVDS_INPUT" and component
== "n":
376 def _get_io_buffer(self
, m
, pin
, port
, attrs
, *, i_invert
=False, o_invert
=False,
378 def get_dff(clk
, d
, q
):
379 m
.submodules
+= Instance("$dff",
386 def get_ineg(y
, invert
):
388 a
= Signal
.like(y
, name_suffix
="_x{}".format(1 if invert
else 0))
389 for bit
in range(len(y
)):
390 m
.submodules
+= Instance("SB_LUT4",
391 p_LUT_INIT
=Const(0b01 if invert
else 0b10, 16),
399 a
= Signal
.like(y
, name_suffix
="_n")
405 def get_oneg(a
, invert
):
407 y
= Signal
.like(a
, name_suffix
="_x{}".format(1 if invert
else 0))
408 for bit
in range(len(a
)):
409 m
.submodules
+= Instance("SB_LUT4",
410 p_LUT_INIT
=Const(0b01 if invert
else 0b10, 16),
418 y
= Signal
.like(a
, name_suffix
="_n")
424 if "GLOBAL" in attrs
:
425 is_global_input
= bool(attrs
["GLOBAL"])
428 is_global_input
= False
429 assert not (is_global_input
and i_invert
)
433 pin_i
= get_ineg(pin
.i
, i_invert
)
435 pin_i0
= get_ineg(pin
.i0
, i_invert
)
436 pin_i1
= get_ineg(pin
.i1
, i_invert
)
439 pin_o
= get_oneg(pin
.o
, o_invert
)
441 pin_o0
= get_oneg(pin
.o0
, o_invert
)
442 pin_o1
= get_oneg(pin
.o1
, o_invert
)
444 if "i" in pin
.dir and pin
.xdr
== 2:
445 i0_ff
= Signal
.like(pin_i0
, name_suffix
="_ff")
446 i1_ff
= Signal
.like(pin_i1
, name_suffix
="_ff")
447 get_dff(pin
.i_clk
, i0_ff
, pin_i0
)
448 get_dff(pin
.i_clk
, i1_ff
, pin_i1
)
449 if "o" in pin
.dir and pin
.xdr
== 2:
450 o1_ff
= Signal
.like(pin_o1
, name_suffix
="_ff")
451 get_dff(pin
.o_clk
, pin_o1
, o1_ff
)
453 for bit
in range(len(port
)):
455 ("io", "PACKAGE_PIN", port
[bit
]),
456 *(("p", key
, value
) for key
, value
in attrs
.items()),
459 if "i" not in pin
.dir:
460 # If no input pin is requested, it is important to use a non-registered input pin
461 # type, because an output-only pin would not have an input clock, and if its input
462 # is configured as registered, this would prevent a co-located input-capable pin
463 # from using an input clock.
464 i_type
= 0b01 # PIN_INPUT
466 i_type
= 0b01 # PIN_INPUT
468 i_type
= 0b00 # PIN_INPUT_REGISTERED aka PIN_INPUT_DDR
469 if "o" not in pin
.dir:
470 o_type
= 0b0000 # PIN_NO_OUTPUT
471 elif pin
.xdr
== 0 and pin
.dir == "o":
472 o_type
= 0b0110 # PIN_OUTPUT
474 o_type
= 0b1010 # PIN_OUTPUT_TRISTATE
475 elif pin
.xdr
== 1 and pin
.dir == "o":
476 o_type
= 0b0101 # PIN_OUTPUT_REGISTERED
478 o_type
= 0b1101 # PIN_OUTPUT_REGISTERED_ENABLE_REGISTERED
479 elif pin
.xdr
== 2 and pin
.dir == "o":
480 o_type
= 0b0100 # PIN_OUTPUT_DDR
482 o_type
= 0b1100 # PIN_OUTPUT_DDR_ENABLE_REGISTERED
483 io_args
.append(("p", "PIN_TYPE", C((o_type
<< 2) | i_type
, 6)))
485 if hasattr(pin
, "i_clk"):
486 io_args
.append(("i", "INPUT_CLK", pin
.i_clk
))
487 if hasattr(pin
, "o_clk"):
488 io_args
.append(("i", "OUTPUT_CLK", pin
.o_clk
))
491 if pin
.xdr
== 0 and is_global_input
:
492 io_args
.append(("o", "GLOBAL_BUFFER_OUTPUT", pin
.i
[bit
]))
494 io_args
.append(("o", "D_IN_0", pin_i
[bit
]))
496 # Re-register both inputs before they enter fabric. This increases hold time
497 # to an entire cycle, and adds one cycle of latency.
498 io_args
.append(("o", "D_IN_0", i0_ff
[bit
]))
499 io_args
.append(("o", "D_IN_1", i1_ff
[bit
]))
502 io_args
.append(("i", "D_OUT_0", pin_o
[bit
]))
504 # Re-register negedge output after it leaves fabric. This increases setup time
505 # to an entire cycle, and doesn't add latency.
506 io_args
.append(("i", "D_OUT_0", pin_o0
[bit
]))
507 io_args
.append(("i", "D_OUT_1", o1_ff
[bit
]))
509 if pin
.dir in ("oe", "io"):
510 io_args
.append(("i", "OUTPUT_ENABLE", pin
.oe
))
513 m
.submodules
["{}_{}".format(pin
.name
, bit
)] = Instance("SB_GB_IO", *io_args
)
515 m
.submodules
["{}_{}".format(pin
.name
, bit
)] = Instance("SB_IO", *io_args
)
517 def get_input(self
, pin
, port
, attrs
, invert
):
518 self
._check
_feature
("single-ended input", pin
, attrs
,
519 valid_xdrs
=(0, 1, 2), valid_attrs
=True)
521 self
._get
_io
_buffer
(m
, pin
, port
, attrs
, i_invert
=invert
)
524 def get_output(self
, pin
, port
, attrs
, invert
):
525 self
._check
_feature
("single-ended output", pin
, attrs
,
526 valid_xdrs
=(0, 1, 2), valid_attrs
=True)
528 self
._get
_io
_buffer
(m
, pin
, port
, attrs
, o_invert
=invert
)
531 def get_tristate(self
, pin
, port
, attrs
, invert
):
532 self
._check
_feature
("single-ended tristate", pin
, attrs
,
533 valid_xdrs
=(0, 1, 2), valid_attrs
=True)
535 self
._get
_io
_buffer
(m
, pin
, port
, attrs
, o_invert
=invert
)
538 def get_input_output(self
, pin
, port
, attrs
, invert
):
539 self
._check
_feature
("single-ended input/output", pin
, attrs
,
540 valid_xdrs
=(0, 1, 2), valid_attrs
=True)
542 self
._get
_io
_buffer
(m
, pin
, port
, attrs
, i_invert
=invert
, o_invert
=invert
)
545 def get_diff_input(self
, pin
, p_port
, n_port
, attrs
, invert
):
546 self
._check
_feature
("differential input", pin
, attrs
,
547 valid_xdrs
=(0, 1, 2), valid_attrs
=True)
549 # See comment in should_skip_port_component above.
550 self
._get
_io
_buffer
(m
, pin
, p_port
, attrs
, i_invert
=invert
)
553 def get_diff_output(self
, pin
, p_port
, n_port
, attrs
, invert
):
554 self
._check
_feature
("differential output", pin
, attrs
,
555 valid_xdrs
=(0, 1, 2), valid_attrs
=True)
557 # Note that the non-inverting output pin is not driven the same way as a regular
558 # output pin. The inverter introduces a delay, so for a non-inverting output pin,
559 # an identical delay is introduced by instantiating a LUT. This makes the waveform
560 # perfectly symmetric in the xdr=0 case.
561 self
._get
_io
_buffer
(m
, pin
, p_port
, attrs
, o_invert
= invert
, invert_lut
=True)
562 self
._get
_io
_buffer
(m
, pin
, n_port
, attrs
, o_invert
=not invert
, invert_lut
=True)
565 # Tristate and bidirectional buffers are not supported on iCE40 because it requires external
566 # termination, which is incompatible for input and output differential I/Os.
568 # CDC primitives are not currently specialized for iCE40. It is not known if iCECube2 supports
569 # the necessary attributes; nextpnr-ice40 does not.