build/xilinx/vivado: cleanup pull request #170
[litex.git] / litex / build / xilinx / vivado.py
1 # This file is Copyright (c) 2014-2019 Florent Kermarrec <florent@enjoy-digital.fr>
2 # License: BSD
3
4 import os
5 import subprocess
6 import sys
7 import math
8 from distutils.spawn import find_executable
9
10 from migen.fhdl.structure import _Fragment
11
12 from litex.build.generic_platform import *
13 from litex.build import tools
14 from litex.build.xilinx import common
15
16
17 def _format_constraint(c):
18 if isinstance(c, Pins):
19 return "set_property LOC " + c.identifiers[0]
20 elif isinstance(c, IOStandard):
21 return "set_property IOSTANDARD " + c.name
22 elif isinstance(c, Drive):
23 return "set_property DRIVE " + str(c.strength)
24 elif isinstance(c, Misc):
25 return "set_property " + c.misc.replace("=", " ")
26 elif isinstance(c, Inverted):
27 return None
28 else:
29 raise ValueError("unknown constraint {}".format(c))
30
31
32 def _format_xdc(signame, resname, *constraints):
33 fmt_c = [_format_constraint(c) for c in constraints]
34 fmt_r = resname[0] + ":" + str(resname[1])
35 if resname[2] is not None:
36 fmt_r += "." + resname[2]
37 r = " ## {}\n".format(fmt_r)
38 for c in fmt_c:
39 if c is not None:
40 r += c + " [get_ports " + signame + "]\n"
41 return r
42
43
44 def _build_xdc(named_sc, named_pc):
45 r = ""
46 for sig, pins, others, resname in named_sc:
47 if len(pins) > 1:
48 for i, p in enumerate(pins):
49 r += _format_xdc(sig + "[" + str(i) + "]", resname, Pins(p), *others)
50 elif pins:
51 r += _format_xdc(sig, resname, Pins(pins[0]), *others)
52 else:
53 r += _format_xdc(sig, resname, *others)
54 if named_pc:
55 r += "\n" + "\n\n".join(named_pc)
56 return r
57
58
59 def _run_vivado(build_name, vivado_path, source, ver=None):
60 if sys.platform == "win32" or sys.platform == "cygwin":
61 build_script_contents = "REM Autogenerated by Migen\n"
62 build_script_contents += "vivado -mode batch -source " + build_name + ".tcl\n"
63 build_script_file = "build_" + build_name + ".bat"
64 tools.write_to_file(build_script_file, build_script_contents)
65 command = build_script_file
66 else:
67 build_script_contents = "# Autogenerated by Migen\nset -e\n"
68 # Only source Vivado settings if not already in our $PATH
69 if not find_executable("vivado"):
70 # For backwards compatibility with ISE paths, also
71 # look for a version in a subdirectory named "Vivado"
72 # under the current directory.
73 paths_to_try = [vivado_path, os.path.join(vivado_path, "Vivado")]
74 for p in paths_to_try:
75 try:
76 settings = common.settings(p, ver)
77 except OSError:
78 continue
79 break
80 else:
81 raise OSError("Unable to locate Vivado directory or settings.")
82 build_script_contents += "source " + settings + "\n"
83
84 build_script_contents += "vivado -mode batch -source " + build_name + ".tcl\n"
85 build_script_file = "build_" + build_name + ".sh"
86 tools.write_to_file(build_script_file, build_script_contents)
87 command = ["bash", build_script_file]
88 r = tools.subprocess_call_filtered(command, common.colors)
89 if r != 0:
90 raise OSError("Subprocess failed")
91
92
93 class XilinxVivadoToolchain:
94 attr_translate = {
95 "keep": ("dont_touch", "true"),
96 "no_retiming": ("dont_touch", "true"),
97 "async_reg": ("async_reg", "true"),
98 "mr_ff": ("mr_ff", "true"), # user-defined attribute
99 "ars_ff1": ("ars_ff1", "true"), # user-defined attribute
100 "ars_ff2": ("ars_ff2", "true"), # user-defined attribute
101 "no_shreg_extract": None
102 }
103
104 def __init__(self):
105 self.bitstream_commands = []
106 self.additional_commands = []
107 self.pre_synthesis_commands = []
108 self.with_phys_opt = False
109 self.clocks = dict()
110 self.false_paths = set()
111
112 def _build_batch(self, platform, sources, edifs, ips, build_name, synth_mode, enable_xpm):
113 assert synth_mode in ["vivado", "yosys"]
114 tcl = []
115 tcl.append("create_project -force -name {} -part {}".format(build_name, platform.device))
116 if enable_xpm:
117 tcl.append("set_property XPM_LIBRARIES {XPM_CDC XPM_MEMORY} [current_project]")
118 if synth_mode == "vivado":
119 # "-include_dirs {}" crashes Vivado 2016.4
120 for filename, language, library in sources:
121 filename_tcl = "{" + filename + "}"
122 tcl.append("add_files " + filename_tcl)
123 if language == "vhdl":
124 tcl.append("set_property library {} [get_files {}]"
125 .format(library, filename_tcl))
126 for filename in edifs:
127 filename_tcl = "{" + filename + "}"
128 tcl.append("read_edif " + filename_tcl)
129
130 for filename in ips:
131 filename_tcl = "{" + filename + "}"
132 ip = os.path.splitext(os.path.basename(filename))[0]
133 tcl.append("read_ip " + filename_tcl)
134 tcl.append("upgrade_ip [get_ips {}]".format(ip))
135 tcl.append("generate_target all [get_ips {}]".format(ip))
136 tcl.append("synth_ip [get_ips {}] -force".format(ip))
137 tcl.append("get_files -all -of_objects [get_files {}]".format(filename_tcl))
138
139 tcl.append("read_xdc {}.xdc".format(build_name))
140 tcl.extend(c.format(build_name=build_name) for c in self.pre_synthesis_commands)
141
142 if synth_mode == "vivado":
143 if platform.verilog_include_paths:
144 tcl.append("synth_design -top {} -part {} -include_dirs {{{}}}".format(build_name, platform.device, " ".join(platform.verilog_include_paths)))
145 else:
146 tcl.append("synth_design -top {} -part {}".format(build_name, platform.device))
147 elif synth_mode == "yosys":
148 tcl.append("read_edif {}.edif".format(build_name))
149 tcl.append("link_design -top {} -part {}".format(build_name, platform.device))
150 else:
151 raise OSError("Unknown synthesis mode! {}".format(synth_mode))
152
153 tcl.append("report_timing_summary -file {}_timing_synth.rpt".format(build_name))
154 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_synth.rpt".format(build_name))
155 tcl.append("report_utilization -file {}_utilization_synth.rpt".format(build_name))
156 tcl.append("opt_design")
157 tcl.append("place_design")
158 if self.with_phys_opt:
159 tcl.append("phys_opt_design -directive AddRetime")
160 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_place.rpt".format(build_name))
161 tcl.append("report_utilization -file {}_utilization_place.rpt".format(build_name))
162 tcl.append("report_io -file {}_io.rpt".format(build_name))
163 tcl.append("report_control_sets -verbose -file {}_control_sets.rpt".format(build_name))
164 tcl.append("report_clock_utilization -file {}_clock_utilization.rpt".format(build_name))
165 tcl.append("route_design")
166 tcl.append("phys_opt_design")
167 tcl.append("report_timing_summary -no_header -no_detailed_paths")
168 tcl.append("write_checkpoint -force {}_route.dcp".format(build_name))
169 tcl.append("report_route_status -file {}_route_status.rpt".format(build_name))
170 tcl.append("report_drc -file {}_drc.rpt".format(build_name))
171 tcl.append("report_timing_summary -datasheet -max_paths 10 -file {}_timing.rpt".format(build_name))
172 tcl.append("report_power -file {}_power.rpt".format(build_name))
173 for bitstream_command in self.bitstream_commands:
174 tcl.append(bitstream_command.format(build_name=build_name))
175 tcl.append("write_bitstream -force {}.bit ".format(build_name))
176 for additional_command in self.additional_commands:
177 tcl.append(additional_command.format(build_name=build_name))
178 tcl.append("quit")
179 tools.write_to_file(build_name + ".tcl", "\n".join(tcl))
180
181 def _convert_clocks(self, platform):
182 for clk, period in sorted(self.clocks.items(), key=lambda x: x[0].duid):
183 platform.add_platform_command(
184 "create_clock -name {clk} -period " + str(period) +
185 " [get_nets {clk}]", clk=clk)
186 for from_, to in sorted(self.false_paths,
187 key=lambda x: (x[0].duid, x[1].duid)):
188 platform.add_platform_command(
189 "set_clock_groups "
190 "-group [get_clocks -include_generated_clocks -of [get_nets {from_}]] "
191 "-group [get_clocks -include_generated_clocks -of [get_nets {to}]] "
192 "-asynchronous",
193 from_=from_, to=to)
194
195 # make sure add_*_constraint cannot be used again
196 del self.clocks
197 del self.false_paths
198
199 def _constrain(self, platform):
200 # The asynchronous input to a MultiReg is a false path
201 platform.add_platform_command(
202 "set_false_path -quiet "
203 "-to [get_nets -quiet -filter {{mr_ff == TRUE}}]"
204 )
205 # The asychronous reset input to the AsyncResetSynchronizer is a false
206 # path
207 platform.add_platform_command(
208 "set_false_path -quiet "
209 "-to [get_pins -quiet -filter {{REF_PIN_NAME == PRE}} "
210 "-of [get_cells -quiet -filter {{ars_ff1 == TRUE || ars_ff2 == TRUE}}]]"
211 )
212 # clock_period-2ns to resolve metastability on the wire between the
213 # AsyncResetSynchronizer FFs
214 platform.add_platform_command(
215 "set_max_delay 2 -quiet "
216 "-from [get_pins -quiet -filter {{REF_PIN_NAME == Q}} "
217 "-of [get_cells -quiet -filter {{ars_ff1 == TRUE}}]] "
218 "-to [get_pins -quiet -filter {{REF_PIN_NAME == D}} "
219 "-of [get_cells -quiet -filter {{ars_ff2 == TRUE}}]]"
220 )
221
222 def build(self, platform, fragment, build_dir="build", build_name="top",
223 toolchain_path="/opt/Xilinx/Vivado", source=True, run=True,
224 synth_mode="vivado", enable_xpm=False, **kwargs):
225 if toolchain_path is None:
226 toolchain_path = "/opt/Xilinx/Vivado"
227 os.makedirs(build_dir, exist_ok=True)
228 cwd = os.getcwd()
229 os.chdir(build_dir)
230
231 if not isinstance(fragment, _Fragment):
232 fragment = fragment.get_fragment()
233 platform.finalize(fragment)
234 self._convert_clocks(platform)
235 self._constrain(platform)
236 v_output = platform.get_verilog(fragment, name=build_name, **kwargs)
237 named_sc, named_pc = platform.resolve_signals(v_output.ns)
238 v_file = build_name + ".v"
239 v_output.write(v_file)
240 sources = platform.sources | {(v_file, "verilog", "work")}
241 edifs = platform.edifs
242 ips = platform.ips
243 self._build_batch(platform, sources, edifs, ips, build_name, synth_mode, enable_xpm)
244 tools.write_to_file(build_name + ".xdc", _build_xdc(named_sc, named_pc))
245 if run:
246 if synth_mode == "yosys":
247 common._run_yosys(platform.device, sources, platform.verilog_include_paths, build_name)
248 _run_vivado(build_name, toolchain_path, source)
249
250 os.chdir(cwd)
251
252 return v_output.ns
253
254 def add_period_constraint(self, platform, clk, period):
255 if clk in self.clocks:
256 raise ValueError("A period constraint already exists")
257 period = math.floor(period*1e3)/1e3 # round to lowest picosecond
258 self.clocks[clk] = period
259
260 def add_false_path_constraint(self, platform, from_, to):
261 if (to, from_) not in self.false_paths:
262 self.false_paths.add((from_, to))