Skip to main content

rustc_interface/
util.rs

1use std::any::Any;
2use std::collections::BTreeMap;
3use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
4use std::path::{Path, PathBuf};
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, OnceLock};
7use std::{env, thread};
8
9use rand::{RngCore, rng};
10use rustc_ast as ast;
11use rustc_attr_parsing::ShouldEmit;
12use rustc_codegen_ssa::back::archive::{ArArchiveBuilderBuilder, ArchiveBuilderBuilder};
13use rustc_codegen_ssa::back::link::link_binary;
14use rustc_codegen_ssa::target_features::internal_target_features;
15use rustc_codegen_ssa::traits::CodegenBackend;
16use rustc_codegen_ssa::{CompiledModules, CrateInfo, TargetConfig};
17use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
18use rustc_data_structures::jobserver::Proxy;
19use rustc_data_structures::sync;
20use rustc_metadata::{DylibError, EncodedMetadata, load_symbol_from_dylib};
21use rustc_middle::dep_graph::WorkProductMap;
22use rustc_middle::ty::{CurrentGcx, TyCtxt};
23use rustc_query_impl::{CollectActiveJobsKind, collect_active_query_jobs};
24pub use rustc_session::config::DEFAULT_STACK_SIZE;
25use rustc_session::config::{
26    Cfg, Jobs, OptionsTargetModifiers, OutFileName, OutputFilenames, OutputTypes, Sysroot,
27    host_tuple,
28};
29use rustc_session::{EarlyDiagCtxt, EarlySession, IncrCompSession, Session, filesearch};
30use rustc_span::edition::Edition;
31use rustc_span::source_map::SourceMapInputs;
32use rustc_span::{SessionGlobals, Symbol, sym};
33use rustc_structures::CrateType;
34use rustc_target::spec::{Arch, Target};
35use tracing::info;
36
37use crate::diagnostics;
38use crate::passes::parse_crate_name;
39
40/// Function pointer type that constructs a new CodegenBackend.
41type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
42
43/// Adds `cfg` values based on the current target configuration (in particular for target features).
44///
45/// This is performed by checking whether a set of permitted features
46/// is available on the target machine, by querying the `TargetConfig` from the codegen backend.
47pub(crate) fn add_configuration(
48    cfg: &mut Cfg,
49    target_config: &TargetConfig,
50    target: &Target,
51    is_nightly_build: bool,
52    is_crt_static: bool,
53) {
54    // Add some of the target features to `cfg`.
55    cfg.extend(
56        target
57            .rust_target_features()
58            .iter()
59            .filter_map(|(feature, stab, _)| {
60                if stab.in_cfg()
61                    && (is_nightly_build || stab.requires_nightly(/* in_cfg */ true).is_none())
62                {
63                    Some(Symbol::intern(feature))
64                } else {
65                    None
66                }
67            })
68            .filter(|feature| target_config.internal_target_features.contains(&feature))
69            .map(|feature| (sym::target_feature, Some(feature))),
70    );
71
72    if target_config.has_reliable_f16 {
73        cfg.insert((sym::target_has_reliable_f16, None));
74    }
75    if target_config.has_reliable_f16_math {
76        cfg.insert((sym::target_has_reliable_f16_math, None));
77    }
78    if target_config.has_reliable_f16b {
79        cfg.insert((sym::target_has_reliable_f16b, None));
80    }
81    if target_config.has_reliable_f128 {
82        cfg.insert((sym::target_has_reliable_f128, None));
83    }
84    if target_config.has_reliable_f128_math {
85        cfg.insert((sym::target_has_reliable_f128_math, None));
86    }
87
88    if is_crt_static {
89        cfg.insert((sym::target_feature, Some(sym::crt_dash_static)));
90    }
91}
92
93/// Populates the target modifier database based on the current target.
94pub(crate) fn add_target_modifiers(
95    tmod: &mut BTreeMap<OptionsTargetModifiers, String>,
96    target_config: &TargetConfig,
97    target: &Target,
98) {
99    // Record relevant target features as target modifier.
100    // Join all target-modifier target features into a single comma-separated string,
101    // sorted by the order they appear in in `rust_target_features`.
102    let target_feature_modifier = target
103        .rust_target_features()
104        .iter()
105        .filter(|(_, stab, _)| stab.is_target_modifier())
106        .map(|(feature, ..)| *feature)
107        .filter(|feature| target_config.internal_target_features.contains(&Symbol::intern(feature)))
108        .collect::<Vec<_>>()
109        .join(",");
110    tmod.insert(OptionsTargetModifiers::TargetFeatures, target_feature_modifier);
111}
112
113/// Ensures that all target features required by the ABI are present.
114/// Must be called after `internal_target_features` has been populated!
115pub(crate) fn check_abi_required_features(sess: &Session) {
116    let abi_feature_constraints = sess.target.abi_required_features();
117    // We check this against `internal_target_features` as that is conveniently already
118    // back-translated to rustc feature names, taking into account `-Ctarget-cpu` and `-Ctarget-feature`.
119    // Just double-check that the features we care about are actually on our list.
120    for feature in
121        abi_feature_constraints.required.iter().chain(abi_feature_constraints.incompatible.iter())
122    {
123        if !sess.target.rust_target_features().iter().any(|(name, ..)|
                feature == name) {
    {
        ::core::panicking::panic_fmt(format_args!("target feature {0} is required/incompatible for the current ABI but not a recognized feature for this target",
                feature));
    }
};assert!(
124            sess.target.rust_target_features().iter().any(|(name, ..)| feature == name),
125            "target feature {feature} is required/incompatible for the current ABI but not a recognized feature for this target"
126        );
127    }
128
129    // Make this a hard error on ARM since starting with LLVM24, the backend will otherwise
130    // emit a (less friendly) hard error.
131    // Also make it a hard error on x86, where we use SSE registers for the "Rust" ABI. The
132    // post-mono ABI check only systematically checks "C" calls, so we better reject this here.
133    let hard_error = #[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
    Arch::AArch64 | Arch::Arm | Arch::X86 => true,
    _ => false,
}matches!(sess.target.arch, Arch::AArch64 | Arch::Arm | Arch::X86);
134
135    for feature in abi_feature_constraints.required {
136        if !sess.internal_target_features.contains(&Symbol::intern(feature)) {
137            let diag = diagnostics::AbiRequiredTargetFeature {
138                feature,
139                enabled: "enabled",
140                fcw: !hard_error,
141            };
142            if hard_error {
143                sess.dcx().emit_err(diag);
144            } else {
145                sess.dcx().emit_warn(diag);
146            }
147        }
148    }
149    for feature in abi_feature_constraints.incompatible {
150        if sess.internal_target_features.contains(&Symbol::intern(feature)) {
151            let diag = diagnostics::AbiRequiredTargetFeature {
152                feature,
153                enabled: "disabled",
154                fcw: !hard_error,
155            };
156            if hard_error {
157                sess.dcx().emit_err(diag);
158            } else {
159                sess.dcx().emit_warn(diag);
160            }
161        }
162    }
163}
164
165pub static STACK_SIZE: OnceLock<usize> = OnceLock::new();
166
167fn init_stack_size(early_dcx: &EarlyDiagCtxt) -> usize {
168    // Obey the environment setting or default
169    *STACK_SIZE.get_or_init(|| {
170        env::var_os("RUST_MIN_STACK")
171            .as_ref()
172            .map(|os_str| os_str.to_string_lossy())
173            // if someone finds out `export RUST_MIN_STACK=640000` isn't enough stack
174            // they might try to "unset" it by running `RUST_MIN_STACK=  rustc code.rs`
175            // this is wrong, but std would nonetheless "do what they mean", so let's do likewise
176            .filter(|s| !s.trim().is_empty())
177            // rustc is a batch program, so error early on inputs which are unlikely to be intended
178            // so no one thinks we parsed them setting `RUST_MIN_STACK="64 megabytes"`
179            // FIXME: we could accept `RUST_MIN_STACK=64MB`, perhaps?
180            .map(|s| {
181                let s = s.trim();
182                s.parse::<usize>().unwrap_or_else(|_| {
183                    let mut err = early_dcx.early_struct_fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`RUST_MIN_STACK` should be a number of bytes, but was \"{0}\"",
                s))
    })format!(
184                        r#"`RUST_MIN_STACK` should be a number of bytes, but was "{s}""#,
185                    ));
186                    err.note("you can also unset `RUST_MIN_STACK` to use the default stack size");
187                    err.emit_fatal()
188                })
189            })
190            // otherwise pick a consistent default
191            .unwrap_or(DEFAULT_STACK_SIZE)
192    })
193}
194
195fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
196    thread_stack_size: usize,
197    edition: Edition,
198    sm_inputs: SourceMapInputs,
199    extra_symbols: &[&'static str],
200    f: F,
201) -> R {
202    // The "thread pool" is a single spawned thread in the non-parallel
203    // compiler. We run on a spawned thread instead of the main thread (a) to
204    // provide control over the stack size, and (b) to increase similarity with
205    // the parallel compiler, in particular to ensure there is no accidental
206    // sharing of data between the main thread and the compilation thread
207    // (which might cause problems for the parallel compiler).
208    let builder = thread::Builder::new().name("rustc".to_string()).stack_size(thread_stack_size);
209
210    // We build the session globals and run `f` on the spawned thread, because
211    // `SessionGlobals` does not impl `Send` in the non-parallel compiler.
212    thread::scope(|s| {
213        // `unwrap` is ok here because `spawn_scoped` only panics if the thread
214        // name contains null bytes.
215        let r = builder
216            .spawn_scoped(s, move || {
217                rustc_span::create_session_globals_then(
218                    edition,
219                    extra_symbols,
220                    Some(sm_inputs),
221                    || f(CurrentGcx::new()),
222                )
223            })
224            .unwrap()
225            .join();
226
227        match r {
228            Ok(v) => v,
229            Err(e) => std::panic::resume_unwind(e),
230        }
231    })
232}
233
234pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
235    thread_builder_diag: &EarlyDiagCtxt,
236    edition: Edition,
237    jobs: Jobs,
238    extra_symbols: &[&'static str],
239    sm_inputs: SourceMapInputs,
240    f: F,
241) -> R {
242    use std::process;
243
244    use rustc_data_structures::defer;
245    use rustc_middle::ty::tls;
246    use rustc_query_impl::break_query_cycle;
247
248    let thread_stack_size = init_stack_size(thread_builder_diag);
249
250    let jobs_frontend = jobs.frontend.limit();
251    let registry = sync::Registry::new(jobs_frontend);
252
253    let Some(proof) = sync::check_dyn_thread_safe() else {
254        {
    match (&jobs_frontend.get(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(jobs_frontend.get(), 1);
255        return run_in_thread_with_globals(
256            thread_stack_size,
257            edition,
258            sm_inputs,
259            extra_symbols,
260            |current_gcx| {
261                // Register the thread for use with the `WorkerLocal` type.
262                registry.register();
263
264                f(current_gcx)
265            },
266        );
267    };
268
269    let current_gcx = proof.derive(CurrentGcx::new());
270    let current_gcx2 = current_gcx.clone();
271
272    let proxy = Proxy::new();
273    let proxy_ = Arc::clone(&proxy);
274
275    let builder = rustc_thread_pool::ThreadPoolBuilder::new()
276        .thread_name(|_| "rustc".to_string())
277        .acquire_thread_handler(move || proxy.acquire_thread())
278        .release_thread_handler(move || proxy_.release_thread())
279        .num_threads(jobs_frontend.get())
280        .deadlock_handler(move || {
281            // On deadlock, creates a new thread and forwards information in thread
282            // locals to it. The new thread runs the deadlock handler.
283
284            let current_gcx2 = current_gcx2.clone();
285            let registry = rustc_thread_pool::Registry::current();
286            let session_globals = rustc_span::with_session_globals(|session_globals| {
287                session_globals as *const SessionGlobals as usize
288            });
289            thread::Builder::new()
290                .name("rustc query cycle handler".to_string())
291                .spawn(move || {
292                    let on_panic = defer(|| {
293                        // Split this long string so that it doesn't cause rustfmt to
294                        // give up on the entire builder expression.
295                        // <https://github.com/rust-lang/rustfmt/issues/3863>
296                        const MESSAGE: &str = "\
297internal compiler error: query cycle handler thread panicked, aborting process";
298                        { ::std::io::_eprint(format_args!("{0}\n", MESSAGE)); };eprintln!("{MESSAGE}");
299                        // We need to abort here as we failed to resolve the deadlock,
300                        // otherwise the compiler could just hang,
301                        process::abort();
302                    });
303
304                    // Get a `GlobalCtxt` reference from `CurrentGcx` as we cannot rely on having a
305                    // `TyCtxt` TLS reference here.
306                    current_gcx2.access(|gcx| {
307                        tls::enter_context(&tls::ImplicitCtxt::new(gcx), || {
308                            tls::with(|tcx| {
309                                // Accessing session globals is sound as they outlive `GlobalCtxt`.
310                                // They are needed to hash query keys containing spans or symbols.
311                                let job_map = rustc_span::set_session_globals_then(
312                                    unsafe { &*(session_globals as *const SessionGlobals) },
313                                    || {
314                                        // Ensure there were no errors collecting all active jobs.
315                                        // We need the complete map to ensure we find a cycle to
316                                        // break.
317                                        collect_active_query_jobs(
318                                            tcx,
319                                            CollectActiveJobsKind::FullNoContention,
320                                        )
321                                    },
322                                );
323                                break_query_cycle(job_map, &registry);
324                            })
325                        })
326                    });
327
328                    on_panic.disable();
329                })
330                .unwrap();
331        })
332        .stack_size(thread_stack_size);
333
334    // We create the session globals on the main thread, then create the thread
335    // pool. Upon creation, each worker thread created gets a copy of the
336    // session globals in TLS. This is possible because `SessionGlobals` impls
337    // `Send` in the parallel compiler.
338    rustc_span::create_session_globals_then(edition, extra_symbols, Some(sm_inputs), || {
339        rustc_span::with_session_globals(|session_globals| {
340            let session_globals = proof.derive(session_globals);
341            builder
342                .build_scoped(
343                    // Initialize each new worker thread when created.
344                    move |thread: rustc_thread_pool::ThreadBuilder| {
345                        // Register the thread for use with the `WorkerLocal` type.
346                        registry.register();
347
348                        rustc_span::set_session_globals_then(session_globals.into_inner(), || {
349                            thread.run()
350                        })
351                    },
352                    // Run `f` on the first thread in the thread pool.
353                    move |pool: &rustc_thread_pool::ThreadPool| {
354                        pool.install(|| f(current_gcx.into_inner()))
355                    },
356                )
357                .unwrap_or_else(|err| {
358                    let mut diag = thread_builder_diag.early_struct_fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to spawn compiler thread pool: could not create {0} threads ({1})",
                jobs_frontend, err))
    })format!(
359                        "failed to spawn compiler thread pool: could not create {jobs_frontend} threads ({err})",
360                    ));
361                    diag.help(
362                        "try lowering `-Z threads` or checking the operating system's resource limits",
363                    );
364                    diag.emit_fatal()
365                })
366        })
367    })
368}
369
370fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
371    match unsafe { load_symbol_from_dylib::<MakeBackendFn>(path, "__rustc_codegen_backend") } {
372        Ok(backend_sym) => backend_sym,
373        Err(DylibError::DlOpen(path, err)) => {
374            let err = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("couldn\'t load codegen backend {0}{1}",
                path, err))
    })format!("couldn't load codegen backend {path}{err}");
