Merge pull request #24 from mithro/vivado-mor1k-fix
[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, ver)
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 "no_shreg_extract": None
79 }
80
81 def __init__(self):
82 self.bitstream_commands = []
83 self.additional_commands = []
84 self.pre_synthesis_commands = []
85 self.with_phys_opt = False
86 self.clocks = dict()
87 self.false_paths = set()
88
89 def _build_batch(self, platform, sources, build_name):
90 tcl = []
91 for filename, language, library in sources:
92 filename_tcl = "{" + filename + "}"
93 tcl.append("add_files " + filename_tcl)
94 if language == "vhdl":
95 tcl.append("set_property library {} [get_files {}]"
96 .format(library, filename_tcl))
97
98 tcl.append("read_xdc {}.xdc".format(build_name))
99 tcl.extend(c.format(build_name=build_name) for c in self.pre_synthesis_commands)
100 if platform.verilog_include_paths:
101 synth_design_extra = "-include_dirs {{{}}}".format(" ".join(platform.verilog_include_paths))
102 else:
103 synth_design_extra = ""
104 tcl.append("synth_design -top {} -part {} {}".format(build_name, platform.device, synth_design_extra))
105 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_synth.rpt".format(build_name))
106 tcl.append("report_utilization -file {}_utilization_synth.rpt".format(build_name))
107 tcl.append("place_design")
108 if self.with_phys_opt:
109 tcl.append("phys_opt_design -directive AddRetime")
110 tcl.append("report_utilization -hierarchical -file {}_utilization_hierarchical_place.rpt".format(build_name))
111 tcl.append("report_utilization -file {}_utilization_place.rpt".format(build_name))
112 tcl.append("report_io -file {}_io.rpt".format(build_name))
113 tcl.append("report_control_sets -verbose -file {}_control_sets.rpt".format(build_name))
114 tcl.append("report_clock_utilization -file {}_clock_utilization.rpt".format(build_name))
115 tcl.append("route_design")
116 tcl.append("report_route_status -file {}_route_status.rpt".format(build_name))
117 tcl.append("report_drc -file {}_drc.rpt".format(build_name))
118 tcl.append("report_timing_summary -datasheet -max_paths 10 -file {}_timing.rpt".format(build_name))
119 tcl.append("report_power -file {}_power.rpt".format(build_name))
120 for bitstream_command in self.bitstream_commands:
121 tcl.append(bitstream_command.format(build_name=build_name))
122 tcl.append("write_bitstream -force {}.bit ".format(build_name))
123 for additional_command in self.additional_commands:
124 tcl.append(additional_command.format(build_name=build_name))
125 tcl.append("quit")
126 tools.write_to_file(build_name + ".tcl", "\n".join(tcl))
127
128 def _convert_clocks(self, platform):
129 for clk, period in sorted(self.clocks.items(), key=lambda x: x[0].duid):
130 platform.add_platform_command(
131 "create_clock -name {clk} -period " + str(period) +
132 " [get_nets {clk}]", clk=clk)
133 for from_, to in sorted(self.false_paths,
134 key=lambda x: (x[0].duid, x[1].duid)):
135 if (from_ not in self.clocks
136 or to not in self.clocks):
137 raise ValueError("Vivado requires period "
138 "constraints on all clocks used in false paths")
139 platform.add_platform_command(
140 "set_false_path -from [get_clocks {from_}] -to [get_clocks {to}]",
141 from_=from_, to=to)
142
143 # make sure add_*_constraint cannot be used again
144 del self.clocks
145 del self.false_paths
146
147 def build(self, platform, fragment, build_dir="build", build_name="top",
148 toolchain_path=None, source=True, run=True, **kwargs):
149 if toolchain_path is None:
150 if sys.platform == "win32":
151 toolchain_path = "C:\\Xilinx\\Vivado"
152 elif sys.platform == "cygwin":
153 toolchain_path = "/cygdrive/c/Xilinx/Vivado"
154 else:
155 toolchain_path = "/opt/Xilinx/Vivado"
156 os.makedirs(build_dir, exist_ok=True)
157 cwd = os.getcwd()
158 os.chdir(build_dir)
159
160 if not isinstance(fragment, _Fragment):
161 fragment = fragment.get_fragment()
162 platform.finalize(fragment)
163 self._convert_clocks(platform)
164 v_output = platform.get_verilog(fragment, name=build_name, **kwargs)
165 named_sc, named_pc = platform.resolve_signals(v_output.ns)
166 v_file = build_name + ".v"
167 v_output.write(v_file)
168 sources = platform.sources | {(v_file, "verilog", "work")}
169 self._build_batch(platform, sources, build_name)
170 tools.write_to_file(build_name + ".xdc", _build_xdc(named_sc, named_pc))
171 if run:
172 _run_vivado(build_name, toolchain_path, source)
173
174 os.chdir(cwd)
175
176 return v_output.ns
177
178 def add_period_constraint(self, platform, clk, period):
179 if clk in self.clocks:
180 raise ValueError("A period constraint already exists")
181 self.clocks[clk] = period
182
183 def add_false_path_constraint(self, platform, from_, to):
184 self.false_paths.add((from_, to))