Skip to main content

rustc_interface/
passes.rs

1use std::any::Any;
2use std::ffi::{OsStr, OsString};
3use std::io::{self, BufWriter, Write};
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, LazyLock, OnceLock};
6use std::{env, fs, iter};
7
8use rustc_ast as ast;
9use rustc_attr_ir::{Attribute, AttributeKind, find_attr};
10use rustc_attr_parsing::{AttributeParser, ShouldEmit};
11use rustc_codegen_ssa::traits::CodegenBackend;
12use rustc_codegen_ssa::{CompiledModules, CrateInfo};
13use rustc_crate_store::Untracked;
14use rustc_data_structures::indexmap::IndexMap;
15use rustc_data_structures::steal::Steal;
16use rustc_data_structures::sync::{
17    AppendOnlyIndexVec, DynSend, DynSync, FreezeLock, WorkerLocal, par_fns,
18};
19use rustc_data_structures::thousands;
20use rustc_errors::timings::TimingSection;
21use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level};
22use rustc_expand::base::{ExtCtxt, LintStoreExpand};
23use rustc_feature::Features;
24use rustc_fs_util::try_canonicalize;
25use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
26use rustc_hir::definitions::Definitions;
27use rustc_incremental::setup_dep_graph;
28use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store};
29use rustc_metadata::EncodedMetadata;
30use rustc_metadata::creader::CStore;
31use rustc_middle::arena::Arena;
32use rustc_middle::middle::resolve::{ResolverAstLowering, ResolverGlobalCtxt};
33use rustc_middle::ty::{self, RegisteredTools, TyCtxt};
34use rustc_middle::util::Providers;
35use rustc_parse::lexer::StripTokens;
36use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
37use rustc_passes::{abi_test, input_stats, layout_test};
38use rustc_resolve::{Resolver, ResolverOutputs};
39use rustc_session::config::{Input, Offload, OutFileName, OutputFilenames, OutputType};
40use rustc_session::diagnostics::feature_err;
41use rustc_session::output::{filename_for_input, invalid_output_for_target};
42use rustc_session::search_paths::PathKind;
43use rustc_session::{IncrCompSession, Session};
44use rustc_span::{
45    DUMMY_SP, ErrorGuaranteed, ExpnKind, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
46};
47use rustc_structures::CrateType;
48use rustc_trait_selection::{solve, traits};
49use tracing::{info, instrument};
50
51use crate::interface::Compiler;
52use crate::{diagnostics, limits, util};
53
54pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
55    let mut krate = sess
56        .time("parse_crate", || {
57            let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
58                Input::File(file) => new_parser_from_file(
59                    &sess.psess,
60                    file,
61                    StripTokens::ShebangAndFrontmatter,
62                    None,
63                ),
64                instr @ (Input::Str { input, .. } | Input::DocTestStr { input, .. }) => {
65                    new_parser_from_source_str(
66                        &sess.psess,
67                        instr.file_name(sess),
68                        input.clone(),
69                        StripTokens::ShebangAndFrontmatter,
70                    )
71                }
72            });
73            parser.parse_crate_mod()
74        })
75        .unwrap_or_else(|parse_error| {
76            let guar: ErrorGuaranteed = parse_error.emit_err();
77            guar.raise_fatal();
78        });
79
80    rustc_builtin_macros::cmdline_attrs::inject(
81        &mut krate,
82        &sess.psess,
83        &sess.opts.unstable_opts.crate_attr,
84    );
85
86    krate
87}
88
89fn pre_expansion_lint<'a>(
90    sess: &Session,
91    features: &Features,
92    lint_store: &LintStore,
93    registered_lint_tools: &RegisteredTools,
94    check_node: EarlyCheckNode<'a>,
95    node_name: Symbol,
96) {
97    sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
98        || {
99            rustc_lint::check_ast_node(
100                sess,
101                features,
102                true,
103                lint_store,
104                registered_lint_tools,
105                None,
106                check_node,
107            );
108        },
109    );
110}
111
112// Cannot implement directly for `LintStore` due to trait coherence.
113struct LintStoreExpandImpl<'a>(&'a LintStore);
114
115impl LintStoreExpand for LintStoreExpandImpl<'_> {
116    fn pre_expansion_lint(
117        &self,
118        sess: &Session,
119        features: &Features,
120        registered_lint_tools: &RegisteredTools,
121        node_id: ast::NodeId,
122        attrs: &[ast::Attribute],
123        items: &[Box<ast::Item>],
124        name: Symbol,
125    ) {
126        let check_node = EarlyCheckNode::LoadedMod(node_id, attrs, items);
127        pre_expansion_lint(sess, features, self.0, registered_lint_tools, check_node, name);
128    }
129}
130
131/// Runs the "early phases" of the compiler: initial `cfg` processing,
132/// syntax expansion, secondary `cfg` expansion, synthesis of a test
133/// harness if one is to be provided, injection of a dependency on the
134/// standard library and prelude, and name resolution.
135{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("configure_and_expand",
                                    "rustc_interface::passes", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_interface/src/passes.rs"),
                                    ::tracing_core::__macro_support::Option::Some(135u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("pre_configured_attrs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("pre_configured_attrs");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pre_configured_attrs)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ast::Crate = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = resolver.tcx();
            let sess = tcx.sess;
            let features = tcx.features();
            let lint_store = unerased_lint_store(sess);
            let crate_name = tcx.crate_name(LOCAL_CRATE);
            pre_expansion_lint(sess, features, lint_store,
                tcx.registered_lint_tools(()),
                EarlyCheckNode::CrateRoot(&krate, pre_configured_attrs),
                crate_name);
            rustc_builtin_macros::register_builtin_macros(resolver);
            let num_standard_library_imports =
                sess.time("crate_injection",
                    ||
                        {
                            rustc_builtin_macros::standard_library_imports::inject(&mut krate,
                                pre_configured_attrs, resolver, sess, features)
                        });
            krate =
                sess.time("macro_expand_crate",
                    ||
                        {
                            let mut old_path = OsString::new();
                            if false {
                                old_path = env::var_os("PATH").unwrap_or(old_path);
                                let mut new_path =
                                    Vec::from_iter(sess.host_filesearch().search_paths(PathKind::Native).map(|p|
                                                p.dir.to_path_buf()));
                                for path in env::split_paths(&old_path) {
                                    if !new_path.contains(&path) { new_path.push(path); }
                                }
                                unsafe {
                                    env::set_var("PATH",
                                        env::join_paths(new_path.iter().filter(|p|
                                                        env::join_paths(iter::once(p)).is_ok())).unwrap());
                                }
                            }
                            let recursion_limit = tcx.recursion_limit();
                            let cfg =
                                rustc_expand::expand::ExpansionConfig {
                                    crate_name,
                                    features,
                                    recursion_limit,
                                    trace_mac: sess.opts.unstable_opts.trace_macros,
                                    should_test: sess.is_test_crate(),
                                    span_debug: sess.opts.unstable_opts.span_debug,
                                    proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
                                };
                            let lint_store = LintStoreExpandImpl(lint_store);
                            let mut ecx =
                                ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
                            ecx.num_standard_library_imports =
                                num_standard_library_imports;
                            let krate =
                                sess.time("expand_crate",
                                    || ecx.monotonic_expander().expand_crate(krate));
                            if ecx.nb_macro_errors > 0 { sess.dcx().abort_if_errors(); }
                            sess.psess.buffered_lints.with_lock(|buffered_lints:
                                        &mut Option<Vec<BufferedEarlyLint>>|
                                    {
                                        buffered_lints.as_mut().expect("Buffered lints are not stolen yet").append(&mut ecx.buffered_early_lint);
                                    });
                            sess.time("check_unused_macros",
                                || { ecx.check_unused_macros(); });
                            if ecx.reduced_recursion_limit.is_some() {
                                sess.dcx().abort_if_errors();
                                ::core::panicking::unreachable_default_msg();
                            }
                            if false { unsafe { env::set_var("PATH", &old_path); } }
                            if ecx.sess.opts.unstable_opts.macro_stats {
                                print_macro_stats(&ecx);
                            }
                            krate
                        });
            sess.time("maybe_building_test_harness",
                ||
                    {
                        rustc_builtin_macros::test_harness::inject(&mut krate, sess,
                            features, resolver)
                    });
            let has_proc_macro_decls =
                sess.time("AST_validation",
                    ||
                        {
                            rustc_ast_passes::ast_validation::check_crate(sess,
                                features, &krate, tcx.is_sdylib_interface_build(),
                                resolver.lint_buffer())
                        });
            if features.rustc_attrs() {
                rustc_ast_passes::show_spans::check_crate(sess, &krate);
            }
            let crate_types = tcx.crate_types();
            let is_executable_crate =
                crate_types.contains(&CrateType::Executable);
            let is_proc_macro_crate =
                crate_types.contains(&CrateType::ProcMacro);
            if crate_types.len() > 1 {
                if is_executable_crate {
                    sess.dcx().emit_err(diagnostics::MixedBinCrate);
                }
                if is_proc_macro_crate {
                    sess.dcx().emit_err(diagnostics::MixedProcMacroCrate);
                }
            }
            if is_proc_macro_crate && sess.target.is_like_wasm &&
                    !sess.opts.unstable_opts.wasm_proc_macros {
                sess.dcx().emit_err(diagnostics::UnstableWasmProcMacro);
            }
            if crate_types.contains(&CrateType::Sdylib) &&
                    !tcx.features().export_stable() {
                feature_err(sess, sym::export_stable, DUMMY_SP,
                        "`sdylib` crate type is unstable").emit();
            }
            if is_proc_macro_crate && !sess.sanitizers().is_empty() {
                sess.dcx().emit_err(diagnostics::CannotSanitizeProcMacro);
            }
            if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
                sess.dcx().emit_warn(diagnostics::ProcMacroCratePanicAbort);
            }
            sess.time("maybe_create_a_macro_crate",
                ||
                    {
                        let is_test_crate = sess.is_test_crate();
                        rustc_builtin_macros::proc_macro_harness::inject(&mut krate,
                            sess, features, resolver, is_proc_macro_crate,
                            has_proc_macro_decls, is_test_crate, sess.dcx())
                    });
            resolver.resolve_crate(&krate);
            CStore::from_tcx(tcx).report_session_incompatibilities(tcx,
                &krate);
            krate
        }
    }
}#[instrument(level = "trace", skip(krate, resolver))]
136fn configure_and_expand(
137    mut krate: ast::Crate,
138    pre_configured_attrs: &[ast::Attribute],
139    resolver: &mut Resolver<'_, '_>,
140) -> ast::Crate {
141    let tcx = resolver.tcx();
142    let sess = tcx.sess;
143    let features = tcx.features();
144    let lint_store = unerased_lint_store(sess);
145    let crate_name = tcx.crate_name(LOCAL_CRATE);
146    pre_expansion_lint(
147        sess,
148        features,
149        lint_store,
150        tcx.registered_lint_tools(()),
151        EarlyCheckNode::CrateRoot(&krate, pre_configured_attrs),
152        crate_name,
153    );
154    rustc_builtin_macros::register_builtin_macros(resolver);
155
156    let num_standard_library_imports = sess.time("crate_injection", || {
157        rustc_builtin_macros::standard_library_imports::inject(
158            &mut krate,
159            pre_configured_attrs,
160            resolver,
161            sess,
162            features,
163        )
164    });
165
166    // Expand all macros
167    krate = sess.time("macro_expand_crate", || {
168        // Windows dlls do not have rpaths, so they don't know how to find their
169        // dependencies. It's up to us to tell the system where to find all the
170        // dependent dlls. Note that this uses cfg!(windows) as opposed to
171        // targ_cfg because syntax extensions are always loaded for the host
172        // compiler, not for the target.
173        //
174        // This is somewhat of an inherently racy operation, however, as
175        // multiple threads calling this function could possibly continue
176        // extending PATH far beyond what it should. To solve this for now we
177        // just don't add any new elements to PATH which are already there
178        // within PATH. This is basically a targeted fix at #17360 for rustdoc
179        // which runs rustc in parallel but has been seen (#33844) to cause
180        // problems with PATH becoming too long.
181        let mut old_path = OsString::new();
182        if cfg!(windows) {
183            old_path = env::var_os("PATH").unwrap_or(old_path);
184            let mut new_path = Vec::from_iter(
185                sess.host_filesearch().search_paths(PathKind::Native).map(|p| p.dir.to_path_buf()),
186            );
187            for path in env::split_paths(&old_path) {
188                if !new_path.contains(&path) {
189                    new_path.push(path);
190                }
191            }
192            unsafe {
193                env::set_var(
194                    "PATH",
195                    env::join_paths(
196                        new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
197                    )
198                    .unwrap(),
199                );
200            }
201        }
202
203        // Create the config for macro expansion
204        let recursion_limit = tcx.recursion_limit();
205        let cfg = rustc_expand::expand::ExpansionConfig {
206            crate_name,
207            features,
208            recursion_limit,
209            trace_mac: sess.opts.unstable_opts.trace_macros,
210            should_test: sess.is_test_crate(),
211            span_debug: sess.opts.unstable_opts.span_debug,
212            proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
213        };
214
215        let lint_store = LintStoreExpandImpl(lint_store);
216        let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
217        ecx.num_standard_library_imports = num_standard_library_imports;
218        // Expand macros now!
219        let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
220
221        if ecx.nb_macro_errors > 0 {
222            sess.dcx().abort_if_errors();
223        }
224
225        // The rest is error reporting and stats
226
227        sess.psess.buffered_lints.with_lock(
228            |buffered_lints: &mut Option<Vec<BufferedEarlyLint>>| {
229                buffered_lints
230                    .as_mut()
231                    .expect("Buffered lints are not stolen yet")
232                    .append(&mut ecx.buffered_early_lint);
233            },
234        );
235
236        sess.time("check_unused_macros", || {
237            ecx.check_unused_macros();
238        });
239
240        // If we hit a recursion limit, exit early to avoid later passes getting overwhelmed
241        // with a large AST
242        if ecx.reduced_recursion_limit.is_some() {
243            sess.dcx().abort_if_errors();
244            unreachable!();
245        }
246
247        if cfg!(windows) {
248            unsafe {
249                env::set_var("PATH", &old_path);
250            }
251        }
252
253        if ecx.sess.opts.unstable_opts.macro_stats {
254            print_macro_stats(&ecx);
255        }
256
257        krate
258    });
259
260    sess.time("maybe_building_test_harness", || {
261        rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
262    });
263
264    let has_proc_macro_decls = sess.time("AST_validation", || {
265        rustc_ast_passes::ast_validation::check_crate(
266            sess,
267            features,
268            &krate,
269            tcx.is_sdylib_interface_build(),
270            resolver.lint_buffer(),
271        )
272    });
273
274    if features.rustc_attrs() {
275        rustc_ast_passes::show_spans::check_crate(sess, &krate);
276    }
277
278    let crate_types = tcx.crate_types();
279    let is_executable_crate = crate_types.contains(&CrateType::Executable);
280    let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
281
282    if crate_types.len() > 1 {
283        if is_executable_crate {
284            sess.dcx().emit_err(diagnostics::MixedBinCrate);
285        }
286        if is_proc_macro_crate {
287            sess.dcx().emit_err(diagnostics::MixedProcMacroCrate);
288        }
289    }
290
291    if is_proc_macro_crate && sess.target.is_like_wasm && !sess.opts.unstable_opts.wasm_proc_macros
292    {
293        sess.dcx().emit_err(diagnostics::UnstableWasmProcMacro);
294    }
295
296    if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
297        feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
298    }
299
300    if is_proc_macro_crate && !sess.sanitizers().is_empty() {
301        sess.dcx().emit_err(diagnostics::CannotSanitizeProcMacro);
302    }
303
304    if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
305        sess.dcx().emit_warn(diagnostics::ProcMacroCratePanicAbort);
306    }
307
308    sess.time("maybe_create_a_macro_crate", || {
309        let is_test_crate = sess.is_test_crate();
310        rustc_builtin_macros::proc_macro_harness::inject(
311            &mut krate,
312            sess,
313            features,
314            resolver,
315            is_proc_macro_crate,
316            has_proc_macro_decls,
317            is_test_crate,
318            sess.dcx(),
319        )
320    });
321
322    // Done with macro expansion!
323
324    resolver.resolve_crate(&krate);
325
326    CStore::from_tcx(tcx).report_session_incompatibilities(tcx, &krate);
327    krate
328}
329
330fn print_macro_stats(ecx: &ExtCtxt<'_>) {
331    use std::fmt::Write;
332
333    let crate_name = ecx.ecfg.crate_name.as_str();
334    let crate_name = if crate_name == "build_script_build" {
335        // This is a build script. Get the package name from the environment.
336        let pkg_name =
337            std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "<unknown crate>".to_string());
338        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} build script", pkg_name))
    })format!("{pkg_name} build script")
