build/xilinx: add support for edif/ngc files
[litex.git] / litex / build / xilinx / vivado.py
1 # This file is Copyright (c) 2014 Florent Kermarrec <florent@enjoy-digital.fr>
2 # License: BSD
3
4 import os
5 import subprocess
6 import sys
7
8 from litex.gen.fhdl.structure import _Fragment
9 from litex.build.generic_platform import *
10 from litex.build import tools
11 from litex.build.xilinx import common
12
13
14 def _format_constraint(c):
15 if isinstance(c, Pins):
16 return "set_property LOC " + c.identifiers[0]
17 elif isinstance(c, IOStandard):
18 return "set_property IOSTANDARD " + c.name
19 elif isinstance(c, Drive):
20 return "set_property DRIVE " + str(c.strength)
21 elif isinstance(c, Misc):
22 return "set_property " + c.misc.replace("=", " ")
23 else:
24 raise ValueError("unknown constraint {}".format(c))
25
26
27 def _format_xdc(signame, resname, *constraints):
28 fmt_c = [_format_constraint(c) for c in constraints]
29 fmt_r = resname[0] + ":" + str(resname[1])
30 if resname[2] is not None:
31 fmt_r += "." + resname[2]
32 r = " ## {}\n".format(fmt_r)
33 for c in fmt_c:
34 r += c + " [get_ports " + signame + "]\n"
35 return r
36
37
38 def _build_xdc(named_sc, named_pc):
39 r = ""
40 for sig, pins, others, resname in named_sc:
41 if len(pins) > 1:
42 for i, p in enumerate(pins):
43 r += _format_xdc(sig + "[" + str(i) + "]", resname, Pins(p), *others)
44 elif pins:
45 r += _format_xdc(sig, resname, Pins(pins[0]), *others)
46 else:
47 r += _format_xdc(sig, resname, *others)
48 if named_pc:
49 r += "\n" + "\n\n".join(named_pc)
50 return r
51
52
53 def _run_vivado(build_name, vivado_path, source, ver=None):
54 if sys.platform == "win32" or sys.platform == "cygwin":
55 build_script_contents = "REM Autogenerated by LiteX\n"
56 build_script_contents += "vivado -mode batch -source " + build_name + ".tcl\n"
57 build_script_file = "build_" + build_name + ".bat"
58 tools.write_to_file(build_script_file, build_script_contents)
59 command = build_script_file
60 else:
61 build_script_contents = "# Autogenerated by LiteX\nset -e\n"
62 settings = common.settings(vivado_path, "Vivado", ver, first="name")
63 build_script_contents += "source " + settings + "\n"
64 build_script_contents += "vivado -mode batch -source " + build_name + ".tcl\n"
65 build_script_file = "build_" + build_name + ".sh"
66 tools.write_to_file(build_script_file, build_script_contents)
67 command = ["bash", build_script_file]
68 r = tools.subprocess_call_filtered(command, common.colors)
69 if r != 0:
70 raise OSError("Subprocess failed")
71
72
73 class XilinxVivadoToolchain:
74 attr_translate = {
75 "keep": ("dont_touch", "true"),
76 "no_retiming": ("dont_touch", "true"),
77 "async_reg": ("async_reg", "true"),
78 "ars_ff": ("ars_ff", "true"), # user-defined attribute
79 "ars_false_path": ("ars_false_path", "true"), # user-defined attribute
80 "no_shreg_extract": None
81 }
82
83 def __init__(self):
84 self.bitstream_commands = []
85 self.additional_commands = []
86 self.pre_synthesis_commands = []
87 self.with_phys_opt = False
88 self.clocks = dict()
89 self.false_paths = set()
90
91 def _build_batch(self, platform, sources, edifs, build_name):
92 tcl = []
93 tcl.append("create_property ars_ff cell")
94 tcl.append("create_property ars_false_path net")
95 for filename, language, library in sources:
96 filename_tcl = "{" + filename + "}"
97 tcl.append("add_files " + filename_tcl)
98 tcl.append("set_property library {} [get_files {}]"
99 .format(library, filename_tcl))
100 for filename in edifs:
101 filename_tcl = "{" + filename + "}"
102 tcl.append("read_edif " + filename_tcl)
103 tcl.append("read_xdc {}.xdc".format(build_name))
104 tcl.extend(c.format(build_name=build_name) for c in self.pre_synthesis_commands)
105 # "-include_dirs {}" crashes Vivado 2016.4
106 if platform.verilog_include_paths:
107 tcl.append("synth_design -top {} -part {} -include_dirs {{{}}}".format(build_name, platform.device, " ".join(platform.verilog_include_paths)))
108 else:
109 tcl.append("synth_design -top {} -part {}".format(build_name, platform.device))
110 tcl.append("write_checkpoint -force {}_synth.dcp".format(build_name))
111 tcl.append("report_timing_summary -file {}_timing_synth.rpt".format(build_name))
112 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_synth.rpt".format(build_name))
113 tcl.append("report_utilization -file {}_utilization_synth.rpt".format(build_name))
114 tcl.append("opt_design")
115 tcl.append("place_design")
116 if self.with_phys_opt:
117 tcl.append("phys_opt_design -directive AddRetime")
118 tcl.append("write_checkpoint -force {}_place.dcp".format(build_name))
119 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_place.rpt".format(build_name))
120 tcl.append("report_utilization -file {}_utilization_place.rpt".format(build_name))
121 tcl.append("report_io -file {}_io.rpt".format(build_name))
122 tcl.append("report_control_sets -verbose -file {}_control_sets.rpt".format(build_name))
123 tcl.append("report_clock_utilization -file {}_clock_utilization.rpt".format(build_name))
124 tcl.append("route_design")
125 tcl.append("write_checkpoint -force {}_route.dcp".format(build_name))
126 tcl.append("report_route_status -file {}_route_status.rpt".format(build_name))
127 tcl.append("report_drc -file {}_drc.rpt".format(build_name))
128 tcl.append("report_timing_summary -datasheet -max_paths 10 -file {}_timing.rpt".format(build_name))
129 tcl.append("report_power -file {}_power.rpt".format(build_name))
130 for bitstream_command in self.bitstream_commands:
131 tcl.append(bitstream_command.format(build_name=build_name))
132 tcl.append("write_bitstream -force {}.bit ".format(build_name))
133 for additional_command in self.additional_commands:
134 tcl.append(additional_command.format(build_name=build_name))
135 tcl.append("quit")
136 tools.write_to_file(build_name + ".tcl", "\n".join(tcl))
137
138 def _convert_clocks(self, platform):
139 for clk, period in sorted(self.clocks.items(), key=lambda x: x[0].duid):
140 platform.add_platform_command(
141 "create_clock -name {clk} -period " + str(period) +
142 " [get_nets {clk}]", clk=clk)
143 for from_, to in sorted(self.false_paths,
144 key=lambda x: (x[0].duid, x[1].duid)):
145 if (from_ not in self.clocks
146 or to not in self.clocks):
147 raise ValueError("Vivado requires period "
148 "constraints on all clocks used in false paths")
149 platform.add_platform_command(
150 "set_false_path -from [get_clocks {from_}] -to [get_clocks {to}]",
151 from_=from_, to=to)
152
153 # make sure add_*_constraint cannot be used again
154 del self.clocks
155 del self.false_paths
156
157 def _constrain(self, platform):
158 # The asychronous reset input to the AsyncResetSynchronizer is a false
159 # path
160 platform.add_platform_command(
161 "set_false_path -quiet "
162 "-through [get_nets -hier -filter {{ars_false_path==true}}] "
163 "-to [get_cells -hier -filter {{ars_ff==true}}]"
164 )
165 # clock_period-2ns to resolve metastability on the wire between the
166 # AsyncResetSynchronizer FFs
167 platform.add_platform_command(
168 "set_max_delay 2 -quiet "
169 "-from [get_cells -hier -filter {{ars_ff==true}}] "
170 "-to [get_cells -hier -filter {{ars_ff==true}}]"
171 )
172
173 def build(self, platform, fragment, build_dir="build", build_name="top",
174 toolchain_path=None, source=True, run=True, **kwargs):
175 if toolchain_path is None:
176 if sys.platform == "win32":
177 toolchain_path = "C:\\Xilinx"
178 elif sys.platform == "cygwin":
179 toolchain_path = "/cygdrive/c/Xilinx"
180 else:
181 toolchain_path = "/opt/Xilinx"
182 os.makedirs(build_dir, exist_ok=True)
183 cwd = os.getcwd()
184 os.chdir(build_dir)
185
186 if not isinstance(fragment, _Fragment):
187 fragment = fragment.get_fragment()
188 platform.finalize(fragment)
189 self._convert_clocks(platform)
190 self._constrain(platform)
191 v_output = platform.get_verilog(fragment, name=build_name, **kwargs)
192 named_sc, named_pc = platform.resolve_signals(v_output.ns)
193 v_file = build_name + ".v"
194 v_output.write(v_file)
195 sources = platform.sources | {(v_file, "verilog", "work")}
196 edifs = platform.edifs
197 self._build_batch(platform, sources, edifs, build_name)
198 tools.write_to_file(build_name + ".xdc", _build_xdc(named_sc, named_pc))
199 if run:
200 _run_vivado(build_name, toolchain_path, source)
201
202 os.chdir(cwd)
203
204 return v_output.ns
205
206 def add_period_constraint(self, platform, clk, period):
207 if clk in self.clocks:
208 raise ValueError("A period constraint already exists")
209 self.clocks[clk] = period
210
211 def add_false_path_constraint(self, platform, from_, to):
212 self.false_paths.add((from_, to))