]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_llvm/build.rs
Rollup merge of #101790 - TaKO8Ki:do-not-suggest-placeholder-to-const-and-static...
[rust.git] / compiler / rustc_llvm / build.rs
1 use std::env;
2 use std::ffi::{OsStr, OsString};
3 use std::fmt::Display;
4 use std::path::{Path, PathBuf};
5 use std::process::{Command, Stdio};
6
7 const OPTIONAL_COMPONENTS: &[&str] = &[
8     "x86",
9     "arm",
10     "aarch64",
11     "amdgpu",
12     "avr",
13     "m68k",
14     "mips",
15     "powerpc",
16     "systemz",
17     "jsbackend",
18     "webassembly",
19     "msp430",
20     "sparc",
21     "nvptx",
22     "hexagon",
23     "riscv",
24     "bpf",
25 ];
26
27 const REQUIRED_COMPONENTS: &[&str] =
28     &["ipo", "bitreader", "bitwriter", "linker", "asmparser", "lto", "coverage", "instrumentation"];
29
30 fn detect_llvm_link() -> (&'static str, &'static str) {
31     // Force the link mode we want, preferring static by default, but
32     // possibly overridden by `configure --enable-llvm-link-shared`.
33     if tracked_env_var_os("LLVM_LINK_SHARED").is_some() {
34         ("dylib", "--link-shared")
35     } else {
36         ("static", "--link-static")
37     }
38 }
39
40 // Because Cargo adds the compiler's dylib path to our library search path, llvm-config may
41 // break: the dylib path for the compiler, as of this writing, contains a copy of the LLVM
42 // shared library, which means that when our freshly built llvm-config goes to load it's
43 // associated LLVM, it actually loads the compiler's LLVM. In particular when building the first
44 // compiler (i.e., in stage 0) that's a problem, as the compiler's LLVM is likely different from
45 // the one we want to use. As such, we restore the environment to what bootstrap saw. This isn't
46 // perfect -- we might actually want to see something from Cargo's added library paths -- but
47 // for now it works.
48 fn restore_library_path() {
49     let key = tracked_env_var_os("REAL_LIBRARY_PATH_VAR").expect("REAL_LIBRARY_PATH_VAR");
50     if let Some(env) = tracked_env_var_os("REAL_LIBRARY_PATH") {
51         env::set_var(&key, &env);
52     } else {
53         env::remove_var(&key);
54     }
55 }
56
57 /// Reads an environment variable and adds it to dependencies.
58 /// Supposed to be used for all variables except those set for build scripts by cargo
59 /// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts>
60 fn tracked_env_var_os<K: AsRef<OsStr> + Display>(key: K) -> Option<OsString> {
61     println!("cargo:rerun-if-env-changed={}", key);
62     env::var_os(key)
63 }
64
65 fn rerun_if_changed_anything_in_dir(dir: &Path) {
66     let mut stack = dir
67         .read_dir()
68         .unwrap()
69         .map(|e| e.unwrap())
70         .filter(|e| &*e.file_name() != ".git")
71         .collect::<Vec<_>>();
72     while let Some(entry) = stack.pop() {
73         let path = entry.path();
74         if entry.file_type().unwrap().is_dir() {
75             stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
76         } else {
77             println!("cargo:rerun-if-changed={}", path.display());
78         }
79     }
80 }
81
82 #[track_caller]
83 fn output(cmd: &mut Command) -> String {
84     let output = match cmd.stderr(Stdio::inherit()).output() {
85         Ok(status) => status,
86         Err(e) => {
87             println!("\n\nfailed to execute command: {:?}\nerror: {}\n\n", cmd, e);
88             std::process::exit(1);
89         }
90     };
91     if !output.status.success() {
92         panic!(
93             "command did not execute successfully: {:?}\n\
94              expected success, got: {}",
95             cmd, output.status
96         );
97     }
98     String::from_utf8(output.stdout).unwrap()
99 }
100
101 fn main() {
102     for component in REQUIRED_COMPONENTS.iter().chain(OPTIONAL_COMPONENTS.iter()) {
103         println!("cargo:rustc-check-cfg=values(llvm_component,\"{}\")", component);
104     }
105
106     if tracked_env_var_os("RUST_CHECK").is_some() {
107         // If we're just running `check`, there's no need for LLVM to be built.
108         return;
109     }
110
111     restore_library_path();
112
113     let target = env::var("TARGET").expect("TARGET was not set");
114     let llvm_config =
115         tracked_env_var_os("LLVM_CONFIG").map(|x| Some(PathBuf::from(x))).unwrap_or_else(|| {
116             if let Some(dir) = tracked_env_var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
117                 let to_test = dir
118                     .parent()
119                     .unwrap()
120                     .parent()
121                     .unwrap()
122                     .join(&target)
123                     .join("llvm/bin/llvm-config");
124                 if Command::new(&to_test).output().is_ok() {
125                     return Some(to_test);
126                 }
127             }
128             None
129         });
130
131     if let Some(llvm_config) = &llvm_config {
132         println!("cargo:rerun-if-changed={}", llvm_config.display());
133     }
134     let llvm_config = llvm_config.unwrap_or_else(|| PathBuf::from("llvm-config"));
135
136     // Test whether we're cross-compiling LLVM. This is a pretty rare case
137     // currently where we're producing an LLVM for a different platform than
138     // what this build script is currently running on.
139     //
140     // In that case, there's no guarantee that we can actually run the target,
141     // so the build system works around this by giving us the LLVM_CONFIG for
142     // the host platform. This only really works if the host LLVM and target
143     // LLVM are compiled the same way, but for us that's typically the case.
144     //
145     // We *want* detect this cross compiling situation by asking llvm-config
146     // what its host-target is. If that's not the TARGET, then we're cross
147     // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
148     // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
149     // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
150     // tricks us into thinking we're doing a cross build when we aren't, so
151     // havoc ensues.
152     //
153     // In any case, if we're cross compiling, this generally just means that we
154     // can't trust all the output of llvm-config because it might be targeted
155     // for the host rather than the target. As a result a bunch of blocks below
156     // are gated on `if !is_crossed`
157     let target = env::var("TARGET").expect("TARGET was not set");
158     let host = env::var("HOST").expect("HOST was not set");
159     let is_crossed = target != host;
160
161     let components = output(Command::new(&llvm_config).arg("--components"));
162     let mut components = components.split_whitespace().collect::<Vec<_>>();
163     components.retain(|c| OPTIONAL_COMPONENTS.contains(c) || REQUIRED_COMPONENTS.contains(c));
164
165     for component in REQUIRED_COMPONENTS {
166         if !components.contains(component) {
167             panic!("require llvm component {} but wasn't found", component);
168         }
169     }
170
171     for component in components.iter() {
172         println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
173     }
174
175     // Link in our own LLVM shims, compiled with the same flags as LLVM
176     let mut cmd = Command::new(&llvm_config);
177     cmd.arg("--cxxflags");
178     let cxxflags = output(&mut cmd);
179     let mut cfg = cc::Build::new();
180     cfg.warnings(false);
181     for flag in cxxflags.split_whitespace() {
182         // Ignore flags like `-m64` when we're doing a cross build
183         if is_crossed && flag.starts_with("-m") {
184             continue;
185         }
186
187         if flag.starts_with("-flto") {
188             continue;
189         }
190
191         // -Wdate-time is not supported by the netbsd cross compiler
192         if is_crossed && target.contains("netbsd") && flag.contains("date-time") {
193             continue;
194         }
195
196         // Include path contains host directory, replace it with target
197         if is_crossed && flag.starts_with("-I") {
198             cfg.flag(&flag.replace(&host, &target));
199             continue;
200         }
201
202         cfg.flag(flag);
203     }
204
205     for component in &components {
206         let mut flag = String::from("LLVM_COMPONENT_");
207         flag.push_str(&component.to_uppercase());
208         cfg.define(&flag, None);
209     }
210
211     if tracked_env_var_os("LLVM_RUSTLLVM").is_some() {
212         cfg.define("LLVM_RUSTLLVM", None);
213     }
214
215     if tracked_env_var_os("LLVM_NDEBUG").is_some() {
216         cfg.define("NDEBUG", None);
217         cfg.debug(false);
218     }
219
220     rerun_if_changed_anything_in_dir(Path::new("llvm-wrapper"));
221     cfg.file("llvm-wrapper/PassWrapper.cpp")
222         .file("llvm-wrapper/RustWrapper.cpp")
223         .file("llvm-wrapper/ArchiveWrapper.cpp")
224         .file("llvm-wrapper/CoverageMappingWrapper.cpp")
225         .file("llvm-wrapper/Linker.cpp")
226         .cpp(true)
227         .cpp_link_stdlib(None) // we handle this below
228         .compile("llvm-wrapper");
229
230     let (llvm_kind, llvm_link_arg) = detect_llvm_link();
231
232     // Link in all LLVM libraries, if we're using the "wrong" llvm-config then
233     // we don't pick up system libs because unfortunately they're for the host
234     // of llvm-config, not the target that we're attempting to link.
235     let mut cmd = Command::new(&llvm_config);
236     cmd.arg(llvm_link_arg).arg("--libs");
237
238     if !is_crossed {
239         cmd.arg("--system-libs");
240     } else if target.contains("windows-gnu") {
241         println!("cargo:rustc-link-lib=shell32");
242         println!("cargo:rustc-link-lib=uuid");
243     } else if target.contains("netbsd") || target.contains("haiku") || target.contains("darwin") {
244         println!("cargo:rustc-link-lib=z");
245     } else if target.starts_with("arm")
246         || target.starts_with("mips-")
247         || target.starts_with("mipsel-")
248         || target.starts_with("powerpc-")
249     {
250         // 32-bit targets need to link libatomic.
251         println!("cargo:rustc-link-lib=atomic");
252     }
253     cmd.args(&components);
254
255     for lib in output(&mut cmd).split_whitespace() {
256         let name = if let Some(stripped) = lib.strip_prefix("-l") {
257             stripped
258         } else if let Some(stripped) = lib.strip_prefix('-') {
259             stripped
260         } else if Path::new(lib).exists() {
261             // On MSVC llvm-config will print the full name to libraries, but
262             // we're only interested in the name part
263             let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
264             name.trim_end_matches(".lib")
265         } else if lib.ends_with(".lib") {
266             // Some MSVC libraries just come up with `.lib` tacked on, so chop
267             // that off
268             lib.trim_end_matches(".lib")
269         } else {
270             continue;
271         };
272
273         // Don't need or want this library, but LLVM's CMake build system
274         // doesn't provide a way to disable it, so filter it here even though we
275         // may or may not have built it. We don't reference anything from this
276         // library and it otherwise may just pull in extra dependencies on
277         // libedit which we don't want
278         if name == "LLVMLineEditor" {
279             continue;
280         }
281
282         let kind = if name.starts_with("LLVM") { llvm_kind } else { "dylib" };
283         println!("cargo:rustc-link-lib={}={}", kind, name);
284     }
285
286     // LLVM ldflags
287     //
288     // If we're a cross-compile of LLVM then unfortunately we can't trust these
289     // ldflags (largely where all the LLVM libs are located). Currently just
290     // hack around this by replacing the host triple with the target and pray
291     // that those -L directories are the same!
292     let mut cmd = Command::new(&llvm_config);
293     cmd.arg(llvm_link_arg).arg("--ldflags");
294     for lib in output(&mut cmd).split_whitespace() {
295         if is_crossed {
296             if let Some(stripped) = lib.strip_prefix("-LIBPATH:") {
297                 println!("cargo:rustc-link-search=native={}", stripped.replace(&host, &target));
298             } else if let Some(stripped) = lib.strip_prefix("-L") {
299                 println!("cargo:rustc-link-search=native={}", stripped.replace(&host, &target));
300             }
301         } else if let Some(stripped) = lib.strip_prefix("-LIBPATH:") {
302             println!("cargo:rustc-link-search=native={}", stripped);
303         } else if let Some(stripped) = lib.strip_prefix("-l") {
304             println!("cargo:rustc-link-lib={}", stripped);
305         } else if let Some(stripped) = lib.strip_prefix("-L") {
306             println!("cargo:rustc-link-search=native={}", stripped);
307         }
308     }
309
310     // Some LLVM linker flags (-L and -l) may be needed even when linking
311     // rustc_llvm, for example when using static libc++, we may need to
312     // manually specify the library search path and -ldl -lpthread as link
313     // dependencies.
314     let llvm_linker_flags = tracked_env_var_os("LLVM_LINKER_FLAGS");
315     if let Some(s) = llvm_linker_flags {
316         for lib in s.into_string().unwrap().split_whitespace() {
317             if let Some(stripped) = lib.strip_prefix("-l") {
318                 println!("cargo:rustc-link-lib={}", stripped);
319             } else if let Some(stripped) = lib.strip_prefix("-L") {
320                 println!("cargo:rustc-link-search=native={}", stripped);
321             }
322         }
323     }
324
325     let llvm_static_stdcpp = tracked_env_var_os("LLVM_STATIC_STDCPP");
326     let llvm_use_libcxx = tracked_env_var_os("LLVM_USE_LIBCXX");
327
328     let stdcppname = if target.contains("openbsd") {
329         if target.contains("sparc64") { "estdc++" } else { "c++" }
330     } else if target.contains("darwin")
331         || target.contains("freebsd")
332         || target.contains("windows-gnullvm")
333     {
334         "c++"
335     } else if target.contains("netbsd") && llvm_static_stdcpp.is_some() {
336         // NetBSD uses a separate library when relocation is required
337         "stdc++_pic"
338     } else if llvm_use_libcxx.is_some() {
339         "c++"
340     } else {
341         "stdc++"
342     };
343
344     // RISC-V GCC erroneously requires libatomic for sub-word
345     // atomic operations. Some BSD uses Clang as its system
346     // compiler and provides no libatomic in its base system so
347     // does not want this.
348     if target.starts_with("riscv") && !target.contains("freebsd") && !target.contains("openbsd") {
349         println!("cargo:rustc-link-lib=atomic");
350     }
351
352     // C++ runtime library
353     if !target.contains("msvc") {
354         if let Some(s) = llvm_static_stdcpp {
355             assert!(!cxxflags.contains("stdlib=libc++"));
356             let path = PathBuf::from(s);
357             println!("cargo:rustc-link-search=native={}", path.parent().unwrap().display());
358             if target.contains("windows") {
359                 println!("cargo:rustc-link-lib=static:-bundle={}", stdcppname);
360             } else {
361                 println!("cargo:rustc-link-lib=static={}", stdcppname);
362             }
363         } else if cxxflags.contains("stdlib=libc++") {
364             println!("cargo:rustc-link-lib=c++");
365         } else {
366             println!("cargo:rustc-link-lib={}", stdcppname);
367         }
368     }
369
370     // Libstdc++ depends on pthread which Rust doesn't link on MinGW
371     // since nothing else requires it.
372     if target.ends_with("windows-gnu") {
373         println!("cargo:rustc-link-lib=static:-bundle=pthread");
374     }
375 }