Skip to main content

rustc_interface/
util.rs

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