375            early_dcx.early_fatal(err);
376        }
377        Err(DylibError::DlSym(_path, err)) => {
378            let e = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`__rustc_codegen_backend` symbol lookup in the codegen backend failed{0}",
                err))
    })format!(
379                "`__rustc_codegen_backend` symbol lookup in the codegen backend failed{err}",
380            );
381            early_dcx.early_fatal(e);
382        }
383    }
384}
385
386/// Get the codegen backend based on the name and specified sysroot.
387///
388/// A name of `None` indicates that the default backend should be used.
389pub fn get_codegen_backend(
390    early_dcx: &EarlyDiagCtxt,
391    sysroot: &Sysroot,
392    backend_name: Option<&str>,
393    target: &Target,
394) -> Box<dyn CodegenBackend> {
395    static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
396
397    let load = LOAD.get_or_init(|| {
398        let backend = backend_name
399            .or(target.default_codegen_backend.as_deref())
400            .or(::core::option::Option::Some("llvm")option_env!("CFG_DEFAULT_CODEGEN_BACKEND"))
401            .unwrap_or("dummy");
402
403        match backend {
404            filename if filename.contains('.') => {
405                load_backend_from_dylib(early_dcx, filename.as_ref())
406            }
407            "dummy" => || Box::new(DummyCodegenBackend),
408            #[cfg(feature = "llvm")]
409            "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
410            backend_name => get_codegen_sysroot(early_dcx, sysroot, backend_name),
411        }
412    });
413
414    // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
415    // backend we hope that the backend links against the same rustc_driver version. If this is not
416    // the case, we get UB.
417    unsafe { load() }
418}
419
420pub struct DummyCodegenBackend;
421
422impl CodegenBackend for DummyCodegenBackend {
423    fn name(&self) -> &'static str {
424        "dummy"
425    }
426
427    fn target_config(&self, sess: &EarlySession) -> TargetConfig {
428        let abi_required_features = sess.target.abi_required_features();
429        let internal_target_features = internal_target_features::<0>(
430            sess,
431            |_feature| Default::default(),
432            |feature| {
433                // This is a standin for the list of features a backend is expected to enable.
434                // It would be better to parse target.features instead and handle implied features,
435                // but target.features doesn't contain features that are enabled by default for an
436                // architecture or target cpu.
437                abi_required_features.required.contains(&feature)
438            },
439        );
440
441        TargetConfig {
442            internal_target_features,
443            has_reliable_f16: true,
444            has_reliable_f16_math: true,
445            has_reliable_f16b: true,
446            has_reliable_f128: true,
447            has_reliable_f128_math: true,
448        }
449    }
450
451    fn supported_crate_types(&self, _sess: &Session) -> Vec<CrateType> {
452        // This includes bin despite failing on the link step to ensure that you
453        // can still get the frontend handling for binaries. For all library
454        // like crate types cargo will fallback to rlib unless you specifically
455        // say that only a different crate type must be used.
456        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [CrateType::Rlib, CrateType::Executable]))vec![CrateType::Rlib, CrateType::Executable]
457    }
458
459    fn target_cpu(&self, _sess: &Session) -> String {
460        String::new()
461    }
462
463    fn codegen_crate<'tcx>(&self, _tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
464        Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
465    }
466
467    fn join_codegen(
468        &self,
469        ongoing_codegen: Box<dyn Any>,
470        _sess: &Session,
471        _incr_comp_session: Option<&IncrCompSession>,
472        _outputs: &OutputFilenames,
473        _crate_info: &CrateInfo,
474    ) -> (CompiledModules, WorkProductMap) {
475        (*ongoing_codegen.downcast().unwrap(), WorkProductMap::default())
476    }
477
478    fn link(
479        &self,
480        sess: &Session,
481        compiled_modules: CompiledModules,
482        crate_info: CrateInfo,
483        metadata: EncodedMetadata,
484        outputs: &OutputFilenames,
485    ) {
486        // JUSTIFICATION: TyCtxt no longer available here
487        #[allow(rustc::bad_opt_access)]
488        if let Some(&crate_type) =
489            crate_info.crate_types.iter().find(|&&crate_type| crate_type != CrateType::Rlib)
490            && outputs.outputs.should_link()
491        {
492            sess.dcx().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("crate type {0} not supported by the dummy codegen backend",
                crate_type))
    })format!(
493                "crate type {crate_type} not supported by the dummy codegen backend"
494            ));
495        }
496
497        link_binary(
498            sess,
499            &DummyArchiveBuilderBuilder,
500            compiled_modules,
501            crate_info,
502            metadata,
503            outputs,
504            self.name(),
505        );
506    }
507}
508
509struct DummyArchiveBuilderBuilder;
510
511impl ArchiveBuilderBuilder for DummyArchiveBuilderBuilder {
512    fn new_archive_builder<'a>(
513        &self,
514        sess: &'a Session,
515    ) -> Box<dyn rustc_codegen_ssa::back::archive::ArchiveBuilder + 'a> {
516        ArArchiveBuilderBuilder.new_archive_builder(sess)
517    }
518
519    fn create_dll_import_lib(
520        &self,
521        sess: &Session,
522        _lib_name: &str,
523        _items: Vec<rustc_codegen_ssa::back::archive::ImportLibraryItem>,
524        output_path: &Path,
525    ) {
526        // Build an empty static library to avoid calling an external dlltool on mingw
527        ArArchiveBuilderBuilder.new_archive_builder(sess).build(output_path, None);
528    }
529}
530
531// This is used for rustdoc, but it uses similar machinery to codegen backend
532// loading, so we leave the code here. It is potentially useful for other tools
533// that want to invoke the rustc binary while linking to rustc as well.
534pub fn rustc_path<'a>(sysroot: &Sysroot) -> Option<&'a Path> {
535    static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
536
537    RUSTC_PATH
538        .get_or_init(|| {
539            let candidate = sysroot
540                .default
541                .join("bin"env!("RUSTC_INSTALL_BINDIR"))
542                .join(if falsecfg!(target_os = "windows") { "rustc.exe" } else { "rustc" });
543            candidate.exists().then_some(candidate)
544        })
545        .as_deref()
546}
547
548fn get_codegen_sysroot(
549    early_dcx: &EarlyDiagCtxt,
550    sysroot: &Sysroot,
551    backend_name: &str,
552) -> MakeBackendFn {
553    // For now we only allow this function to be called once as it'll dlopen a
554    // few things, which seems to work best if we only do that once. In
555    // general this assertion never trips due to the once guard in `get_codegen_backend`,
556    // but there's a few manual calls to this function in this file we protect
557    // against.
558    static LOADED: AtomicBool = AtomicBool::new(false);
559    if !!LOADED.fetch_or(true, Ordering::SeqCst) {
    {
        ::core::panicking::panic_fmt(format_args!("cannot load the default codegen backend twice"));
    }
};assert!(
560        !LOADED.fetch_or(true, Ordering::SeqCst),
561        "cannot load the default codegen backend twice"
562    );
563
564    let target = host_tuple();
565
566    let sysroot = sysroot
567        .all_paths()
568        .map(|sysroot| {
569            filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
570        })
571        .find(|f| {
572            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_interface/src/util.rs:572",
                        "rustc_interface::util", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_interface/src/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(572u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::util"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen backend candidate: {0}",
                                                    f.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("codegen backend candidate: {}", f.display());
573            f.exists()
574        })
575        .unwrap_or_else(|| {
576            let candidates = sysroot
577                .all_paths()
578                .map(|p| p.display().to_string())
579                .collect::<Vec<_>>()
580                .join("\n* ");
581            let err = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to find a `codegen-backends` folder in the sysroot candidates:\n* {0}",
                candidates))
    })format!(
582                "failed to find a `codegen-backends` folder in the sysroot candidates:\n\
583                 * {candidates}"
584            );
585            early_dcx.early_fatal(err);
586        });
587
588    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_interface/src/util.rs:588",
                        "rustc_interface::util", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_interface/src/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(588u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::util"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("probing {0} for a codegen backend",
                                                    sysroot.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("probing {} for a codegen backend", sysroot.display());
589
590    let d = sysroot.read_dir().unwrap_or_else(|e| {
591        let err = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to load default codegen backend, couldn\'t read `{0}`: {1}",
                sysroot.display(), e))
    })format!(
592            "failed to load default codegen backend, couldn't read `{}`: {e}",
593            sysroot.display(),
594        );
595        early_dcx.early_fatal(err);
596    });
597
598    let mut file: Option<PathBuf> = None;
599
600    let expected_names = &[
601        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc_codegen_{0}-{1}",
                backend_name, "1.102.0-nightly"))
    })format!("rustc_codegen_{}-{}", backend_name, env!("CFG_RELEASE")),
