build_llvm.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. experimental_backends = ["ARC", "Xtensa"]
  91. normal_backends = [s for s in backends if s not in experimental_backends]
  92. LLVM_TARGETS_TO_BUILD = [
  93. '-DLLVM_TARGETS_TO_BUILD:STRING="' + ";".join(normal_backends) + '"'
  94. if normal_backends
  95. else '-DLLVM_TARGETS_TO_BUILD:STRING="AArch64;ARM;Mips;RISCV;X86"'
  96. ]
  97. # if not on ARC platform, but want to add expeirmental backend ARC as target
  98. if platform != "ARC" and "ARC" in backends:
  99. LLVM_TARGETS_TO_BUILD.extend(
  100. LLVM_EXTRA_COMPILE_OPTIONS["arc"]
  101. )
  102. LLVM_PROJECTS_TO_BUILD = [
  103. '-DLLVM_ENABLE_PROJECTS:STRING="' + ";".join(projects) + '"' if projects else ""
  104. ]
  105. # lldb project requires libxml2
  106. LLVM_LIBXML2_OPTION = [
  107. "-DLLVM_ENABLE_LIBXML2:BOOL=" + ("ON" if "lldb" in projects else "OFF")
  108. ]
  109. # enabling LLVM_INCLUDE_TOOLS will increase ~300M to the final package
  110. LLVM_INCLUDE_TOOLS_OPTION = [
  111. "-DLLVM_INCLUDE_TOOLS:BOOL=ON" if projects else "-DLLVM_INCLUDE_TOOLS:BOOL=OFF"
  112. ]
  113. if not llvm_dir.exists():
  114. raise Exception(f"{llvm_dir} doesn't exist")
  115. build_dir = llvm_dir.joinpath("build").resolve()
  116. build_dir.mkdir(exist_ok=True)
  117. lib_llvm_core_library = build_dir.joinpath("lib/libLLVMCore.a").resolve()
  118. if lib_llvm_core_library.exists():
  119. print(
  120. f"It has already been fully compiled. If want to a re-build, please remove {build_dir} manually and try again"
  121. )
  122. return None
  123. compile_options = " ".join(
  124. LLVM_COMPILE_OPTIONS
  125. + LLVM_LIBXML2_OPTION
  126. + LLVM_EXTRA_COMPILE_OPTIONS.get(
  127. platform, LLVM_EXTRA_COMPILE_OPTIONS["default"]
  128. )
  129. + LLVM_TARGETS_TO_BUILD
  130. + LLVM_PROJECTS_TO_BUILD
  131. + LLVM_INCLUDE_TOOLS_OPTION
  132. )
  133. CONFIG_CMD = f"cmake {compile_options} {extra_flags} ../llvm"
  134. if "windows" == platform:
  135. if "mingw" in sysconfig.get_platform().lower():
  136. CONFIG_CMD += " -G'Unix Makefiles'"
  137. else:
  138. CONFIG_CMD += " -A x64"
  139. else:
  140. CONFIG_CMD += " -G'Ninja'"
  141. print(f"Config command: {CONFIG_CMD}")
  142. subprocess.check_call(shlex.split(CONFIG_CMD), cwd=build_dir)
  143. BUILD_CMD = "cmake --build . --target package" + (
  144. " --config Release" if "windows" == platform else ""
  145. )
  146. if "windows" == platform:
  147. BUILD_CMD += " --parallel " + str(os.cpu_count())
  148. print(f"Build command: {BUILD_CMD}")
  149. subprocess.check_call(shlex.split(BUILD_CMD), cwd=build_dir)
  150. return build_dir
  151. def repackage_llvm(llvm_dir):
  152. build_dir = llvm_dir.joinpath("./build").resolve()
  153. packs = [f for f in build_dir.glob("LLVM-*.tar.gz")]
  154. if len(packs) > 1:
  155. raise Exception("Find more than one LLVM-*.tar.gz")
  156. if not packs:
  157. raise Exception("Didn't find any LLVM-* package")
  158. return
  159. llvm_package = packs[0].name
  160. # mv build/LLVM-*.gz .
  161. shutil.move(str(build_dir.joinpath(llvm_package).resolve()), str(llvm_dir))
  162. # rm -r build
  163. shutil.rmtree(str(build_dir))
  164. # mkdir build
  165. build_dir.mkdir()
  166. # tar xf ./LLVM-*.tar.gz --strip-components=1 --directory=build
  167. CMD = f"tar xf {llvm_dir.joinpath(llvm_package).resolve()} --strip-components=1 --directory={build_dir}"
  168. subprocess.check_call(shlex.split(CMD), cwd=llvm_dir)
  169. # rm ./LLVM-1*.gz
  170. os.remove(llvm_dir.joinpath(llvm_package).resolve())
  171. def repackage_llvm_windows(llvm_dir):
  172. build_dir = llvm_dir.joinpath("./build").resolve()
  173. packs_path = [f for f in build_dir.glob("./_CPack_Packages/win64/NSIS/LLVM-*-win64")]
  174. if len(packs_path) > 1:
  175. raise Exception("Find more than one LLVM-* package")
  176. if not packs_path:
  177. raise Exception("Didn't find any LLVM-* package")
  178. return
  179. llvm_package_path = f"_CPack_Packages/win64/NSIS/{packs_path[0].name}"
  180. windows_package_dir = build_dir.joinpath(llvm_package_path).resolve()
  181. # mv package dir outside of build
  182. shutil.move(str(windows_package_dir), str(llvm_dir))
  183. # rm -r build
  184. shutil.rmtree(str(build_dir))
  185. # mkdir build
  186. build_dir.mkdir()
  187. # move back all the subdiretories under cpack directory(bin/include/lib) to build dir
  188. moved_package_dir = llvm_dir.joinpath(packs_path[0].name)
  189. for sub_dir in moved_package_dir.iterdir():
  190. shutil.move(str(sub_dir), str(build_dir))
  191. moved_package_dir.rmdir()
  192. def main():
  193. parser = argparse.ArgumentParser(description="build necessary LLVM libraries")
  194. parser.add_argument(
  195. "--platform",
  196. type=str,
  197. choices=["android", "arc", "darwin", "linux", "windows", "xtensa"],
  198. help="identify current platform",
  199. )
  200. parser.add_argument(
  201. "--arch",
  202. nargs="+",
  203. type=str,
  204. choices=[
  205. "AArch64",
  206. "ARC",
  207. "ARM",
  208. "Mips",
  209. "RISCV",
  210. "WebAssembly",
  211. "X86",
  212. "Xtensa",
  213. ],
  214. default=[],
  215. help="identify LLVM supported backends, separate by space, like '--arch ARM Mips X86'",
  216. )
  217. parser.add_argument(
  218. "--project",
  219. nargs="+",
  220. type=str,
  221. default="",
  222. choices=["clang", "lldb"],
  223. help="identify extra LLVM projects, separate by space, like '--project clang lldb'",
  224. )
  225. parser.add_argument(
  226. "--llvm-ver",
  227. action="store_true",
  228. help="return the version info of generated llvm libraries",
  229. )
  230. parser.add_argument(
  231. "--use-clang",
  232. action="store_true",
  233. help="use clang instead of gcc",
  234. )
  235. parser.add_argument(
  236. "--extra-cmake-flags",
  237. type=str,
  238. default="",
  239. help="custom extra cmake flags",
  240. )
  241. options = parser.parse_args()
  242. # if the "platform" is not identified in the command line option,
  243. # detect it
  244. if not options.platform:
  245. if sys.platform.startswith("win32") or sys.platform.startswith("msys"):
  246. platform = "windows"
  247. elif sys.platform.startswith("darwin"):
  248. platform = "darwin"
  249. else:
  250. platform = "linux"
  251. else:
  252. platform = options.platform
  253. llvm_repo_and_branch = {
  254. "arc": {
  255. "repo": "https://github.com/llvm/llvm-project.git",
  256. "repo_ssh": "git@github.com:llvm/llvm-project.git",
  257. "branch": "release/18.x",
  258. },
  259. "xtensa": {
  260. "repo": "https://github.com/espressif/llvm-project.git",
  261. "repo_ssh": "git@github.com:espressif/llvm-project.git",
  262. "branch": "xtensa_release_18.1.2",
  263. },
  264. "default": {
  265. "repo": "https://github.com/llvm/llvm-project.git",
  266. "repo_ssh": "git@github.com:llvm/llvm-project.git",
  267. "branch": "release/18.x",
  268. },
  269. }
  270. # retrieve the real file
  271. current_file = pathlib.Path(__file__)
  272. if current_file.is_symlink():
  273. current_file = pathlib.Path(os.readlink(current_file))
  274. current_dir = current_file.parent.resolve()
  275. deps_dir = current_dir.joinpath("../core/deps").resolve()
  276. try:
  277. llvm_info = llvm_repo_and_branch.get(platform, llvm_repo_and_branch["default"])
  278. if options.llvm_ver:
  279. commit_hash = query_llvm_version(llvm_info)
  280. print(commit_hash)
  281. return commit_hash is not None
  282. repo_addr = llvm_info["repo"]
  283. if os.environ.get('USE_GIT_SSH') == "true":
  284. repo_addr = llvm_info["repo_ssh"]
  285. else:
  286. print("To use ssh for git clone, run: export USE_GIT_SSH=true")
  287. llvm_dir = clone_llvm(deps_dir, repo_addr, llvm_info["branch"])
  288. if (
  289. build_llvm(
  290. llvm_dir, platform, options.arch, options.project, options.use_clang,
  291. options.extra_cmake_flags
  292. )
  293. is not None
  294. ):
  295. # TODO: repackage process may change in the future, this work for LLVM 15.x
  296. if "windows" == platform:
  297. repackage_llvm_windows(llvm_dir)
  298. else:
  299. repackage_llvm(llvm_dir)
  300. return True
  301. except subprocess.CalledProcessError:
  302. return False
  303. if __name__ == "__main__":
  304. sys.exit(0 if main() else 1)