339    } else {
340        crate_name.to_string()
341    };
342
343    // No instability because we immediately sort the produced vector.
344    #[allow(rustc::potential_query_instability)]
345    let mut macro_stats: Vec<_> = ecx
346        .macro_stats
347        .iter()
348        .map(|((name, kind), stat)| {
349            // This gives the desired sort order: sort by bytes, then lines, etc.
350            (stat.bytes, stat.lines, stat.uses, name, *kind)
351        })
352        .collect();
353    macro_stats.sort_unstable();
354    macro_stats.reverse(); // bigger items first
355
356    let prefix = "macro-stats";
357    let name_w = 32;
358    let uses_w = 7;
359    let lines_w = 11;
360    let avg_lines_w = 11;
361    let bytes_w = 11;
362    let avg_bytes_w = 11;
363    let banner_w = name_w + uses_w + lines_w + avg_lines_w + bytes_w + avg_bytes_w;
364
365    // We write all the text into a string and print it with a single
366    // `eprint!`. This is an attempt to minimize interleaved text if multiple
367    // rustc processes are printing macro-stats at the same time (e.g. with
368    // `RUSTFLAGS='-Zmacro-stats' cargo build`). It still doesn't guarantee
369    // non-interleaving, though.
370    let mut s = String::new();
371    _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
372    _ = s.write_fmt(format_args!("{1} MACRO EXPANSION STATS: {0}\n", crate_name,
        prefix))writeln!(s, "{prefix} MACRO EXPANSION STATS: {}", crate_name);
