bootstrap/core/config/toml/
rust.rs

1//! This module defines the `Rust` struct, which represents the `[rust]` table
2//! in the `bootstrap.toml` configuration file.
3
4use serde::{Deserialize, Deserializer};
5
6use crate::core::config::toml::TomlConfig;
7use crate::core::config::{DebuginfoLevel, Merge, ReplaceOpt, StringOrBool};
8use crate::{BTreeSet, CodegenBackendKind, HashSet, PathBuf, TargetSelection, define_config, exit};
9
10define_config! {
11    /// TOML representation of how the Rust build is configured.
12    #[derive(Default)]
13    struct Rust {
14        optimize: Option<RustOptimize> = "optimize",
15        debug: Option<bool> = "debug",
16        codegen_units: Option<u32> = "codegen-units",
17        codegen_units_std: Option<u32> = "codegen-units-std",
18        rustc_debug_assertions: Option<bool> = "debug-assertions",
19        randomize_layout: Option<bool> = "randomize-layout",
20        std_debug_assertions: Option<bool> = "debug-assertions-std",
21        tools_debug_assertions: Option<bool> = "debug-assertions-tools",
22        overflow_checks: Option<bool> = "overflow-checks",
23        overflow_checks_std: Option<bool> = "overflow-checks-std",
24        debug_logging: Option<bool> = "debug-logging",
25        debuginfo_level: Option<DebuginfoLevel> = "debuginfo-level",
26        debuginfo_level_rustc: Option<DebuginfoLevel> = "debuginfo-level-rustc",
27        debuginfo_level_std: Option<DebuginfoLevel> = "debuginfo-level-std",
28        debuginfo_level_tools: Option<DebuginfoLevel> = "debuginfo-level-tools",
29        debuginfo_level_tests: Option<DebuginfoLevel> = "debuginfo-level-tests",
30        backtrace: Option<bool> = "backtrace",
31        incremental: Option<bool> = "incremental",
32        default_linker: Option<String> = "default-linker",
33        channel: Option<String> = "channel",
34        musl_root: Option<String> = "musl-root",
35        rpath: Option<bool> = "rpath",
36        strip: Option<bool> = "strip",
37        frame_pointers: Option<bool> = "frame-pointers",
38        stack_protector: Option<String> = "stack-protector",
39        verbose_tests: Option<bool> = "verbose-tests",
40        optimize_tests: Option<bool> = "optimize-tests",
41        codegen_tests: Option<bool> = "codegen-tests",
42        omit_git_hash: Option<bool> = "omit-git-hash",
43        dist_src: Option<bool> = "dist-src",
44        save_toolstates: Option<String> = "save-toolstates",
45        codegen_backends: Option<Vec<String>> = "codegen-backends",
46        llvm_bitcode_linker: Option<bool> = "llvm-bitcode-linker",
47        lld: Option<bool> = "lld",
48        lld_mode: Option<LldMode> = "use-lld",
49        llvm_tools: Option<bool> = "llvm-tools",
50        deny_warnings: Option<bool> = "deny-warnings",
51        backtrace_on_ice: Option<bool> = "backtrace-on-ice",
52        verify_llvm_ir: Option<bool> = "verify-llvm-ir",
53        thin_lto_import_instr_limit: Option<u32> = "thin-lto-import-instr-limit",
54        remap_debuginfo: Option<bool> = "remap-debuginfo",
55        jemalloc: Option<bool> = "jemalloc",
56        test_compare_mode: Option<bool> = "test-compare-mode",
57        llvm_libunwind: Option<String> = "llvm-libunwind",
58        control_flow_guard: Option<bool> = "control-flow-guard",
59        ehcont_guard: Option<bool> = "ehcont-guard",
60        new_symbol_mangling: Option<bool> = "new-symbol-mangling",
61        profile_generate: Option<String> = "profile-generate",
62        profile_use: Option<String> = "profile-use",
63        // ignored; this is set from an env var set by bootstrap.py
64        download_rustc: Option<StringOrBool> = "download-rustc",
65        lto: Option<String> = "lto",
66        validate_mir_opts: Option<u32> = "validate-mir-opts",
67        std_features: Option<BTreeSet<String>> = "std-features",
68    }
69}
70
71/// LLD in bootstrap works like this:
72/// - Self-contained lld: use `rust-lld` from the compiler's sysroot
73/// - External: use an external `lld` binary
74///
75/// It is configured depending on the target:
76/// 1) Everything except MSVC
77/// - Self-contained: `-Clinker-flavor=gnu-lld-cc -Clink-self-contained=+linker`
78/// - External: `-Clinker-flavor=gnu-lld-cc`
79/// 2) MSVC
80/// - Self-contained: `-Clinker=<path to rust-lld>`
81/// - External: `-Clinker=lld`
82#[derive(Copy, Clone, Default, Debug, PartialEq)]
83pub enum LldMode {
84    /// Do not use LLD
85    #[default]
86    Unused,
87    /// Use `rust-lld` from the compiler's sysroot
88    SelfContained,
89    /// Use an externally provided `lld` binary.
90    /// Note that the linker name cannot be overridden, the binary has to be named `lld` and it has
91    /// to be in $PATH.
92    External,
93}
94
95impl LldMode {
96    pub fn is_used(&self) -> bool {
97        match self {
98            LldMode::SelfContained | LldMode::External => true,
99            LldMode::Unused => false,
100        }
101    }
102}
103
104impl<'de> Deserialize<'de> for LldMode {
105    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
106    where
107        D: Deserializer<'de>,
108    {
109        struct LldModeVisitor;
110
111        impl serde::de::Visitor<'_> for LldModeVisitor {
112            type Value = LldMode;
113
114            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115                formatter.write_str("one of true, 'self-contained' or 'external'")
116            }
117
118            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
119            where
120                E: serde::de::Error,
121            {
122                Ok(if v { LldMode::External } else { LldMode::Unused })
123            }
124
125            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
126            where
127                E: serde::de::Error,
128            {
129                match v {
130                    "external" => Ok(LldMode::External),
131                    "self-contained" => Ok(LldMode::SelfContained),
132                    _ => Err(E::custom(format!("unknown mode {v}"))),
133                }
134            }
135        }
136
137        deserializer.deserialize_any(LldModeVisitor)
138    }
139}
140
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub enum RustOptimize {
143    String(String),
144    Int(u8),
145    Bool(bool),
146}
147
148impl Default for RustOptimize {
149    fn default() -> RustOptimize {
150        RustOptimize::Bool(false)
151    }
152}
153
154impl<'de> Deserialize<'de> for RustOptimize {
155    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
156    where
157        D: Deserializer<'de>,
158    {
159        deserializer.deserialize_any(OptimizeVisitor)
160    }
161}
162
163struct OptimizeVisitor;
164
165impl serde::de::Visitor<'_> for OptimizeVisitor {
166    type Value = RustOptimize;
167
168    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        formatter.write_str(r#"one of: 0, 1, 2, 3, "s", "z", true, false"#)
170    }
171
172    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
173    where
174        E: serde::de::Error,
175    {
176        if matches!(value, "s" | "z") {
177            Ok(RustOptimize::String(value.to_string()))
178        } else {
179            Err(serde::de::Error::custom(format_optimize_error_msg(value)))
180        }
181    }
182
183    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
184    where
185        E: serde::de::Error,
186    {
187        if matches!(value, 0..=3) {
188            Ok(RustOptimize::Int(value as u8))
189        } else {
190            Err(serde::de::Error::custom(format_optimize_error_msg(value)))
191        }
192    }
193
194    fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
195    where
196        E: serde::de::Error,
197    {
198        Ok(RustOptimize::Bool(value))
199    }
200}
201
202fn format_optimize_error_msg(v: impl std::fmt::Display) -> String {
203    format!(
204        r#"unrecognized option for rust optimize: "{v}", expected one of 0, 1, 2, 3, "s", "z", true, false"#
205    )
206}
207
208impl RustOptimize {
209    pub(crate) fn is_release(&self) -> bool {
210        match &self {
211            RustOptimize::Bool(true) | RustOptimize::String(_) => true,
212            RustOptimize::Int(i) => *i > 0,
213            RustOptimize::Bool(false) => false,
214        }
215    }
216
217    pub(crate) fn get_opt_level(&self) -> Option<String> {
218        match &self {
219            RustOptimize::String(s) => Some(s.clone()),
220            RustOptimize::Int(i) => Some(i.to_string()),
221            RustOptimize::Bool(_) => None,
222        }
223    }
224}
225
226/// Compares the current Rust options against those in the CI rustc builder and detects any incompatible options.
227/// It does this by destructuring the `Rust` instance to make sure every `Rust` field is covered and not missing.
228pub fn check_incompatible_options_for_ci_rustc(
229    host: TargetSelection,
230    current_config_toml: TomlConfig,
231    ci_config_toml: TomlConfig,
232) -> Result<(), String> {
233    macro_rules! err {
234        ($current:expr, $expected:expr, $config_section:expr) => {
235            if let Some(current) = &$current {
236                if Some(current) != $expected.as_ref() {
237                    return Err(format!(
238                        "ERROR: Setting `{}` is incompatible with `rust.download-rustc`. \
239                        Current value: {:?}, Expected value(s): {}{:?}",
240                        format!("{}.{}", $config_section, stringify!($expected).replace("_", "-")),
241                        $current,
242                        if $expected.is_some() { "None/" } else { "" },
243                        $expected,
244                    ));
245                };
246            };
247        };
248    }
249
250    macro_rules! warn {
251        ($current:expr, $expected:expr, $config_section:expr) => {
252            if let Some(current) = &$current {
253                if Some(current) != $expected.as_ref() {
254                    println!(
255                        "WARNING: `{}` has no effect with `rust.download-rustc`. \
256                        Current value: {:?}, Expected value(s): {}{:?}",
257                        format!("{}.{}", $config_section, stringify!($expected).replace("_", "-")),
258                        $current,
259                        if $expected.is_some() { "None/" } else { "" },
260                        $expected,
261                    );
262                };
263            };
264        };
265    }
266
267    let current_profiler = current_config_toml.build.as_ref().and_then(|b| b.profiler);
268    let profiler = ci_config_toml.build.as_ref().and_then(|b| b.profiler);
269    err!(current_profiler, profiler, "build");
270
271    let current_optimized_compiler_builtins =
272        current_config_toml.build.as_ref().and_then(|b| b.optimized_compiler_builtins.clone());
273    let optimized_compiler_builtins =
274        ci_config_toml.build.as_ref().and_then(|b| b.optimized_compiler_builtins.clone());
275    err!(current_optimized_compiler_builtins, optimized_compiler_builtins, "build");
276
277    // We always build the in-tree compiler on cross targets, so we only care
278    // about the host target here.
279    let host_str = host.to_string();
280    if let Some(current_cfg) = current_config_toml.target.as_ref().and_then(|c| c.get(&host_str))
281        && current_cfg.profiler.is_some()
282    {
283        let ci_target_toml = ci_config_toml.target.as_ref().and_then(|c| c.get(&host_str));
284        let ci_cfg = ci_target_toml.ok_or(format!(
285            "Target specific config for '{host_str}' is not present for CI-rustc"
286        ))?;
287
288        let profiler = &ci_cfg.profiler;
289        err!(current_cfg.profiler, profiler, "build");
290
291        let optimized_compiler_builtins = &ci_cfg.optimized_compiler_builtins;
292        err!(current_cfg.optimized_compiler_builtins, optimized_compiler_builtins, "build");
293    }
294
295    let (Some(current_rust_config), Some(ci_rust_config)) =
296        (current_config_toml.rust, ci_config_toml.rust)
297    else {
298        return Ok(());
299    };
300
301    let Rust {
302        // Following options are the CI rustc incompatible ones.
303        optimize,
304        randomize_layout,
305        debug_logging,
306        debuginfo_level_rustc,
307        llvm_tools,
308        llvm_bitcode_linker,
309        lto,
310        stack_protector,
311        strip,
312        lld_mode,
313        jemalloc,
314        rpath,
315        channel,
316        default_linker,
317        std_features,
318
319        // Rest of the options can simply be ignored.
320        incremental: _,
321        debug: _,
322        codegen_units: _,
323        codegen_units_std: _,
324        rustc_debug_assertions: _,
325        std_debug_assertions: _,
326        tools_debug_assertions: _,
327        overflow_checks: _,
328        overflow_checks_std: _,
329        debuginfo_level: _,
330        debuginfo_level_std: _,
331        debuginfo_level_tools: _,
332        debuginfo_level_tests: _,
333        backtrace: _,
334        musl_root: _,
335        verbose_tests: _,
336        optimize_tests: _,
337        codegen_tests: _,
338        omit_git_hash: _,
339        dist_src: _,
340        save_toolstates: _,
341        codegen_backends: _,
342        lld: _,
343        deny_warnings: _,
344        backtrace_on_ice: _,
345        verify_llvm_ir: _,
346        thin_lto_import_instr_limit: _,
347        remap_debuginfo: _,
348        test_compare_mode: _,
349        llvm_libunwind: _,
350        control_flow_guard: _,
351        ehcont_guard: _,
352        new_symbol_mangling: _,
353        profile_generate: _,
354        profile_use: _,
355        download_rustc: _,
356        validate_mir_opts: _,
357        frame_pointers: _,
358    } = ci_rust_config;
359
360    // There are two kinds of checks for CI rustc incompatible options:
361    //    1. Checking an option that may change the compiler behaviour/output.
362    //    2. Checking an option that have no effect on the compiler behaviour/output.
363    //
364    // If the option belongs to the first category, we call `err` macro for a hard error;
365    // otherwise, we just print a warning with `warn` macro.
366
367    err!(current_rust_config.optimize, optimize, "rust");
368    err!(current_rust_config.randomize_layout, randomize_layout, "rust");
369    err!(current_rust_config.debug_logging, debug_logging, "rust");
370    err!(current_rust_config.debuginfo_level_rustc, debuginfo_level_rustc, "rust");
371    err!(current_rust_config.rpath, rpath, "rust");
372    err!(current_rust_config.strip, strip, "rust");
373    err!(current_rust_config.lld_mode, lld_mode, "rust");
374    err!(current_rust_config.llvm_tools, llvm_tools, "rust");
375    err!(current_rust_config.llvm_bitcode_linker, llvm_bitcode_linker, "rust");
376    err!(current_rust_config.jemalloc, jemalloc, "rust");
377    err!(current_rust_config.default_linker, default_linker, "rust");
378    err!(current_rust_config.stack_protector, stack_protector, "rust");
379    err!(current_rust_config.lto, lto, "rust");
380    err!(current_rust_config.std_features, std_features, "rust");
381
382    warn!(current_rust_config.channel, channel, "rust");
383
384    Ok(())
385}
386
387pub(crate) const BUILTIN_CODEGEN_BACKENDS: &[&str] = &["llvm", "cranelift", "gcc"];
388
389pub(crate) fn parse_codegen_backends(
390    backends: Vec<String>,
391    section: &str,
392) -> Vec<CodegenBackendKind> {
393    const CODEGEN_BACKEND_PREFIX: &str = "rustc_codegen_";
394
395    let mut found_backends = vec![];
396    for backend in &backends {
397        if let Some(stripped) = backend.strip_prefix(CODEGEN_BACKEND_PREFIX) {
398            panic!(
399                "Invalid value '{backend}' for '{section}.codegen-backends'. \
400                Codegen backends are defined without the '{CODEGEN_BACKEND_PREFIX}' prefix. \
401                Please, use '{stripped}' instead."
402            )
403        }
404        if !BUILTIN_CODEGEN_BACKENDS.contains(&backend.as_str()) {
405            println!(
406                "HELP: '{backend}' for '{section}.codegen-backends' might fail. \
407                List of known codegen backends: {BUILTIN_CODEGEN_BACKENDS:?}"
408            );
409        }
410        let backend = match backend.as_str() {
411            "llvm" => CodegenBackendKind::Llvm,
412            "cranelift" => CodegenBackendKind::Cranelift,
413            "gcc" => CodegenBackendKind::Gcc,
414            backend => CodegenBackendKind::Custom(backend.to_string()),
415        };
416        found_backends.push(backend);
417    }
418    if found_backends.is_empty() {
419        eprintln!("ERROR: `{section}.codegen-backends` should not be set to `[]`");
420        exit!(1);
421    }
422    found_backends
423}
424
425#[cfg(not(test))]
426pub fn default_lld_opt_in_targets() -> Vec<String> {
427    vec!["x86_64-unknown-linux-gnu".to_string()]
428}
429
430#[cfg(test)]
431thread_local! {
432    static TEST_LLD_OPT_IN_TARGETS: std::cell::RefCell<Option<Vec<String>>> = std::cell::RefCell::new(None);
433}
434
435#[cfg(test)]
436pub fn default_lld_opt_in_targets() -> Vec<String> {
437    TEST_LLD_OPT_IN_TARGETS.with(|cell| cell.borrow().clone()).unwrap_or_default()
438}
439
440#[cfg(test)]
441pub fn with_lld_opt_in_targets<R>(targets: Vec<String>, f: impl FnOnce() -> R) -> R {
442    TEST_LLD_OPT_IN_TARGETS.with(|cell| {
443        let prev = cell.replace(Some(targets));
444        let result = f();
445        cell.replace(prev);
446        result
447    })
448}