602        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc_codegen_{0}", backend_name))
    })format!("rustc_codegen_{backend_name}"),
603    ];
604    for entry in d.filter_map(|e| e.ok()) {
605        let path = entry.path();
606        let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
607        if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
608            continue;
609        }
610        let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
611        if !expected_names.iter().any(|expected| expected == name) {
612            continue;
613        }
614        if let Some(ref prev) = file {
615            let err = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("duplicate codegen backends found\nfirst:  {0}\nsecond: {1}\n",
                prev.display(), path.display()))
    })format!(
616                "duplicate codegen backends found\n\
617                               first:  {}\n\
618                               second: {}\n\
619            ",
620                prev.display(),
621                path.display()
622            );
623            early_dcx.early_fatal(err);
624        }
625        file = Some(path.clone());
626    }
627
628    match file {
629        Some(ref s) => load_backend_from_dylib(early_dcx, s),
630        None => {
631            let err = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unsupported builtin codegen backend `{0}`",
                backend_name))
    })format!("unsupported builtin codegen backend `{backend_name}`");
632            early_dcx.early_fatal(err);
633        }
634    }
635}
636
637fn multiple_output_types_to_stdout(
638    output_types: &OutputTypes,
639    single_output_file_is_stdout: bool,
640) -> bool {
641    use std::io::IsTerminal;
642    if std::io::stdout().is_terminal() {
643        // If stdout is a tty, check if multiple text output types are
644        // specified by `--emit foo=- --emit bar=-` or `-o - --emit foo,bar`
645        let named_text_types = output_types
646            .iter()
647            .filter(|(f, o)| f.is_text_output() && *o == &Some(OutFileName::Stdout))
648            .count();
649        let unnamed_text_types =
650            output_types.iter().filter(|(f, o)| f.is_text_output() && o.is_none()).count();
651        named_text_types > 1 || unnamed_text_types > 1 && single_output_file_is_stdout
652    } else {
653        // Otherwise, all the output types should be checked
654        let named_types =
655            output_types.values().filter(|o| *o == &Some(OutFileName::Stdout)).count();
656        let unnamed_types = output_types.values().filter(|o| o.is_none()).count();
657        named_types > 1 || unnamed_types > 1 && single_output_file_is_stdout
658    }
659}
660
661pub fn build_output_filenames(attrs: &[ast::Attribute], sess: &Session) -> OutputFilenames {
662    if multiple_output_types_to_stdout(
663        &sess.opts.output_types,
664        sess.io.output_file == Some(OutFileName::Stdout),
665    ) {
666        sess.dcx().emit_fatal(diagnostics::MultipleOutputTypesToStdout);
667    }
668
669    let crate_name =
670        sess.opts.crate_name.clone().or_else(|| {
671            parse_crate_name(sess, attrs, ShouldEmit::Nothing).map(|i| i.0.to_string())
672        });
673
674    let invocation_temp = sess
675        .opts
676        .incremental
677        .as_ref()
678        .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
679
680    match sess.io.output_file {
681        None => {
682            // "-" as input file will cause the parser to read from stdin so we
683            // have to make up a name
684            // We want to toss everything after the final '.'
685            let dirpath = sess.io.output_dir.clone().unwrap_or_default();
686
687            // If a crate name is present, we use it as the link name
688            let stem = crate_name.clone().unwrap_or_else(|| sess.io.input.filestem().to_owned());
689
690            OutputFilenames::new(
691                dirpath,
692                crate_name.unwrap_or_else(|| stem.replace('-', "_")),
693                stem,
694                None,
695                sess.io.temps_dir.clone(),
696                invocation_temp,
697                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
698                sess.opts.cg.extra_filename.clone(),
699                sess.opts.output_types.clone(),
700            )
701        }
702
703        Some(ref out_file) => {
704            let unnamed_output_types =
705                sess.opts.output_types.values().filter(|a| a.is_none()).count();
706            let ofile = if unnamed_output_types > 1 {
707                sess.dcx().emit_warn(diagnostics::MultipleOutputTypesAdaption);
708                None
709            } else {
710                if !sess.opts.cg.extra_filename.is_empty() {
711                    sess.dcx().emit_warn(diagnostics::IgnoringExtraFilename);
712                }
713                Some(out_file.clone())
714            };
715            if sess.io.output_dir.is_some() {
716                sess.dcx().emit_warn(diagnostics::IgnoringOutDir);
717            }
718
719            let out_filestem =
720                out_file.filestem().unwrap_or_default().to_str().unwrap().to_string();
721            OutputFilenames::new(
722                out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
723                crate_name.unwrap_or_else(|| out_filestem.replace('-', "_")),
724                out_filestem,
725                ofile,
726                sess.io.temps_dir.clone(),
727                invocation_temp,
728                sess.opts.unstable_opts.split_dwarf_out_dir.clone(),
729                sess.opts.cg.extra_filename.clone(),
730                sess.opts.output_types.clone(),
731            )
732        }
733    }
734}
735
736/// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)" when invoked by an in-tree tool.
737pub macro version_str() {
738    option_env!("CFG_VERSION")
739}
740
741/// Returns the version string for `rustc` itself (which may be different from a tool version).
742pub fn rustc_version_str() -> Option<&'static str> {
743    ::core::option::Option::Some("1.102.0-nightly (9c5648833 2026-11-10)")version_str!()
744}