build_llvm.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (C) 2019 Intel Corporation. All rights reserved.
  4. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  5. #
  6. import argparse
  7. import os
  8. import pathlib
  9. import requests
  10. import shlex
  11. import shutil
  12. import subprocess
  13. import sysconfig
  14. import sys
  15. def clone_llvm(dst_dir, llvm_repo, llvm_branch):
  16. """
  17. any error will raise CallProcessError
  18. """
  19. llvm_dir = dst_dir.joinpath("llvm").resolve()
  20. if not llvm_dir.exists():
  21. GIT_CLONE_CMD = f"git clone --depth 1 --branch {llvm_branch} {llvm_repo} llvm"
  22. print(GIT_CLONE_CMD)
  23. subprocess.check_output(shlex.split(GIT_CLONE_CMD), cwd=dst_dir)
  24. return llvm_dir
  25. def query_llvm_version(llvm_info):
  26. github_token = os.environ['GH_TOKEN']
  27. owner_project = llvm_info['repo'].replace("https://github.com/", "").replace(".git", "")
  28. url = f"https://api.github.com/repos/{owner_project}/commits/{llvm_info['branch']}"
  29. headers = {
  30. 'Authorization': f"Bearer {github_token}"
  31. }
  32. try:
  33. response = requests.request("GET", url, headers=headers, data={})
  34. response.raise_for_status()
  35. except requests.exceptions.HTTPError as error:
  36. print (error) # for debugging purpose
  37. return None
  38. response = response.json()
  39. return response['sha']
  40. def build_llvm(llvm_dir, platform, backends, projects, use_clang=False, extra_flags=''):
  41. LLVM_COMPILE_OPTIONS = [
  42. '-DCMAKE_BUILD_TYPE:STRING="Release"',
  43. "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
  44. "-DLLVM_APPEND_VC_REV:BOOL=ON",
  45. "-DLLVM_BUILD_EXAMPLES:BOOL=OFF",
  46. "-DLLVM_BUILD_LLVM_DYLIB:BOOL=OFF",
  47. "-DLLVM_ENABLE_BINDINGS:BOOL=OFF",
  48. "-DLLVM_ENABLE_IDE:BOOL=OFF",
  49. "-DLLVM_ENABLE_LIBEDIT=OFF",
  50. "-DLLVM_ENABLE_TERMINFO:BOOL=OFF",
  51. "-DLLVM_ENABLE_ZLIB:BOOL=ON",
  52. "-DLLVM_INCLUDE_BENCHMARKS:BOOL=OFF",
  53. "-DLLVM_INCLUDE_DOCS:BOOL=OFF",
  54. "-DLLVM_INCLUDE_EXAMPLES:BOOL=OFF",
  55. "-DLLVM_INCLUDE_UTILS:BOOL=OFF",
  56. "-DLLVM_INCLUDE_TESTS:BOOL=OFF",
  57. "-DLLVM_OPTIMIZED_TABLEGEN:BOOL=ON",
  58. ]
  59. # ccache is not available on Windows
  60. if not "windows" == platform:
  61. LLVM_COMPILE_OPTIONS.append("-DLLVM_CCACHE_BUILD:BOOL=ON")
  62. # perf support is available on Linux only
  63. if "linux" == platform:
  64. LLVM_COMPILE_OPTIONS.append("-DLLVM_USE_PERF:BOOL=ON")
  65. # use clang/clang++/lld. but macos doesn't support lld
  66. if not sys.platform.startswith("darwin") and use_clang:
  67. if shutil.which("clang") and shutil.which("clang++") and shutil.which("lld"):
  68. os.environ["CC"] = "clang"
  69. os.environ["CXX"] = "clang++"
  70. LLVM_COMPILE_OPTIONS.append('-DLLVM_USE_LINKER:STRING="lld"')
  71. print("Use the clang toolchain")
  72. else:
  73. print("Can not find clang, clang++ and lld, keep using the gcc toolchain")
  74. else:
  75. print("Use the gcc toolchain")
  76. LLVM_EXTRA_COMPILE_OPTIONS = {
  77. "arc": [
  78. '-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD:STRING="ARC"',
  79. "-DLLVM_ENABLE_LIBICUUC:BOOL=OFF",
  80. "-DLLVM_ENABLE_LIBICUDATA:BOOL=OFF",
  81. ],
  82. "xtensa": [
  83. '-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD:STRING="Xtensa"',
  84. ],
  85. "windows": [
  86. "-DCMAKE_INSTALL_PREFIX=LLVM-install",
  87. ],
  88. "default": [],
  89. }
  90. LLVM_TARGETS_TO_BUILD = [
  91. '-DLLVM_TARGETS_TO_BUILD:STRING="' + ";".join(backends) + '"'
  92. if backends
  93. else '-DLLVM_TARGETS_TO_BUILD:STRING="AArch64;ARM;Mips;RISCV;X86"'
  94. ]
  95. LLVM_PROJECTS_TO_BUILD = [
  96. '-DLLVM_ENABLE_PROJECTS:STRING="' + ";".join(projects) + '"' if projects else ""
  97. ]
  98. # lldb project requires libxml2
  99. LLVM_LIBXML2_OPTION = [
  100. "-DLLVM_ENABLE_LIBXML2:BOOL=" + ("ON" if "lldb" in projects else "OFF")
  101. ]
  102. # enabling LLVM_INCLUDE_TOOLS will increase ~300M to the final package
  103. LLVM_INCLUDE_TOOLS_OPTION = [
  104. "-DLLVM_INCLUDE_TOOLS:BOOL=ON" if projects else "-DLLVM_INCLUDE_TOOLS:BOOL=OFF"
  105. ]
  106. if not llvm_dir.exists():
  107. raise Exception(f"{llvm_dir} doesn't exist")
  108. build_dir = llvm_dir.joinpath("build").resolve()
  109. build_dir.mkdir(exist_ok=True)
  110. lib_llvm_core_library = build_dir.joinpath("lib/libLLVMCore.a").resolve()
  111. if lib_llvm_core_library.exists():
  112. print(
  113. f"It has already been fully compiled. If want to a re-build, please remove {build_dir} manually and try again"
  114. )
  115. return None
  116. compile_options = " ".join(
  117. LLVM_COMPILE_OPTIONS
  118. + LLVM_LIBXML2_OPTION
  119. + LLVM_EXTRA_COMPILE_OPTIONS.get(
  120. platform, LLVM_EXTRA_COMPILE_OPTIONS["default"]
  121. )
  122. + LLVM_TARGETS_TO_BUILD
  123. + LLVM_PROJECTS_TO_BUILD
  124. + LLVM_INCLUDE_TOOLS_OPTION
  125. )
  126. CONFIG_CMD = f"cmake {compile_options} {extra_flags} ../llvm"
  127. if "windows" == platform:
  128. if "mingw" in sysconfig.get_platform().lower():
  129. CONFIG_CMD += " -G'Unix Makefiles'"
  130. else:
  131. CONFIG_CMD += " -A x64"
  132. else:
  133. CONFIG_CMD += " -G'Ninja'"
  134. print(f"Config command: {CONFIG_CMD}")
  135. subprocess.check_call(shlex.split(CONFIG_CMD), cwd=build_dir)
  136. BUILD_CMD = "cmake --build . --target package" + (
  137. " --config Release" if "windows" == platform else ""
  138. )
  139. if "windows" == platform:
  140. BUILD_CMD += " --parallel " + str(os.cpu_count())
  141. print(f"Build command: {BUILD_CMD}")
  142. subprocess.check_call(shlex.split(BUILD_CMD), cwd=build_dir)
  143. return build_dir
  144. def repackage_llvm(llvm_dir):
  145. build_dir = llvm_dir.joinpath("./build").resolve()
  146. packs = [f for f in build_dir.glob("LLVM-*.tar.gz")]
  147. if len(packs) > 1:
  148. raise Exception("Find more than one LLVM-*.tar.gz")
  149. if not packs:
  150. raise Exception("Didn't find any LLVM-* package")
  151. return
  152. llvm_package = packs[0].name
  153. # mv build/LLVM-*.gz .
  154. shutil.move(str(build_dir.joinpath(llvm_package).resolve()), str(llvm_dir))
  155. # rm -r build
  156. shutil.rmtree(str(build_dir))
  157. # mkdir build
  158. build_dir.mkdir()
  159. # tar xf ./LLVM-*.tar.gz --strip-components=1 --directory=build
  160. CMD = f"tar xf {llvm_dir.joinpath(llvm_package).resolve()} --strip-components=1 --directory={build_dir}"
  161. subprocess.check_call(shlex.split(CMD), cwd=llvm_dir)
  162. # rm ./LLVM-1*.gz
  163. os.remove(llvm_dir.joinpath(llvm_package).resolve())
  164. def repackage_llvm_windows(llvm_dir):
  165. build_dir = llvm_dir.joinpath("./build").resolve()
  166. packs_path = [f for f in build_dir.glob("./_CPack_Packages/win64/NSIS/LLVM-*-win64")]
  167. if len(packs_path) > 1:
  168. raise Exception("Find more than one LLVM-* package")
  169. if not packs_path:
  170. raise Exception("Didn't find any LLVM-* package")
  171. return
  172. llvm_package_path = f"_CPack_Packages/win64/NSIS/{packs_path[0].name}"
  173. windows_package_dir = build_dir.joinpath(llvm_package_path).resolve()
  174. # mv package dir outside of build
  175. shutil.move(str(windows_package_dir), str(llvm_dir))
  176. # rm -r build
  177. shutil.rmtree(str(build_dir))
  178. # mkdir build
  179. build_dir.mkdir()
  180. # move back all the subdiretories under cpack directory(bin/include/lib) to build dir
  181. moved_package_dir = llvm_dir.joinpath(packs_path[0].name)
  182. for sub_dir in moved_package_dir.iterdir():
  183. shutil.move(str(sub_dir), str(build_dir))
  184. moved_package_dir.rmdir()
  185. def main():
  186. parser = argparse.ArgumentParser(description="build necessary LLVM libraries")
  187. parser.add_argument(
  188. "--platform",
  189. type=str,
  190. choices=["android", "arc", "darwin", "linux", "windows", "xtensa"],
  191. help="identify current platform",
  192. )
  193. parser.add_argument(
  194. "--arch",
  195. nargs="+",
  196. type=str,
  197. choices=[
  198. "AArch64",
  199. "ARC",
  200. "ARM",
  201. "Mips",
  202. "RISCV",
  203. "WebAssembly",
  204. "X86",
  205. "Xtensa",
  206. ],
  207. help="identify LLVM supported backends, separate by space, like '--arch ARM Mips X86'",
  208. )
  209. parser.add_argument(
  210. "--project",
  211. nargs="+",
  212. type=str,
  213. default="",
  214. choices=["clang", "lldb"],
  215. help="identify extra LLVM projects, separate by space, like '--project clang lldb'",
  216. )
  217. parser.add_argument(
  218. "--llvm-ver",
  219. action="store_true",
  220. help="return the version info of generated llvm libraries",
  221. )
  222. parser.add_argument(
  223. "--use-clang",
  224. action="store_true",
  225. help="use clang instead of gcc",
  226. )
  227. parser.add_argument(
  228. "--extra-cmake-flags",
  229. type=str,
  230. default="",
  231. help="custom extra cmake flags",
  232. )
  233. options = parser.parse_args()
  234. # if the "platform" is not identified in the command line option,
  235. # detect it
  236. if not options.platform:
  237. if sys.platform.startswith("win32") or sys.platform.startswith("msys"):
  238. platform = "windows"
  239. elif sys.platform.startswith("darwin"):
  240. platform = "darwin"
  241. else:
  242. platform = "linux"
  243. else:
  244. platform = options.platform
  245. llvm_repo_and_branch = {
  246. "arc": {
  247. "repo": "https://github.com/llvm/llvm-project.git",
  248. "repo_ssh": "git@github.com:llvm/llvm-project.git",
  249. "branch": "release/15.x",
  250. },
  251. "xtensa": {
  252. "repo": "https://github.com/espressif/llvm-project.git",
  253. "repo_ssh": "git@github.com:espressif/llvm-project.git",
  254. "branch": "xtensa_release_17.0.1",
  255. },
  256. "default": {
  257. "repo": "https://github.com/llvm/llvm-project.git",
  258. "repo_ssh": "git@github.com:llvm/llvm-project.git",
  259. "branch": "release/15.x",
  260. },
  261. }
  262. # retrieve the real file
  263. current_file = pathlib.Path(__file__)
  264. if current_file.is_symlink():
  265. current_file = pathlib.Path(os.readlink(current_file))
  266. current_dir = current_file.parent.resolve()
  267. deps_dir = current_dir.joinpath("../core/deps").resolve()
  268. try:
  269. llvm_info = llvm_repo_and_branch.get(platform, llvm_repo_and_branch["default"])
  270. if options.llvm_ver:
  271. commit_hash = query_llvm_version(llvm_info)
  272. print(commit_hash)
  273. return commit_hash is not None
  274. repo_addr = llvm_info["repo"]
  275. if os.environ.get('USE_GIT_SSH') == "true":
  276. repo_addr = llvm_info["repo_ssh"]
  277. else:
  278. print("To use ssh for git clone, run: export USE_GIT_SSH=true")
  279. llvm_dir = clone_llvm(deps_dir, repo_addr, llvm_info["branch"])
  280. if (
  281. build_llvm(
  282. llvm_dir, platform, options.arch, options.project, options.use_clang,
  283. options.extra_cmake_flags
  284. )
  285. is not None
  286. ):
  287. # TODO: repackage process may change in the future, this work for LLVM 15.x
  288. if "windows" == platform:
  289. repackage_llvm_windows(llvm_dir)
  290. else:
  291. repackage_llvm(llvm_dir)
  292. return True
  293. except subprocess.CalledProcessError:
  294. return False
  295. if __name__ == "__main__":
  296. sys.exit(0 if main() else 1)