373    _ = s.write_fmt(format_args!("{6} {0:<7$}{1:>8$}{2:>9$}{3:>10$}{4:>11$}{5:>12$}\n",
        "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
        prefix, name_w, uses_w, lines_w, avg_lines_w, bytes_w, avg_bytes_w))writeln!(
374        s,
375        "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
376        "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
377    );
378    _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
379    // It's helpful to print something when there are no entries, otherwise it
380    // might look like something went wrong.
381    if macro_stats.is_empty() {
382        _ = s.write_fmt(format_args!("{0} (none)\n", prefix))writeln!(s, "{prefix} (none)");
383    }
384    for (bytes, lines, uses, name, kind) in macro_stats {
385        let mut name = ExpnKind::Macro(kind, *name).descr();
386        let uses_with_underscores = thousands::usize_with_underscores(uses);
387        let avg_lines = lines as f64 / uses as f64;
388        let avg_bytes = bytes as f64 / uses as f64;
389
390        // Ensure the "Macro Name" and "Uses" columns are as compact as possible.
391        let mut uses_w = uses_w;
392        if name.len() + uses_with_underscores.len() >= name_w + uses_w {
393            // The name would abut or overlap the uses value. Print the name
394            // on a line by itself, then set the name to empty and print things
395            // normally, to show the stats on the next line.
396            _ = s.write_fmt(format_args!("{1} {0:<2$}\n", name, prefix, name_w))writeln!(s, "{prefix} {:<name_w$}", name);
397            name = String::new();
398        } else if name.len() >= name_w {
399            // The name won't abut or overlap with the uses value, but it does
400            // overlap with the empty part of the uses column. Shrink the width
401            // of the uses column to account for the excess name length.
402            uses_w -= name.len() - name_w;
403        };
404
405        _ = s.write_fmt(format_args!("{6} {0:<7$}{1:>8$}{2:>9$}{3:>10$}{4:>11$}{5:>12$}\n",
        name, uses_with_underscores, thousands::usize_with_underscores(lines),
        thousands::f64p1_with_underscores(avg_lines),
        thousands::usize_with_underscores(bytes),
        thousands::f64p1_with_underscores(avg_bytes), prefix, name_w, uses_w,
        lines_w, avg_lines_w, bytes_w, avg_bytes_w))writeln!(
406            s,
407            "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
408            name,
409            uses_with_underscores,
410            thousands::usize_with_underscores(lines),
411            thousands::f64p1_with_underscores(avg_lines),
412            thousands::usize_with_underscores(bytes),
413            thousands::f64p1_with_underscores(avg_bytes),
414        );
415    }
416    _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
417    { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
418}
419
420fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
421    let sess = tcx.sess;
422    let (resolver, krate) = tcx.resolver_for_lowering();
423    let resolver = &*resolver.borrow();
424    let krate = &*krate.borrow();
425    let mut lint_buffer = resolver.lint_buffer.steal();
426
427    if sess.opts.unstable_opts.input_stats {
428        input_stats::print_ast_stats(tcx, krate);
429    }
430
431    // Needs to go *after* expansion to be able to check the results of macro expansion.
432    sess.time("complete_gated_feature_checking", || {
433        rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
434    });
435
436    // Add all buffered lints from the `ParseSess` to the `Session`.
437    sess.psess.buffered_lints.with_lock(|buffered_lints| {
438        let buffered_lints = buffered_lints.take().expect("Buffered lints are not stolen yet");
439        {
    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/passes.rs:439",
                        "rustc_interface::passes", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_interface/src/passes.rs"),
                        ::tracing_core::__macro_support::Option::Some(439u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                        ::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!("{0} parse sess buffered_lints",
                                                    buffered_lints.len()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("{} parse sess buffered_lints", buffered_lints.len());
440        for early_lint in buffered_lints {
441            lint_buffer.add_early_lint(early_lint);
442        }
443    });
444
445    // Gate identifiers containing invalid Unicode codepoints that were recovered during lexing.
446    sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
447        for (ident, mut spans) in identifiers.drain(..) {
448            spans.sort_by_key(|span| span.lo_hi());
449            if ident == sym::ferris {
450                enum FerrisFix {
451                    SnakeCase,
452                    ScreamingSnakeCase,
453                    PascalCase,
454                }
455
456                impl FerrisFix {
457                    const fn as_str(self) -> &'static str {
458                        match self {
459                            FerrisFix::SnakeCase => "ferris",
460                            FerrisFix::ScreamingSnakeCase => "FERRIS",
461                            FerrisFix::PascalCase => "Ferris",
462                        }
463                    }
464                }
465
466                let first_span = spans[0];
467                let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
468                let ferris_fix = prev_source
469                    .map_or(FerrisFix::SnakeCase, |source| {
470                        let mut source_before_ferris = source.split_whitespace().rev();
471                        match source_before_ferris.next() {
472                            Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
473                                FerrisFix::PascalCase
474                            }
475                            Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
476                            Some("mut") if source_before_ferris.next() == Some("static") => {
477                                FerrisFix::ScreamingSnakeCase
478                            }
479                            _ => FerrisFix::SnakeCase,
480                        }
481                    })
482                    .as_str();
483
484                sess.dcx().emit_err(diagnostics::FerrisIdentifier {
485                    spans,
486                    first_span,
487                    ferris_fix,
488                });
489            } else {
490                sess.dcx().emit_err(diagnostics::EmojiIdentifier { spans, ident });
491            }
492        }
493    });
494
495    let lint_store = unerased_lint_store(tcx.sess);
496    rustc_lint::check_ast_node(
497        sess,
498        tcx.features(),
499        false,
500        lint_store,
501        tcx.registered_lint_tools(()),
502        Some(lint_buffer),
503        EarlyCheckNode::CrateRoot(&*krate, &*krate.attrs),
504    )
505}
506
507fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
508    let value = env::var_os(key);
509
510    let value_tcx = value.as_ref().map(|value| tcx.arena.alloc_os_str(value));
511
512    // Also add the variable to Cargo's dependency tracking
513    //
514    // NOTE: This only works for passes run before `write_dep_info`. See that
515    // for extension points for configuring environment variables to be
516    // properly change-tracked.
517    tcx.sess.env_depinfo.borrow_mut().insert((
518        Symbol::intern(&key.to_string_lossy()),
519        value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(value)),
520    ));
521
522    value_tcx
523}
524
525// Returns all the paths that correspond to generated files.
526fn generated_output_paths(
527    tcx: TyCtxt<'_>,
528    outputs: &OutputFilenames,
529    exact_name: bool,
530    crate_name: Symbol,
531) -> Vec<PathBuf> {
532    let sess = tcx.sess;
533    let mut out_filenames = Vec::new();
534    for output_type in sess.opts.output_types.keys() {
535        let out_filename = outputs.path(*output_type);
536        let file = out_filename.as_path().to_path_buf();
537        match *output_type {
538            // If the filename has been overridden using `-o`, it will not be modified
539            // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
540            OutputType::Exe if !exact_name => {
541                for crate_type in tcx.crate_types().iter() {
542                    let p = filename_for_input(sess, *crate_type, crate_name, outputs);
543                    out_filenames.push(p.as_path().to_path_buf());
544                }
545            }
546            OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
547                // Don't add the dep-info output when omitting it from dep-info targets
548            }
549            OutputType::DepInfo if out_filename.is_stdout() => {
550                // Don't add the dep-info output when it goes to stdout
551            }
552            _ => {
553                out_filenames.push(file);
554            }
555        }
556    }
557    out_filenames
558}
559
560fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
561    let input_path = try_canonicalize(input_path).ok();
562    if input_path.is_none() {
563        return false;
564    }
565    output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
566}
567
568fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
569    output_paths.iter().find(|output_path| output_path.is_dir())
570}
571
572fn escape_dep_filename(filename: &str) -> String {
573    // Apparently clang and gcc *only* escape spaces:
574    // https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
575    filename.replace(' ', "\\ ")
576}
577
578// Makefile comments only need escaping newlines and `\`.
579// The result can be unescaped by anything that can unescape `escape_default` and friends.
580fn escape_dep_env(symbol: Symbol) -> String {
581    let s = symbol.as_str();
582    let mut escaped = String::with_capacity(s.len());
583    for c in s.chars() {
584        match c {
585            '\n' => escaped.push_str(r"\n"),
586            '\r' => escaped.push_str(r"\r"),
587            '\\' => escaped.push_str(r"\\"),
588            _ => escaped.push(c),
589        }
590    }
591    escaped
592}
593
594fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
595    // Write out dependency rules to the dep-info file if requested
596    let sess = tcx.sess;
597    if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
598        return;
599    }
600    let deps_output = outputs.path(OutputType::DepInfo);
601    let deps_filename = deps_output.as_path();
602
603    let result = try {
604        // Build a list of files used to compile the output and
605        // write Makefile-compatible dependency rules
606        let mut files: IndexMap<String, (u64, Option<SourceFileHash>)> = sess
607            .source_map()
608            .files()
609            .iter()
610            .filter(|fmap| fmap.is_real_file())
611            .filter(|fmap| !fmap.is_imported())
612            .map(|fmap| {
613                (
614                    escape_dep_filename(&fmap.name.prefer_local_unconditionally().to_string()),
615                    (
616                        // This needs to be unnormalized,
617                        // as external tools wouldn't know how rustc normalizes them
618                        fmap.unnormalized_source_len as u64,
619                        fmap.checksum_hash,
620                    ),
621                )
622            })
623            .collect();
624
625        let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
626
627        // Account for explicitly marked-to-track files
628        // (e.g. accessed in proc macros).
629        let file_depinfo = sess.file_depinfo.borrow();
630
631        let normalize_path = |path: PathBuf| escape_dep_filename(&path.to_string_lossy());
632
633        // The entries will be used to declare dependencies between files in a
634        // Makefile-like output, so the iteration order does not matter.
635        fn hash_iter_files<P: AsRef<Path>>(
636            it: impl Iterator<Item = P>,
637            checksum_hash_algo: Option<SourceFileHashAlgorithm>,
638        ) -> impl Iterator<Item = (P, (u64, Option<SourceFileHash>))> {
639            it.map(move |path| {
640                match checksum_hash_algo.and_then(|algo| {
641                    fs::File::open(path.as_ref())
642                        .and_then(|mut file| {
643                            SourceFileHash::new(algo, &mut file).map(|h| (file, h))
644                        })
645                        .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
646                        .map_err(|e| {
647                            {
    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/passes.rs:647",
                        "rustc_interface::passes", ::tracing::Level::ERROR,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_interface/src/passes.rs"),
                        ::tracing_core::__macro_support::Option::Some(647u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::ERROR <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::ERROR <=
                    ::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!("failed to compute checksum, omitting it from dep-info {0} {1}",
                                                    path.as_ref().display(), e) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
}tracing::error!(
648                                "failed to compute checksum, omitting it from dep-info {} {e}",
649                                path.as_ref().display()
650                            )
651                        })
652                        .ok()
653                }) {
654                    Some((file_len, checksum)) => (path, (file_len, Some(checksum))),
655                    None => (path, (0, None)),
656                }
657            })
658        }
659
660        let extra_tracked_files = hash_iter_files(
661            file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
662            checksum_hash_algo,
663        );
664        files.extend(extra_tracked_files);
665
666        // We also need to track used PGO profile files
667        if let Some(ref profile_instr) = sess.opts.cg.profile_use {
668            files.extend(hash_iter_files(
669                iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
670                checksum_hash_algo,
671            ));
672        }
673        if let Some(ref profile_sample) = sess.opts.cg.profile_sample_use {
674            files.extend(hash_iter_files(
675                iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
676                checksum_hash_algo,
677            ));
678        }
679
680        // Debugger visualizer files
681        for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
682            files.extend(hash_iter_files(
683                iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
684                checksum_hash_algo,
685            ));
686        }
687
688        if sess.binary_dep_depinfo() {
689            if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
690                if backend.contains('.') {
691                    // If the backend name contain a `.`, it is the path to an external dynamic
692                    // library. If not, it is not a path.
693                    files.extend(hash_iter_files(
694                        iter::once(backend.to_string()),
695                        checksum_hash_algo,
696                    ));
697                }
698            }
699
700            for &cnum in tcx.crates(()) {
701                let source = tcx.used_crate_source(cnum);
702                if let Some(path) = &source.dylib {
703                    files.extend(hash_iter_files(
704                        iter::once(escape_dep_filename(&path.display().to_string())),
705                        checksum_hash_algo,
706                    ));
707                }
708                if let Some(path) = &source.rlib {
709                    files.extend(hash_iter_files(
710                        iter::once(escape_dep_filename(&path.display().to_string())),
711                        checksum_hash_algo,
712                    ));
713                }
714                if let Some(path) = &source.rmeta {
715                    files.extend(hash_iter_files(
716                        iter::once(escape_dep_filename(&path.display().to_string())),
717                        checksum_hash_algo,
718                    ));
719                }
720            }
721        }
722
723        let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
724            for path in out_filenames {
725                file.write_fmt(format_args!("{0}: {1}\n\n", path.display(),
        files.keys().map(String::as_str).intersperse(" ").collect::<String>()))writeln!(
726                    file,
727                    "{}: {}\n",
728                    path.display(),
729                    files.keys().map(String::as_str).intersperse(" ").collect::<String>()
730                )?;
731            }
732
733            // Emit a fake target for each input file to the compilation. This
734            // prevents `make` from spitting out an error if a file is later
735            // deleted. For more info see #28735
736            for path in files.keys() {
737                file.write_fmt(format_args!("{0}:\n", path))writeln!(file, "{path}:")?;
738            }
739
740            // Emit special comments with information about accessed environment variables.
741            let env_depinfo = sess.env_depinfo.borrow();
742            if !env_depinfo.is_empty() {
743                // We will soon sort, so the initial order does not matter.
744                #[allow(rustc::potential_query_instability)]
745                let mut envs: Vec<_> = env_depinfo
746                    .iter()
747                    .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
748                    .collect();
749                envs.sort_unstable();
750                file.write_fmt(format_args!("\n"))writeln!(file)?;
751                for (k, v) in envs {
752                    file.write_fmt(format_args!("# env-dep:{0}", k))write!(file, "# env-dep:{k}")?;
753                    if let Some(v) = v {
754                        file.write_fmt(format_args!("={0}", v))write!(file, "={v}")?;
755                    }
756                    file.write_fmt(format_args!("\n"))writeln!(file)?;
757                }
758            }
759
760            // If caller requested this information, add special comments about source file checksums.
761            // These are not necessarily the same checksums as was used in the debug files.
762            if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
763                files
764                    .iter()
765                    .filter_map(|(path, (file_len, hash_algo))| {
766                        hash_algo.map(|hash_algo| (path, file_len, hash_algo))
767                    })
768                    .try_for_each(|(path, file_len, checksum_hash)| {
769                        file.write_fmt(format_args!("# checksum:{0} file_len:{1} {2}\n",
        checksum_hash, file_len, path))writeln!(file, "# checksum:{checksum_hash} file_len:{file_len} {path}")
770                    })?;
771            }
772
773            Ok(())
774        };
775
776        match deps_output {
777            OutFileName::Stdout => {
778                let mut file = BufWriter::new(io::stdout());
779                write_deps_to_file(&mut file)?;
780            }
781            OutFileName::Real(ref path) => {
782                let mut file = fs::File::create_buffered(path)?;
783                write_deps_to_file(&mut file)?;
784            }
785        }
786    };
787
788    match result {
789        Ok(_) => {
790            if sess.opts.json_artifact_notifications {
791                sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
792            }
793        }
794        Err(error) => {
795            sess.dcx()
796                .emit_fatal(diagnostics::ErrorWritingDependencies { path: deps_filename, error });
797        }
798    }
799}
800
801fn resolver_for_lowering_raw<'tcx>(
802    tcx: TyCtxt<'tcx>,
803    (): (),
804) -> (&'tcx Steal<ResolverAstLowering<'tcx>>, &'tcx Steal<ast::Crate>, &'tcx ResolverGlobalCtxt) {
805    let arenas = WorkerLocal::new(|_| Resolver::arenas());
806    let _ = tcx.registered_attr_tools(()); // Uses `crate_for_resolver`.
807    let _ = tcx.registered_lint_tools(()); // Uses `crate_for_resolver`.
808    let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
809    let mut resolver = Resolver::new(
810        tcx,
811        &pre_configured_attrs,
812        krate.spans.inner_span,
813        krate.spans.inject_use_span,
814        &arenas,
815    );
816    let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
817
818    // Don't mutate the cstore or stable crate id map from here on.
819    tcx.untracked().freeze_cstore();
820
821    let ResolverOutputs {
822        global_ctxt: untracked_resolutions,
823        ast_lowering: untracked_resolver_for_lowering,
824    } = resolver.into_outputs();
825
826    (
827        tcx.arena.alloc(Steal::new(untracked_resolver_for_lowering)),
828        tcx.arena.alloc(Steal::new(krate)),
829        tcx.arena.alloc(untracked_resolutions),
830    )
831}
832
833pub fn write_dep_info(tcx: TyCtxt<'_>) {
834    // Make sure name resolution and macro expansion is run for
835    // the side-effect of providing a complete set of all
836    // accessed files and env vars.
837    let _ = tcx.resolver_for_lowering();
838
839    let sess = tcx.sess;
840    let _timer = sess.timer("write_dep_info");
841    let crate_name = tcx.crate_name(LOCAL_CRATE);
842
843    let outputs = tcx.output_filenames(());
844    let output_paths =
845        generated_output_paths(tcx, outputs, sess.io.output_file.is_some(), crate_name);
846
847    // Ensure the source file isn't accidentally overwritten during compilation.
848    if let Some(input_path) = sess.io.input.opt_path() {
849        if sess.opts.will_create_output_file() {
850            if output_contains_path(&output_paths, input_path) {
851                sess.dcx()
852                    .emit_fatal(diagnostics::InputFileWouldBeOverWritten { path: input_path });
853            }
854            if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
855                sess.dcx().emit_fatal(diagnostics::GeneratedFileConflictsWithDirectory {
856                    input_path,
857                    dir_path,
858                });
859            }
860        }
861    }
862
863    if let Some(ref dir) = sess.io.temps_dir {
864        if fs::create_dir_all(dir).is_err() {
865            sess.dcx().emit_fatal(diagnostics::TempsDirError);
866        }
867    }
868
869    write_out_deps(tcx, outputs, &output_paths);
870
871    let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
872        && sess.opts.output_types.len() == 1;
873
874    if !only_dep_info {
875        if let Some(ref dir) = sess.io.output_dir {
876            if fs::create_dir_all(dir).is_err() {
877                sess.dcx().emit_fatal(diagnostics::OutDirError);
878            }
879        }
880    }
881}
882
883pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
884    if !tcx.crate_types().contains(&rustc_structures::CrateType::Sdylib) {
885        return;
886    }
887    let _timer = tcx.sess.timer("write_interface");
888    let (_, krate) = tcx.resolver_for_lowering();
889
890    let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
891        &*krate.borrow(),
892        tcx.sess.psess.edition,
893        &tcx.sess.psess.attr_id_generator,
894    );
895    let export_output = tcx.output_filenames(()).interface_path();
896    let mut file = fs::File::create_buffered(&export_output).unwrap_or_else(|error| {
897        tcx.dcx().emit_fatal(diagnostics::FailedWritingFile { path: &export_output, error })
898    });
899    if let Err(error) = file.write_fmt(format_args!("{0}", krate))write!(file, "{}", krate) {
900        tcx.dcx().emit_fatal(diagnostics::FailedWritingFile { path: &export_output, error });
901    }
902}
903
904pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
905    let providers = &mut Providers::default();
906    providers.queries.analysis = analysis;
907    providers.queries.resolver_for_lowering_raw = resolver_for_lowering_raw;
908    providers.queries.stripped_cfg_items = |tcx, _| &tcx.resolutions(()).stripped_cfg_items[..];
909    providers.queries.get_lang_items = |tcx, ()| &tcx.resolutions(()).lang_items;
910    providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).2;
911    providers.queries.early_lint_checks = early_lint_checks;
912    providers.queries.env_var_os = env_var_os;
913    providers.queries.proc_macro_decls_static = |tcx, _| tcx.hir_crate_items(()).proc_macro_decls();
914    rustc_ast_lowering::provide(&mut providers.queries);
915    rustc_expand_queries::provide(&mut providers.queries);
916    rustc_const_eval::provide(providers);
917    rustc_middle::hir::provide(&mut providers.queries);
918    rustc_borrowck::provide(&mut providers.queries);
919    rustc_incremental::provide(providers);
920    rustc_mir_build::provide(providers);
921    rustc_mir_dataflow::provide(providers);
922    rustc_mir_transform::provide(providers);
923    rustc_monomorphize::provide(providers);
924    rustc_privacy::provide(&mut providers.queries);
925    rustc_query_impl::provide(providers);
926    rustc_resolve::provide(&mut providers.queries);
927    rustc_hir_analysis::provide(&mut providers.queries);
928    rustc_hir_typeck::provide(&mut providers.queries);
929    ty::provide(&mut providers.queries);
930    traits::provide(&mut providers.queries);
931    solve::provide(&mut providers.queries);
932    rustc_passes::provide(&mut providers.queries);
933    rustc_traits::provide(&mut providers.queries);
934    rustc_ty_utils::provide(&mut providers.queries);
935    rustc_metadata::provide(providers);
936    rustc_lint::provide(&mut providers.queries);
937    rustc_symbol_mangling::provide(&mut providers.queries);
938    rustc_codegen_ssa::provide(providers);
939    *providers
940});
941
942pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
943    compiler: &Compiler,
944    krate: rustc_ast::Crate,
945    f: F,
946) -> (T, Option<IncrCompSession>) {
947    let sess = &compiler.sess;
948
949    let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
950
951    let crate_name = get_crate_name(sess, &pre_configured_attrs);
952    let crate_types = collect_crate_types(
953        sess,
954        &compiler.codegen_backend.supported_crate_types(sess),
955        compiler.codegen_backend.name(),
956        &pre_configured_attrs,
957        krate.spans.inner_span,
958    );
959    let stable_crate_id = StableCrateId::new(
960        crate_name,
961        crate_types.contains(&CrateType::Executable),
962        sess.opts.cg.metadata.clone(),
963        sess.cfg_version,
964    );
965
966    let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
967
968    let (dep_graph, incr_comp_session) = setup_dep_graph(sess, crate_name, stable_crate_id);
969
970    let cstore =
971        FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
972    let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
973
974    let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
975    let untracked = Untracked {
976        cstore,
977        source_span: AppendOnlyIndexVec::new(),
978        definitions,
979        stable_crate_ids,
980        local_crate_hash: OnceLock::new(),
981    };
982
983    // We're constructing the HIR here; we don't care what we will
984    // read, since we haven't even constructed the *input* to
985    // incr. comp. yet.
986    dep_graph.assert_ignored();
987
988    let query_result_on_disk_cache =
989        rustc_incremental::load_query_result_cache(sess, incr_comp_session.as_ref());
990
991    let codegen_backend = &compiler.codegen_backend;
992    let mut providers = *DEFAULT_QUERY_PROVIDERS;
993    codegen_backend.provide(&mut providers);
994
995    if let Some(callback) = compiler.override_queries {
996        callback(sess, &mut providers);
997    }
998
999    let incremental = dep_graph.is_fully_enabled();
1000    let track_present = incremental
1001        || sess.opts.unstable_opts.incremental_verify_ich
1002        || sess.prof.enabled()
1003        || truecfg!(debug_assertions);
1004
1005    // Note: this function body is the origin point of the widely-used 'tcx lifetime.
1006    //
1007    // `gcx_cell` is defined here and `&gcx_cell` is passed to `create_global_ctxt`, which then
1008    // actually creates the `GlobalCtxt` with a `gcx_cell.get_or_init(...)` call. This is done so
1009    // that the resulting reference has the type `&'tcx GlobalCtxt<'tcx>`, which is what `TyCtxt`
1010    // needs. If we defined and created the `GlobalCtxt` within `create_global_ctxt` then its type
1011    // would be `&'a GlobalCtxt<'tcx>`, with two lifetimes.
1012    //
1013    // Similarly, by creating `arena` here and passing in `&arena`, that reference has the type
1014    // `&'tcx WorkerLocal<Arena<'tcx>>`, also with one lifetime. And likewise for `hir_arena`.
1015
1016    let gcx_cell = OnceLock::new();
1017    let arena = WorkerLocal::new(|_| Arena::default());
1018    let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
1019
1020    let res = TyCtxt::create_global_ctxt(
1021        &gcx_cell,
1022        &compiler.sess,
1023        crate_types,
1024        stable_crate_id,
1025        &arena,
1026        &hir_arena,
1027        untracked,
1028        incr_comp_session.as_ref(),
1029        dep_graph,
1030        rustc_query_impl::query_system(
1031            &arena,
1032            providers.queries,
1033            providers.extern_queries,
1034            query_result_on_disk_cache,
1035            incremental,
1036            track_present,
1037        ),
1038        providers.hooks,
1039        compiler.current_gcx.clone(),
1040        |tcx| {
1041            let feed = tcx.create_crate_num(stable_crate_id).unwrap();
1042            {
    match (&feed.key(), &LOCAL_CRATE) {
        (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!(feed.key(), LOCAL_CRATE);
1043            feed.crate_name(crate_name);
1044
1045            let feed = tcx.feed_unit_query();
1046            let features = tcx.arena.alloc(rustc_expand::config::features(
1047                tcx.sess,
1048                &pre_configured_attrs,
1049                crate_name,
1050            ));
1051            feed.features_query(features);
1052            feed.limits(limits::get_limits(&pre_configured_attrs, tcx.sess, features));
1053            feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
1054            feed.output_filenames(Arc::new(outputs));
1055
1056            // There are two paths out of `f`.
1057            // - Normal exit.
1058            // - Panic, e.g. triggered by `abort_if_errors` or a fatal error.
1059            //
1060            // If a panic occurs, we still need to wind down the self-profiler to correctly record
1061            // the query events that are still in flight. Otherwise, they will be invalid and will
1062            // show up as "<unknown>" in the profiling data.
1063            let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(tcx)));
1064            let res = match res {
1065                Ok(res) => res,
1066                Err(err) => {
1067                    tcx.alloc_self_profile_query_strings();
1068
1069                    // Resume unwinding if a panic happened.
1070                    std::panic::resume_unwind(err);
1071                }
1072            };
1073
1074            tcx.finish();
1075            res
1076        },
1077    );
1078
1079    (res, incr_comp_session)
1080}
1081
1082struct DiagCallback<'tcx> {
1083    callback: Box<
1084        dyn for<'b> FnOnce(DiagCtxtHandle<'b>, Level, &dyn Any) -> Diag<'b> + DynSend + DynSync,
1085    >,
1086    tcx: TyCtxt<'tcx>,
1087}
1088
1089impl<'a, 'tcx> Diagnostic<'a> for DiagCallback<'tcx> {
1090    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
1091        (self.callback)(dcx, level, self.tcx.sess)
1092    }
1093}
1094
1095pub fn emit_delayed_lints(tcx: TyCtxt<'_>) {
1096    for owner_id in tcx.hir_crate_items(()).owners() {
1097        if let Some(delayed_lints) = tcx.opt_ast_lowering_delayed_lints(owner_id) {
1098            for lint in delayed_lints.steal() {
1099                tcx.emit_node_span_lint(
1100                    lint.lint_id.lint,
1101                    lint.id,
1102                    lint.span.clone(),
1103                    DiagCallback { callback: lint.callback, tcx },
1104                );
1105            }
1106        }
1107    }
1108}
1109
1110/// Runs all analyses that we guarantee to run, even if errors were reported in earlier analyses.
1111/// This function never fails.
1112fn run_required_analyses(tcx: TyCtxt<'_>) {
1113    if tcx.sess.opts.unstable_opts.input_stats {
1114        rustc_passes::input_stats::print_hir_stats(tcx);
1115    }
1116    // When using rustdoc's "jump to def" feature, it enters this code and `check_crate`
1117    // is not defined. So we need to cfg it out.
1118    #[cfg(all(not(doc), debug_assertions))]
1119    rustc_passes::hir_id_validator::check_crate(tcx);
1120
1121    // Prefetch this to prevent multiple threads from blocking on it later.
1122    // This is needed since the `hir_id_validator::check_crate` call above is not guaranteed
1123    // to use `hir_crate_items`.
1124    tcx.ensure_done().hir_crate_items(());
1125
1126    tcx.untracked().definitions.write().commit_end_of_determinism();
1127
1128    rustc_passes::delegation::check_glob_and_list_delegations_target_expr(tcx);
1129
1130    let sess = tcx.sess;
1131    sess.time("misc_checking_1", || {
1132        par_fns(&mut [
1133            &mut || {
1134                sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1135                sess.time("check_externally_implementable_items", || {
1136                    tcx.ensure_ok().check_externally_implementable_items(())
1137                });
1138
1139                sess.time("looking_for_derive_registrar", || {
1140                    tcx.ensure_ok().proc_macro_decls_static(())
1141                });
1142
1143                CStore::from_tcx(tcx).report_unused_deps(tcx);
1144            },
1145            &mut || {
1146                tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1147                tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1148                tcx.par_hir_for_each_module(|module| {
1149                    tcx.ensure_ok().check_mod_attrs(module);
1150                    tcx.ensure_ok().check_mod_unstable_api_usage(module);
1151                });
1152            },
1153        ]);
1154    });
1155
1156    sess.time("emit_ast_lowering_delayed_lints", || {
1157        emit_delayed_lints(tcx);
1158    });
1159
1160    rustc_hir_analysis::check_crate(tcx);
1161    // Freeze definitions as we don't add new ones at this point.
1162    // We need to wait until now since we synthesize a by-move body
1163    // for all coroutine-closures.
1164    //
1165    // This improves performance by allowing lock-free access to them.
1166    tcx.untracked().definitions.freeze();
1167
1168    sess.time("MIR_checking", || {
1169        tcx.par_hir_body_owners(|def_id| {
1170            let not_typeck_child = !tcx.is_typeck_child(def_id.to_def_id());
1171            if not_typeck_child {
1172                // Child unsafety and borrowck happens together with the parent
1173                tcx.ensure_ok().check_unsafety(def_id);
1174            }
1175            if tcx.is_trivial_const(def_id) {
1176                return;
1177            }
1178            if not_typeck_child {
1179                tcx.ensure_ok().mir_borrowck(def_id);
1180                tcx.ensure_ok().check_transmutes(def_id);
1181                if !tcx.sess.opts.unstable_opts.offload.is_empty() {
1182                    tcx.ensure_ok().check_offloads(def_id);
1183                }
1184            }
1185            tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1186            tcx.ensure_ok().check_liveness(def_id);
1187
1188            // If we need to codegen, ensure that we emit all errors from
1189            // `mir_drops_elaborated_and_const_checked` now, to avoid discovering
1190            // them later during codegen.
1191            if tcx.sess.opts.output_types.should_codegen()
1192                || tcx.hir_body_const_context(def_id).is_some()
1193            {
1194                tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1195            }
1196            if tcx.is_coroutine(def_id.to_def_id())
1197                && (!tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()))
1198            {
1199                // Eagerly check the unsubstituted layout for cycles.
1200                tcx.ensure_ok()
1201                    .layout_of(ty::TypingEnv::codegen(tcx, def_id.to_def_id()).as_query_input(
1202                        tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
1203                    ));
1204            }
1205        });
1206    });
1207
1208    sess.time("layout_testing", || layout_test::test_layout(tcx));
1209    sess.time("abi_testing", || abi_test::test_abi(tcx));
1210}
1211
1212/// Runs the type-checking, region checking and other miscellaneous analysis
1213/// passes on the crate.
1214fn analysis(tcx: TyCtxt<'_>, (): ()) {
1215    run_required_analyses(tcx);
1216
1217    let sess = tcx.sess;
1218
1219    // Avoid overwhelming user with errors if borrow checking failed.
1220    // I'm not sure how helpful this is, to be honest, but it avoids a
1221    // lot of annoying errors in the ui tests (basically,
1222    // lint warnings and so on -- kindck used to do this abort, but
1223    // kindck is gone now). -nmatsakis
1224    //
1225    // But we exclude lint errors from this, because lint errors are typically
1226    // less serious and we're more likely to want to continue (#87337).
1227    if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1228        guar.raise_fatal();
1229    }
1230
1231    sess.time("misc_checking_3", || {
1232        par_fns(&mut [
1233            &mut || {
1234                tcx.ensure_ok().effective_visibilities(());
1235
1236                par_fns(&mut [
1237                    &mut || {
1238                        tcx.par_hir_for_each_module(|module| {
1239                            tcx.ensure_ok().check_private_in_public(module)
1240                        })
1241                    },
1242                    &mut || {
1243                        tcx.par_hir_for_each_module(|module| {
1244                            tcx.ensure_ok().check_mod_deathness(module)
1245                        });
1246                    },
1247                    &mut || {
1248                        sess.time("lint_checking", || {
1249                            rustc_lint::check_crate(tcx);
1250                        });
1251                    },
1252                    &mut || {
1253                        tcx.ensure_ok().clashing_extern_declarations(());
1254                    },
1255                ]);
1256            },
1257            &mut || {
1258                sess.time("privacy_checking_modules", || {
1259                    tcx.par_hir_for_each_module(|module| {
1260                        tcx.ensure_ok().check_mod_privacy(module);
1261                    });
1262                });
1263            },
1264        ]);
1265
1266        // This check has to be run after all lints are done processing. We don't
1267        // define a lint filter, as all lint checks should have finished at this point.
1268        sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1269
1270        // This query is only invoked normally if a diagnostic is emitted that needs any
1271        // diagnostic item. If the crate compiles without checking any diagnostic items,
1272        // we will fail to emit overlap diagnostics. Thus we invoke it here unconditionally.
1273        let _ = tcx.all_diagnostic_items(());
1274
1275        // This query is only invoked normally if a diagnostic is emitted that needs any
1276        // canonical symbol. If the crate compiles without checking any runtime symbols,
1277        // we will fail to emit overlap diagnostics. Thus we invoke it here unconditionally.
1278        let _ = tcx.all_canonical_symbols(());
1279    });
1280
1281    // If `-Zvalidate-mir` is set, we also want to compute the final MIR for each item
1282    // (either its `mir_for_ctfe` or `optimized_mir`) since that helps uncover any bugs
1283    // in MIR optimizations that may only be reachable through codegen, or other codepaths
1284    // that requires the optimized/ctfe MIR, coroutine bodies, or evaluating consts.
1285    // Nevertheless, wait after type checking is finished, as optimizing code that does not
1286    // type-check is very prone to ICEs.
1287    if tcx.sess.opts.unstable_opts.validate_mir {
1288        sess.time("ensuring_final_MIR_is_computable", || {
1289            tcx.par_hir_body_owners(|def_id| {
1290                if !tcx.is_trivial_const(def_id) {
1291                    tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1292                }
1293            });
1294        });
1295    }
1296}
1297
1298/// Runs the codegen backend, after which the AST and analysis can
1299/// be discarded.
1300pub(crate) fn start_codegen<'tcx>(
1301    codegen_backend: &dyn CodegenBackend,
1302    tcx: TyCtxt<'tcx>,
1303) -> (Box<dyn Any>, CrateInfo, EncodedMetadata) {
1304    tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen);
1305
1306    // Hook for tests.
1307    if let Some((def_id, _)) = tcx.entry_fn(())
1308        && {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcDelayedBugFromInsideQuery)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool(..) |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcDelayedBugFromInsideQuery)
1309    {
1310        tcx.ensure_ok().trigger_delayed_bug(def_id);
1311    }
1312
1313    // Don't run this test assertions when not doing codegen. Compiletest tries to build
1314    // build-fail tests in check mode first and expects it to not give an error in that case.
1315    if tcx.sess.opts.output_types.should_codegen() {
1316        rustc_symbol_mangling::test::dump_symbol_names_and_def_paths(tcx);
1317    }
1318
1319    // Don't do code generation if there were any errors. Likewise if
1320    // there were any delayed bugs, because codegen will likely cause
1321    // more ICEs, obscuring the original problem.
1322    if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1323        guar.raise_fatal();
1324    }
1325
1326    {
    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/passes.rs:1326",
                        "rustc_interface::passes", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_interface/src/passes.rs"),
                        ::tracing_core::__macro_support::Option::Some(1326u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                        ::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!("Pre-codegen\n{0:?}",
                                                    tcx.debug_stats()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("Pre-codegen\n{:?}", tcx.debug_stats());
1327
1328    let metadata = match rustc_metadata::fs::encode_and_write_metadata(tcx) {
1329        Ok(metadata) => metadata,
1330        Err(guar) => guar.raise_fatal(),
1331    };
1332
1333    let is_host_metadata = tcx
1334        .sess
1335        .opts
1336        .unstable_opts
1337        .offload
1338        .iter()
1339        .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    rustc_session::config::Offload::HostMetadata(_) => true,
    _ => false,
}matches!(o, rustc_session::config::Offload::HostMetadata(_)));
1340
1341    let codegen = tcx.sess.time("codegen_crate", || {
1342        if tcx.sess.opts.unstable_opts.no_codegen
1343            || !tcx.sess.opts.output_types.should_codegen()
1344            || is_host_metadata
1345        {
1346            tcx.sess.dcx().abort_if_errors();
1347
1348            if is_host_metadata {
1349                rustc_monomorphize::write_host_metadata_offload_manifest(tcx);
1350            }
1351
1352            // Linker::link will skip join_codegen in case of a `CompiledModules` Any value.
1353            Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
1354        } else {
1355            codegen_backend.codegen_crate(tcx)
1356        }
1357    });
1358
1359    {
    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/passes.rs:1359",
                        "rustc_interface::passes", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_interface/src/passes.rs"),
                        ::tracing_core::__macro_support::Option::Some(1359u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
                        ::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!("Post-codegen\n{0:?}",
                                                    tcx.debug_stats()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("Post-codegen\n{:?}", tcx.debug_stats());
1360
1361    // This must run after monomorphization so that all generic types
1362    // have been instantiated.
1363    if tcx.sess.opts.unstable_opts.print_type_sizes {
1364        tcx.sess.code_stats.print_type_sizes();
1365    }
1366
1367    let crate_info = CrateInfo::new(tcx, codegen_backend.target_cpu(tcx.sess));
1368
1369    (codegen, crate_info, metadata)
1370}
1371
1372/// Compute and validate the crate name.
1373pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1374    // We validate *all* occurrences of `#![crate_name]`, pick the first find and
1375    // if a crate name was passed on the command line via `--crate-name` we enforce
1376    // that they match.
1377    // We perform the validation step here instead of later to ensure it gets run
1378    // in all code paths that require the crate name very early on, namely before
1379    // macro expansion.
1380
1381    let attr_crate_name =
1382        parse_crate_name(sess, krate_attrs, ShouldEmit::EarlyFatal { also_emit_lints: true });
1383
1384    let validate = |name, span| {
1385        rustc_session::output::validate_crate_name(sess, name, span);
1386        name
1387    };
1388
1389    if let Some(crate_name) = &sess.opts.crate_name {
1390        let crate_name = Symbol::intern(crate_name);
1391        if let Some((attr_crate_name, span)) = attr_crate_name
1392            && attr_crate_name != crate_name
1393        {
1394            sess.dcx().emit_err(diagnostics::CrateNameDoesNotMatch {
1395                span,
1396                crate_name,
1397                attr_crate_name,
1398            });
1399        }
1400        return validate(crate_name, None);
1401    }
1402
1403    if let Some((crate_name, span)) = attr_crate_name {
1404        return validate(crate_name, Some(span));
1405    }
1406
1407    if let Input::File(ref path) = sess.io.input
1408        && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1409    {
1410        if file_stem.starts_with('-') {
1411            sess.dcx().emit_err(diagnostics::CrateNameInvalid { crate_name: file_stem });
1412        } else {
1413            return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1414        }
1415    }
1416
1417    sym::rust_out
1418}
1419
1420pub(crate) fn parse_crate_name(
1421    sess: &Session,
1422    attrs: &[ast::Attribute],
1423    emit_errors: ShouldEmit,
1424) -> Option<(Symbol, Span)> {
1425    let Attribute::Parsed(AttributeKind::CrateName { name, name_span, .. }) =
1426        AttributeParser::parse_limited_sym_should_emit(
1427            sess,
1428            attrs,
1429            &[sym::crate_name],
1430            DUMMY_SP,
1431            None,
1432            emit_errors,
1433        )?
1434    else {
1435        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("crate_name is the only attr we could\'ve parsed here")));
};unreachable!("crate_name is the only attr we could've parsed here");
1436    };
1437
1438    Some((name, name_span))
1439}
1440
1441pub fn collect_crate_types(
1442    session: &Session,
1443    backend_crate_types: &[CrateType],
1444    codegen_backend_name: &'static str,
1445    attrs: &[ast::Attribute],
1446    crate_span: Span,
1447) -> Vec<CrateType> {
1448    // If we're generating a test executable, then ignore all other output
1449    // styles at all other locations
1450    if session.opts.test {
1451        if !session.target.executables {
1452            session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget {
1453                crate_type: CrateType::Executable,
1454                target_triple: &session.opts.target_triple,
1455            });
1456            return Vec::new();
1457        }
1458        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [CrateType::Executable]))vec![CrateType::Executable];
1459    }
1460
1461    // Shadow `sdylib` crate type in interface build.
1462    if session.opts.unstable_opts.build_sdylib_interface {
1463        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [CrateType::Rlib]))vec![CrateType::Rlib];
1464    }
1465
1466    // Only check command line flags if present. If no types are specified by
1467    // command line, then reuse the empty `base` Vec to hold the types that
1468    // will be found in crate attributes.
1469    // JUSTIFICATION: before wrapper fn is available
1470    #[allow(rustc::bad_opt_access)]
1471    let mut base = session.opts.crate_types.clone();
1472    if base.is_empty() {
1473        if let Some(Attribute::Parsed(AttributeKind::CrateType(crate_type))) =
1474            AttributeParser::parse_limited_sym_should_emit(
1475                session,
1476                attrs,
1477                &[sym::crate_type],
1478                crate_span,
1479                None,
1480                ShouldEmit::EarlyFatal { also_emit_lints: false },
1481            )
1482        {
1483            base.extend(crate_type);
1484        }
1485
1486        if base.is_empty() {
1487            base.push(default_output_for_target(session));
1488        } else {
1489            base.sort();
1490            base.dedup();
1491        }
1492    }
1493
1494    // GPU code is never run as a binary; the offload runtime looks up kernels by
1495    // name, and only cdylibs export their symbols.
1496    if session.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    Offload::Device(_) => true,
    _ => false,
}matches!(o, Offload::Device(_))) {
1497        for crate_type in &mut base {
1498            if *crate_type == CrateType::Executable {
1499                *crate_type = CrateType::Cdylib;
1500            }
1501        }
1502    }
1503
1504    base.retain(|crate_type| {
1505        if invalid_output_for_target(session, *crate_type) {
1506            session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget {
1507                crate_type: *crate_type,
1508                target_triple: &session.opts.target_triple,
1509            });
1510            false
1511        } else if !backend_crate_types.contains(crate_type) {
1512            session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForCodegenBackend {
1513                crate_type: *crate_type,
1514                codegen_backend: codegen_backend_name,
1515            });
1516            false
1517        } else {
1518            true
1519        }
1520    });
1521
1522    base
1523}
1524
1525/// Returns default crate type for target
1526///
1527/// Default crate type is used when crate type isn't provided neither
1528/// through cmd line arguments nor through crate attributes
1529///
1530/// It is CrateType::Executable for all platforms but iOS as there is no
1531/// way to run iOS binaries anyway without jailbreaking and
1532/// interaction with Rust code through static library is the only
1533/// option for now
1534fn default_output_for_target(sess: &Session) -> CrateType {
1535    if !sess.target.executables { CrateType::StaticLib } else { CrateType::Executable }
1536}