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