Skip to main content

rustc_interface/
util.rs

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