rustc_codegen_ssa/
base.rs

1use std::cmp;
2use std::collections::BTreeSet;
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use itertools::Itertools;
7use rustc_abi::FIRST_VARIANT;
8use rustc_ast::expand::allocator::{ALLOCATOR_METHODS, AllocatorKind, global_fn_name};
9use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
10use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
11use rustc_data_structures::sync::par_map;
12use rustc_data_structures::unord::UnordMap;
13use rustc_hir::def_id::{DefId, LOCAL_CRATE};
14use rustc_hir::lang_items::LangItem;
15use rustc_metadata::EncodedMetadata;
16use rustc_middle::bug;
17use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
18use rustc_middle::middle::debugger_visualizer::{DebuggerVisualizerFile, DebuggerVisualizerType};
19use rustc_middle::middle::exported_symbols::SymbolExportKind;
20use rustc_middle::middle::{exported_symbols, lang_items};
21use rustc_middle::mir::BinOp;
22use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};
23use rustc_middle::query::Providers;
24use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
25use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
26use rustc_session::Session;
27use rustc_session::config::{self, CrateType, EntryFnType, OptLevel, OutputType};
28use rustc_span::{DUMMY_SP, Symbol, sym};
29use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
30use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
31use tracing::{debug, info};
32use {rustc_ast as ast, rustc_attr_parsing as attr};
33
34use crate::assert_module_sources::CguReuse;
35use crate::back::link::are_upstream_rust_objects_already_included;
36use crate::back::metadata::create_compressed_metadata_file;
37use crate::back::write::{
38    ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
39    submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
40};
41use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
42use crate::meth::load_vtable;
43use crate::mir::operand::OperandValue;
44use crate::mir::place::PlaceRef;
45use crate::traits::*;
46use crate::{
47    CachedModuleCodegen, CodegenLintLevels, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
48    errors, meth, mir,
49};
50
51pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
52    match (op, signed) {
53        (BinOp::Eq, _) => IntPredicate::IntEQ,
54        (BinOp::Ne, _) => IntPredicate::IntNE,
55        (BinOp::Lt, true) => IntPredicate::IntSLT,
56        (BinOp::Lt, false) => IntPredicate::IntULT,
57        (BinOp::Le, true) => IntPredicate::IntSLE,
58        (BinOp::Le, false) => IntPredicate::IntULE,
59        (BinOp::Gt, true) => IntPredicate::IntSGT,
60        (BinOp::Gt, false) => IntPredicate::IntUGT,
61        (BinOp::Ge, true) => IntPredicate::IntSGE,
62        (BinOp::Ge, false) => IntPredicate::IntUGE,
63        op => bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
64    }
65}
66
67pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
68    match op {
69        BinOp::Eq => RealPredicate::RealOEQ,
70        BinOp::Ne => RealPredicate::RealUNE,
71        BinOp::Lt => RealPredicate::RealOLT,
72        BinOp::Le => RealPredicate::RealOLE,
73        BinOp::Gt => RealPredicate::RealOGT,
74        BinOp::Ge => RealPredicate::RealOGE,
75        op => bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
76    }
77}
78
79pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
80    bx: &mut Bx,
81    lhs: Bx::Value,
82    rhs: Bx::Value,
83    t: Ty<'tcx>,
84    ret_ty: Bx::Type,
85    op: BinOp,
86) -> Bx::Value {
87    let signed = match t.kind() {
88        ty::Float(_) => {
89            let cmp = bin_op_to_fcmp_predicate(op);
90            let cmp = bx.fcmp(cmp, lhs, rhs);
91            return bx.sext(cmp, ret_ty);
92        }
93        ty::Uint(_) => false,
94        ty::Int(_) => true,
95        _ => bug!("compare_simd_types: invalid SIMD type"),
96    };
97
98    let cmp = bin_op_to_icmp_predicate(op, signed);
99    let cmp = bx.icmp(cmp, lhs, rhs);
100    // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
101    // to get the correctly sized type. This will compile to a single instruction
102    // once the IR is converted to assembly if the SIMD instruction is supported
103    // by the target architecture.
104    bx.sext(cmp, ret_ty)
105}
106
107/// Codegen takes advantage of the additional assumption, where if the
108/// principal trait def id of what's being casted doesn't change,
109/// then we don't need to adjust the vtable at all. This
110/// corresponds to the fact that `dyn Tr<A>: Unsize<dyn Tr<B>>`
111/// requires that `A = B`; we don't allow *upcasting* objects
112/// between the same trait with different args. If we, for
113/// some reason, were to relax the `Unsize` trait, it could become
114/// unsound, so let's validate here that the trait refs are subtypes.
115pub fn validate_trivial_unsize<'tcx>(
116    tcx: TyCtxt<'tcx>,
117    source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
118    target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
119) -> bool {
120    match (source_data.principal(), target_data.principal()) {
121        (Some(hr_source_principal), Some(hr_target_principal)) => {
122            let (infcx, param_env) =
123                tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
124            let universe = infcx.universe();
125            let ocx = ObligationCtxt::new(&infcx);
126            infcx.enter_forall(hr_target_principal, |target_principal| {
127                let source_principal = infcx.instantiate_binder_with_fresh_vars(
128                    DUMMY_SP,
129                    BoundRegionConversionTime::HigherRankedType,
130                    hr_source_principal,
131                );
132                let Ok(()) = ocx.eq(
133                    &ObligationCause::dummy(),
134                    param_env,
135                    target_principal,
136                    source_principal,
137                ) else {
138                    return false;
139                };
140                if !ocx.select_all_or_error().is_empty() {
141                    return false;
142                }
143                infcx.leak_check(universe, None).is_ok()
144            })
145        }
146        (_, None) => true,
147        _ => false,
148    }
149}
150
151/// Retrieves the information we are losing (making dynamic) in an unsizing
152/// adjustment.
153///
154/// The `old_info` argument is a bit odd. It is intended for use in an upcast,
155/// where the new vtable for an object will be derived from the old one.
156fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
157    bx: &mut Bx,
158    source: Ty<'tcx>,
159    target: Ty<'tcx>,
160    old_info: Option<Bx::Value>,
161) -> Bx::Value {
162    let cx = bx.cx();
163    let (source, target) =
164        cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
165    match (source.kind(), target.kind()) {
166        (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
167            len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
168        ),
169        (&ty::Dynamic(data_a, _, src_dyn_kind), &ty::Dynamic(data_b, _, target_dyn_kind))
170            if src_dyn_kind == target_dyn_kind =>
171        {
172            let old_info =
173                old_info.expect("unsized_info: missing old info for trait upcasting coercion");
174            let b_principal_def_id = data_b.principal_def_id();
175            if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
176                // Codegen takes advantage of the additional assumption, where if the
177                // principal trait def id of what's being casted doesn't change,
178                // then we don't need to adjust the vtable at all. This
179                // corresponds to the fact that `dyn Tr<A>: Unsize<dyn Tr<B>>`
180                // requires that `A = B`; we don't allow *upcasting* objects
181                // between the same trait with different args. If we, for
182                // some reason, were to relax the `Unsize` trait, it could become
183                // unsound, so let's assert here that the trait refs are *equal*.
184                debug_assert!(
185                    validate_trivial_unsize(cx.tcx(), data_a, data_b),
186                    "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
187                );
188
189                // A NOP cast that doesn't actually change anything, let's avoid any
190                // unnecessary work. This relies on the assumption that if the principal
191                // traits are equal, then the associated type bounds (`dyn Trait<Assoc=T>`)
192                // are also equal, which is ensured by the fact that normalization is
193                // a function and we do not allow overlapping impls.
194                return old_info;
195            }
196
197            // trait upcasting coercion
198
199            let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
200
201            if let Some(entry_idx) = vptr_entry_idx {
202                let ptr_size = bx.data_layout().pointer_size;
203                let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
204                load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
205            } else {
206                old_info
207            }
208        }
209        (_, ty::Dynamic(data, _, _)) => meth::get_vtable(
210            cx,
211            source,
212            data.principal()
213                .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
214        ),
215        _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
216    }
217}
218
219/// Coerces `src` to `dst_ty`. `src_ty` must be a pointer.
220pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
221    bx: &mut Bx,
222    src: Bx::Value,
223    src_ty: Ty<'tcx>,
224    dst_ty: Ty<'tcx>,
225    old_info: Option<Bx::Value>,
226) -> (Bx::Value, Bx::Value) {
227    debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
228    match (src_ty.kind(), dst_ty.kind()) {
229        (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
230        | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
231            assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
232            (src, unsized_info(bx, a, b, old_info))
233        }
234        (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
235            assert_eq!(def_a, def_b); // implies same number of fields
236            let src_layout = bx.cx().layout_of(src_ty);
237            let dst_layout = bx.cx().layout_of(dst_ty);
238            if src_ty == dst_ty {
239                return (src, old_info.unwrap());
240            }
241            let mut result = None;
242            for i in 0..src_layout.fields.count() {
243                let src_f = src_layout.field(bx.cx(), i);
244                if src_f.is_1zst() {
245                    // We are looking for the one non-1-ZST field; this is not it.
246                    continue;
247                }
248
249                assert_eq!(src_layout.fields.offset(i).bytes(), 0);
250                assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
251                assert_eq!(src_layout.size, src_f.size);
252
253                let dst_f = dst_layout.field(bx.cx(), i);
254                assert_ne!(src_f.ty, dst_f.ty);
255                assert_eq!(result, None);
256                result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
257            }
258            result.unwrap()
259        }
260        _ => bug!("unsize_ptr: called on bad types"),
261    }
262}
263
264/// Coerces `src` to `dst_ty` which is guaranteed to be a `dyn*` type.
265pub(crate) fn cast_to_dyn_star<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
266    bx: &mut Bx,
267    src: Bx::Value,
268    src_ty_and_layout: TyAndLayout<'tcx>,
269    dst_ty: Ty<'tcx>,
270    old_info: Option<Bx::Value>,
271) -> (Bx::Value, Bx::Value) {
272    debug!("cast_to_dyn_star: {:?} => {:?}", src_ty_and_layout.ty, dst_ty);
273    assert!(
274        matches!(dst_ty.kind(), ty::Dynamic(_, _, ty::DynStar)),
275        "destination type must be a dyn*"
276    );
277    let src = match bx.cx().type_kind(bx.cx().backend_type(src_ty_and_layout)) {
278        TypeKind::Pointer => src,
279        TypeKind::Integer => bx.inttoptr(src, bx.type_ptr()),
280        // FIXME(dyn-star): We probably have to do a bitcast first, then inttoptr.
281        kind => bug!("unexpected TypeKind for left-hand side of `dyn*` cast: {kind:?}"),
282    };
283    (src, unsized_info(bx, src_ty_and_layout.ty, dst_ty, old_info))
284}
285
286/// Coerces `src`, which is a reference to a value of type `src_ty`,
287/// to a value of type `dst_ty`, and stores the result in `dst`.
288pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
289    bx: &mut Bx,
290    src: PlaceRef<'tcx, Bx::Value>,
291    dst: PlaceRef<'tcx, Bx::Value>,
292) {
293    let src_ty = src.layout.ty;
294    let dst_ty = dst.layout.ty;
295    match (src_ty.kind(), dst_ty.kind()) {
296        (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
297            let (base, info) = match bx.load_operand(src).val {
298                OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
299                OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
300                OperandValue::Ref(..) | OperandValue::ZeroSized => bug!(),
301            };
302            OperandValue::Pair(base, info).store(bx, dst);
303        }
304
305        (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
306            assert_eq!(def_a, def_b); // implies same number of fields
307
308            for i in def_a.variant(FIRST_VARIANT).fields.indices() {
309                let src_f = src.project_field(bx, i.as_usize());
310                let dst_f = dst.project_field(bx, i.as_usize());
311
312                if dst_f.layout.is_zst() {
313                    // No data here, nothing to copy/coerce.
314                    continue;
315                }
316
317                if src_f.layout.ty == dst_f.layout.ty {
318                    bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
319                } else {
320                    coerce_unsized_into(bx, src_f, dst_f);
321                }
322            }
323        }
324        _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
325    }
326}
327
328/// Returns `rhs` sufficiently masked, truncated, and/or extended so that it can be used to shift
329/// `lhs`: it has the same size as `lhs`, and the value, when interpreted unsigned (no matter its
330/// type), will not exceed the size of `lhs`.
331///
332/// Shifts in MIR are all allowed to have mismatched LHS & RHS types, and signed RHS.
333/// The shift methods in `BuilderMethods`, however, are fully homogeneous
334/// (both parameters and the return type are all the same size) and assume an unsigned RHS.
335///
336/// If `is_unchecked` is false, this masks the RHS to ensure it stays in-bounds,
337/// as the `BuilderMethods` shifts are UB for out-of-bounds shift amounts.
338/// For 32- and 64-bit types, this matches the semantics
339/// of Java. (See related discussion on #1877 and #10183.)
340///
341/// If `is_unchecked` is true, this does no masking, and adds sufficient `assume`
342/// calls or operation flags to preserve as much freedom to optimize as possible.
343pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
344    bx: &mut Bx,
345    lhs: Bx::Value,
346    mut rhs: Bx::Value,
347    is_unchecked: bool,
348) -> Bx::Value {
349    // Shifts may have any size int on the rhs
350    let mut rhs_llty = bx.cx().val_ty(rhs);
351    let mut lhs_llty = bx.cx().val_ty(lhs);
352
353    let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
354    if !is_unchecked {
355        rhs = bx.and(rhs, mask);
356    }
357
358    if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
359        rhs_llty = bx.cx().element_type(rhs_llty)
360    }
361    if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
362        lhs_llty = bx.cx().element_type(lhs_llty)
363    }
364    let rhs_sz = bx.cx().int_width(rhs_llty);
365    let lhs_sz = bx.cx().int_width(lhs_llty);
366    if lhs_sz < rhs_sz {
367        if is_unchecked && bx.sess().opts.optimize != OptLevel::No {
368            // FIXME: Use `trunc nuw` once that's available
369            let inrange = bx.icmp(IntPredicate::IntULE, rhs, mask);
370            bx.assume(inrange);
371        }
372
373        bx.trunc(rhs, lhs_llty)
374    } else if lhs_sz > rhs_sz {
375        // We zero-extend even if the RHS is signed. So e.g. `(x: i32) << -1i8` will zero-extend the
376        // RHS to `255i32`. But then we mask the shift amount to be within the size of the LHS
377        // anyway so the result is `31` as it should be. All the extra bits introduced by zext
378        // are masked off so their value does not matter.
379        // FIXME: if we ever support 512bit integers, this will be wrong! For such large integers,
380        // the extra bits introduced by zext are *not* all masked away any more.
381        assert!(lhs_sz <= 256);
382        bx.zext(rhs, lhs_llty)
383    } else {
384        rhs
385    }
386}
387
388// Returns `true` if this session's target will use native wasm
389// exceptions. This means that the VM does the unwinding for
390// us
391pub fn wants_wasm_eh(sess: &Session) -> bool {
392    sess.target.is_like_wasm
393        && (sess.target.os != "emscripten" || sess.opts.unstable_opts.emscripten_wasm_eh)
394}
395
396/// Returns `true` if this session's target will use SEH-based unwinding.
397///
398/// This is only true for MSVC targets, and even then the 64-bit MSVC target
399/// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
400/// 64-bit MinGW) instead of "full SEH".
401pub fn wants_msvc_seh(sess: &Session) -> bool {
402    sess.target.is_like_msvc
403}
404
405/// Returns `true` if this session's target requires the new exception
406/// handling LLVM IR instructions (catchpad / cleanuppad / ... instead
407/// of landingpad)
408pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
409    wants_wasm_eh(sess) || wants_msvc_seh(sess)
410}
411
412pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
413    cx: &'a Bx::CodegenCx,
414    instance: Instance<'tcx>,
415) {
416    // this is an info! to allow collecting monomorphization statistics
417    // and to allow finding the last function before LLVM aborts from
418    // release builds.
419    info!("codegen_instance({})", instance);
420
421    mir::codegen_mir::<Bx>(cx, instance);
422}
423
424/// Creates the `main` function which will initialize the rust runtime and call
425/// users main function.
426pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
427    cx: &'a Bx::CodegenCx,
428) -> Option<Bx::Function> {
429    let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
430    let main_is_local = main_def_id.is_local();
431    let instance = Instance::mono(cx.tcx(), main_def_id);
432
433    if main_is_local {
434        // We want to create the wrapper in the same codegen unit as Rust's main
435        // function.
436        if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
437            return None;
438        }
439    } else if !cx.codegen_unit().is_primary() {
440        // We want to create the wrapper only when the codegen unit is the primary one
441        return None;
442    }
443
444    let main_llfn = cx.get_fn_addr(instance);
445
446    let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
447    return Some(entry_fn);
448
449    fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
450        cx: &'a Bx::CodegenCx,
451        rust_main: Bx::Value,
452        rust_main_def_id: DefId,
453        entry_type: EntryFnType,
454    ) -> Bx::Function {
455        // The entry function is either `int main(void)` or `int main(int argc, char **argv)`, or
456        // `usize efi_main(void *handle, void *system_table)` depending on the target.
457        let llfty = if cx.sess().target.os.contains("uefi") {
458            cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
459        } else if cx.sess().target.main_needs_argc_argv {
460            cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
461        } else {
462            cx.type_func(&[], cx.type_int())
463        };
464
465        let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
466        // Given that `main()` has no arguments,
467        // then its return type cannot have
468        // late-bound regions, since late-bound
469        // regions must appear in the argument
470        // listing.
471        let main_ret_ty = cx
472            .tcx()
473            .normalize_erasing_regions(cx.typing_env(), main_ret_ty.no_bound_vars().unwrap());
474
475        let Some(llfn) = cx.declare_c_main(llfty) else {
476            // FIXME: We should be smart and show a better diagnostic here.
477            let span = cx.tcx().def_span(rust_main_def_id);
478            cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
479        };
480
481        // `main` should respect same config for frame pointer elimination as rest of code
482        cx.set_frame_pointer_type(llfn);
483        cx.apply_target_cpu_attr(llfn);
484
485        let llbb = Bx::append_block(cx, llfn, "top");
486        let mut bx = Bx::build(cx, llbb);
487
488        bx.insert_reference_to_gdb_debug_scripts_section_global();
489
490        let isize_ty = cx.type_isize();
491        let ptr_ty = cx.type_ptr();
492        let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
493
494        let EntryFnType::Main { sigpipe } = entry_type;
495        let (start_fn, start_ty, args, instance) = {
496            let start_def_id = cx.tcx().require_lang_item(LangItem::Start, None);
497            let start_instance = ty::Instance::expect_resolve(
498                cx.tcx(),
499                cx.typing_env(),
500                start_def_id,
501                cx.tcx().mk_args(&[main_ret_ty.into()]),
502                DUMMY_SP,
503            );
504            let start_fn = cx.get_fn_addr(start_instance);
505
506            let i8_ty = cx.type_i8();
507            let arg_sigpipe = bx.const_u8(sigpipe);
508
509            let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
510            (
511                start_fn,
512                start_ty,
513                vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
514                Some(start_instance),
515            )
516        };
517
518        let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
519        if cx.sess().target.os.contains("uefi") {
520            bx.ret(result);
521        } else {
522            let cast = bx.intcast(result, cx.type_int(), true);
523            bx.ret(cast);
524        }
525
526        llfn
527    }
528}
529
530/// Obtain the `argc` and `argv` values to pass to the rust start function
531/// (i.e., the "start" lang item).
532fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
533    if bx.cx().sess().target.os.contains("uefi") {
534        // Params for UEFI
535        let param_handle = bx.get_param(0);
536        let param_system_table = bx.get_param(1);
537        let ptr_size = bx.tcx().data_layout.pointer_size;
538        let ptr_align = bx.tcx().data_layout.pointer_align.abi;
539        let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
540        let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
541        bx.store(param_handle, arg_argv, ptr_align);
542        let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
543        bx.store(param_system_table, arg_argv_el1, ptr_align);
544        (arg_argc, arg_argv)
545    } else if bx.cx().sess().target.main_needs_argc_argv {
546        // Params from native `main()` used as args for rust start function
547        let param_argc = bx.get_param(0);
548        let param_argv = bx.get_param(1);
549        let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
550        let arg_argv = param_argv;
551        (arg_argc, arg_argv)
552    } else {
553        // The Rust start function doesn't need `argc` and `argv`, so just pass zeros.
554        let arg_argc = bx.const_int(bx.cx().type_int(), 0);
555        let arg_argv = bx.const_null(bx.cx().type_ptr());
556        (arg_argc, arg_argv)
557    }
558}
559
560/// This function returns all of the debugger visualizers specified for the
561/// current crate as well as all upstream crates transitively that match the
562/// `visualizer_type` specified.
563pub fn collect_debugger_visualizers_transitive(
564    tcx: TyCtxt<'_>,
565    visualizer_type: DebuggerVisualizerType,
566) -> BTreeSet<DebuggerVisualizerFile> {
567    tcx.debugger_visualizers(LOCAL_CRATE)
568        .iter()
569        .chain(
570            tcx.crates(())
571                .iter()
572                .filter(|&cnum| {
573                    let used_crate_source = tcx.used_crate_source(*cnum);
574                    used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
575                })
576                .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
577        )
578        .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
579        .cloned()
580        .collect::<BTreeSet<_>>()
581}
582
583/// Decide allocator kind to codegen. If `Some(_)` this will be the same as
584/// `tcx.allocator_kind`, but it may be `None` in more cases (e.g. if using
585/// allocator definitions from a dylib dependency).
586pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
587    // If the crate doesn't have an `allocator_kind` set then there's definitely
588    // no shim to generate. Otherwise we also check our dependency graph for all
589    // our output crate types. If anything there looks like its a `Dynamic`
590    // linkage, then it's already got an allocator shim and we'll be using that
591    // one instead. If nothing exists then it's our job to generate the
592    // allocator!
593    let any_dynamic_crate = tcx.dependency_formats(()).iter().any(|(_, list)| {
594        use rustc_middle::middle::dependency_format::Linkage;
595        list.iter().any(|&linkage| linkage == Linkage::Dynamic)
596    });
597    if any_dynamic_crate { None } else { tcx.allocator_kind(()) }
598}
599
600pub fn codegen_crate<B: ExtraBackendMethods>(
601    backend: B,
602    tcx: TyCtxt<'_>,
603    target_cpu: String,
604    metadata: EncodedMetadata,
605    need_metadata_module: bool,
606) -> OngoingCodegen<B> {
607    // Skip crate items and just output metadata in -Z no-codegen mode.
608    if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
609        let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, metadata, None);
610
611        ongoing_codegen.codegen_finished(tcx);
612
613        ongoing_codegen.check_for_errors(tcx.sess);
614
615        return ongoing_codegen;
616    }
617
618    if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
619        // The target has no default cpu, but none is set explicitly
620        tcx.dcx().emit_fatal(errors::CpuRequired);
621    }
622
623    let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
624
625    // Run the monomorphization collector and partition the collected items into
626    // codegen units.
627    let MonoItemPartitions { codegen_units, autodiff_items, .. } =
628        tcx.collect_and_partition_mono_items(());
629    let autodiff_fncs = autodiff_items.to_vec();
630
631    // Force all codegen_unit queries so they are already either red or green
632    // when compile_codegen_unit accesses them. We are not able to re-execute
633    // the codegen_unit query from just the DepNode, so an unknown color would
634    // lead to having to re-execute compile_codegen_unit, possibly
635    // unnecessarily.
636    if tcx.dep_graph.is_fully_enabled() {
637        for cgu in codegen_units {
638            tcx.ensure_ok().codegen_unit(cgu.name());
639        }
640    }
641
642    let metadata_module = need_metadata_module.then(|| {
643        // Emit compressed metadata object.
644        let metadata_cgu_name =
645            cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
646        tcx.sess.time("write_compressed_metadata", || {
647            let file_name =
648                tcx.output_filenames(()).temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
649            let data = create_compressed_metadata_file(
650                tcx.sess,
651                &metadata,
652                &exported_symbols::metadata_symbol_name(tcx),
653            );
654            if let Err(error) = std::fs::write(&file_name, data) {
655                tcx.dcx().emit_fatal(errors::MetadataObjectFileWrite { error });
656            }
657            CompiledModule {
658                name: metadata_cgu_name,
659                kind: ModuleKind::Metadata,
660                object: Some(file_name),
661                dwarf_object: None,
662                bytecode: None,
663                assembly: None,
664                llvm_ir: None,
665            }
666        })
667    });
668
669    let ongoing_codegen =
670        start_async_codegen(backend.clone(), tcx, target_cpu, metadata, metadata_module);
671
672    // Codegen an allocator shim, if necessary.
673    if let Some(kind) = allocator_kind_for_codegen(tcx) {
674        let llmod_id =
675            cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
676        let module_llvm = tcx.sess.time("write_allocator_module", || {
677            backend.codegen_allocator(
678                tcx,
679                &llmod_id,
680                kind,
681                // If allocator_kind is Some then alloc_error_handler_kind must
682                // also be Some.
683                tcx.alloc_error_handler_kind(()).unwrap(),
684            )
685        });
686
687        ongoing_codegen.wait_for_signal_to_codegen_item();
688        ongoing_codegen.check_for_errors(tcx.sess);
689
690        // These modules are generally cheap and won't throw off scheduling.
691        let cost = 0;
692        submit_codegened_module_to_llvm(
693            &backend,
694            &ongoing_codegen.coordinator.sender,
695            ModuleCodegen { name: llmod_id, module_llvm, kind: ModuleKind::Allocator },
696            cost,
697        );
698    }
699
700    if !autodiff_fncs.is_empty() {
701        ongoing_codegen.submit_autodiff_items(autodiff_fncs);
702    }
703
704    // For better throughput during parallel processing by LLVM, we used to sort
705    // CGUs largest to smallest. This would lead to better thread utilization
706    // by, for example, preventing a large CGU from being processed last and
707    // having only one LLVM thread working while the rest remained idle.
708    //
709    // However, this strategy would lead to high memory usage, as it meant the
710    // LLVM-IR for all of the largest CGUs would be resident in memory at once.
711    //
712    // Instead, we can compromise by ordering CGUs such that the largest and
713    // smallest are first, second largest and smallest are next, etc. If there
714    // are large size variations, this can reduce memory usage significantly.
715    let codegen_units: Vec<_> = {
716        let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
717        sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
718
719        let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
720        first_half.iter().interleave(second_half.iter().rev()).copied().collect()
721    };
722
723    // Calculate the CGU reuse
724    let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
725        codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
726    });
727
728    crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
729        for (i, cgu) in codegen_units.iter().enumerate() {
730            let cgu_reuse = cgu_reuse[i];
731            cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
732        }
733    });
734
735    let mut total_codegen_time = Duration::new(0, 0);
736    let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
737
738    // The non-parallel compiler can only translate codegen units to LLVM IR
739    // on a single thread, leading to a staircase effect where the N LLVM
740    // threads have to wait on the single codegen threads to generate work
741    // for them. The parallel compiler does not have this restriction, so
742    // we can pre-load the LLVM queue in parallel before handing off
743    // coordination to the OnGoingCodegen scheduler.
744    //
745    // This likely is a temporary measure. Once we don't have to support the
746    // non-parallel compiler anymore, we can compile CGUs end-to-end in
747    // parallel and get rid of the complicated scheduling logic.
748    let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
749        tcx.sess.time("compile_first_CGU_batch", || {
750            // Try to find one CGU to compile per thread.
751            let cgus: Vec<_> = cgu_reuse
752                .iter()
753                .enumerate()
754                .filter(|&(_, reuse)| reuse == &CguReuse::No)
755                .take(tcx.sess.threads())
756                .collect();
757
758            // Compile the found CGUs in parallel.
759            let start_time = Instant::now();
760
761            let pre_compiled_cgus = par_map(cgus, |(i, _)| {
762                let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
763                (i, module)
764            });
765
766            total_codegen_time += start_time.elapsed();
767
768            pre_compiled_cgus
769        })
770    } else {
771        FxHashMap::default()
772    };
773
774    for (i, cgu) in codegen_units.iter().enumerate() {
775        ongoing_codegen.wait_for_signal_to_codegen_item();
776        ongoing_codegen.check_for_errors(tcx.sess);
777
778        let cgu_reuse = cgu_reuse[i];
779
780        match cgu_reuse {
781            CguReuse::No => {
782                let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
783                    cgu
784                } else {
785                    let start_time = Instant::now();
786                    let module = backend.compile_codegen_unit(tcx, cgu.name());
787                    total_codegen_time += start_time.elapsed();
788                    module
789                };
790                // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`
791                // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes
792                // compilation hang on post-monomorphization errors.
793                tcx.dcx().abort_if_errors();
794
795                submit_codegened_module_to_llvm(
796                    &backend,
797                    &ongoing_codegen.coordinator.sender,
798                    module,
799                    cost,
800                );
801            }
802            CguReuse::PreLto => {
803                submit_pre_lto_module_to_llvm(
804                    &backend,
805                    tcx,
806                    &ongoing_codegen.coordinator.sender,
807                    CachedModuleCodegen {
808                        name: cgu.name().to_string(),
809                        source: cgu.previous_work_product(tcx),
810                    },
811                );
812            }
813            CguReuse::PostLto => {
814                submit_post_lto_module_to_llvm(
815                    &backend,
816                    &ongoing_codegen.coordinator.sender,
817                    CachedModuleCodegen {
818                        name: cgu.name().to_string(),
819                        source: cgu.previous_work_product(tcx),
820                    },
821                );
822            }
823        }
824    }
825
826    ongoing_codegen.codegen_finished(tcx);
827
828    // Since the main thread is sometimes blocked during codegen, we keep track
829    // -Ztime-passes output manually.
830    if tcx.sess.opts.unstable_opts.time_passes {
831        let end_rss = get_resident_set_size();
832
833        print_time_passes_entry(
834            "codegen_to_LLVM_IR",
835            total_codegen_time,
836            start_rss.unwrap(),
837            end_rss,
838            tcx.sess.opts.unstable_opts.time_passes_format,
839        );
840    }
841
842    ongoing_codegen.check_for_errors(tcx.sess);
843    ongoing_codegen
844}
845
846/// Returns whether a call from the current crate to the [`Instance`] would produce a call
847/// from `compiler_builtins` to a symbol the linker must resolve.
848///
849/// Such calls from `compiler_bultins` are effectively impossible for the linker to handle. Some
850/// linkers will optimize such that dead calls to unresolved symbols are not an error, but this is
851/// not guaranteed. So we used this function in codegen backends to ensure we do not generate any
852/// unlinkable calls.
853///
854/// Note that calls to LLVM intrinsics are uniquely okay because they won't make it to the linker.
855pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
856    tcx: TyCtxt<'tcx>,
857    instance: Instance<'tcx>,
858) -> bool {
859    fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
860        if let Some(name) = tcx.codegen_fn_attrs(def_id).link_name {
861            name.as_str().starts_with("llvm.")
862        } else {
863            false
864        }
865    }
866
867    let def_id = instance.def_id();
868    !def_id.is_local()
869        && tcx.is_compiler_builtins(LOCAL_CRATE)
870        && !is_llvm_intrinsic(tcx, def_id)
871        && !tcx.should_codegen_locally(instance)
872}
873
874impl CrateInfo {
875    pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
876        let crate_types = tcx.crate_types().to_vec();
877        let exported_symbols = crate_types
878            .iter()
879            .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
880            .collect();
881        let linked_symbols =
882            crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
883        let local_crate_name = tcx.crate_name(LOCAL_CRATE);
884        let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
885        let subsystem =
886            ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
887        let windows_subsystem = subsystem.map(|subsystem| {
888            if subsystem != sym::windows && subsystem != sym::console {
889                tcx.dcx().emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
890            }
891            subsystem.to_string()
892        });
893
894        // This list is used when generating the command line to pass through to
895        // system linker. The linker expects undefined symbols on the left of the
896        // command line to be defined in libraries on the right, not the other way
897        // around. For more info, see some comments in the add_used_library function
898        // below.
899        //
900        // In order to get this left-to-right dependency ordering, we use the reverse
901        // postorder of all crates putting the leaves at the rightmost positions.
902        let mut compiler_builtins = None;
903        let mut used_crates: Vec<_> = tcx
904            .postorder_cnums(())
905            .iter()
906            .rev()
907            .copied()
908            .filter(|&cnum| {
909                let link = !tcx.dep_kind(cnum).macros_only();
910                if link && tcx.is_compiler_builtins(cnum) {
911                    compiler_builtins = Some(cnum);
912                    return false;
913                }
914                link
915            })
916            .collect();
917        // `compiler_builtins` are always placed last to ensure that they're linked correctly.
918        used_crates.extend(compiler_builtins);
919
920        let crates = tcx.crates(());
921        let n_crates = crates.len();
922        let mut info = CrateInfo {
923            target_cpu,
924            crate_types,
925            exported_symbols,
926            linked_symbols,
927            local_crate_name,
928            compiler_builtins,
929            profiler_runtime: None,
930            is_no_builtins: Default::default(),
931            native_libraries: Default::default(),
932            used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
933            crate_name: UnordMap::with_capacity(n_crates),
934            used_crates,
935            used_crate_source: UnordMap::with_capacity(n_crates),
936            dependency_formats: Arc::clone(tcx.dependency_formats(())),
937            windows_subsystem,
938            natvis_debugger_visualizers: Default::default(),
939            lint_levels: CodegenLintLevels::from_tcx(tcx),
940        };
941
942        info.native_libraries.reserve(n_crates);
943
944        for &cnum in crates.iter() {
945            info.native_libraries
946                .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
947            info.crate_name.insert(cnum, tcx.crate_name(cnum));
948
949            let used_crate_source = tcx.used_crate_source(cnum);
950            info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
951            if tcx.is_profiler_runtime(cnum) {
952                info.profiler_runtime = Some(cnum);
953            }
954            if tcx.is_no_builtins(cnum) {
955                info.is_no_builtins.insert(cnum);
956            }
957        }
958
959        // Handle circular dependencies in the standard library.
960        // See comment before `add_linked_symbol_object` function for the details.
961        // If global LTO is enabled then almost everything (*) is glued into a single object file,
962        // so this logic is not necessary and can cause issues on some targets (due to weak lang
963        // item symbols being "privatized" to that object file), so we disable it.
964        // (*) Native libs, and `#[compiler_builtins]` and `#[no_builtins]` crates are not glued,
965        // and we assume that they cannot define weak lang items. This is not currently enforced
966        // by the compiler, but that's ok because all this stuff is unstable anyway.
967        let target = &tcx.sess.target;
968        if !are_upstream_rust_objects_already_included(tcx.sess) {
969            let missing_weak_lang_items: FxIndexSet<Symbol> = info
970                .used_crates
971                .iter()
972                .flat_map(|&cnum| tcx.missing_lang_items(cnum))
973                .filter(|l| l.is_weak())
974                .filter_map(|&l| {
975                    let name = l.link_name()?;
976                    lang_items::required(tcx, l).then_some(name)
977                })
978                .collect();
979            let prefix = match (target.is_like_windows, target.arch.as_ref()) {
980                (true, "x86") => "_",
981                (true, "arm64ec") => "#",
982                _ => "",
983            };
984
985            // This loop only adds new items to values of the hash map, so the order in which we
986            // iterate over the values is not important.
987            #[allow(rustc::potential_query_instability)]
988            info.linked_symbols
989                .iter_mut()
990                .filter(|(crate_type, _)| {
991                    !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
992                })
993                .for_each(|(_, linked_symbols)| {
994                    let mut symbols = missing_weak_lang_items
995                        .iter()
996                        .map(|item| (format!("{prefix}{item}"), SymbolExportKind::Text))
997                        .collect::<Vec<_>>();
998                    symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
999                    linked_symbols.extend(symbols);
1000                    if tcx.allocator_kind(()).is_some() {
1001                        // At least one crate needs a global allocator. This crate may be placed
1002                        // after the crate that defines it in the linker order, in which case some
1003                        // linkers return an error. By adding the global allocator shim methods to
1004                        // the linked_symbols list, linking the generated symbols.o will ensure that
1005                        // circular dependencies involving the global allocator don't lead to linker
1006                        // errors.
1007                        linked_symbols.extend(ALLOCATOR_METHODS.iter().map(|method| {
1008                            (
1009                                format!("{prefix}{}", global_fn_name(method.name).as_str()),
1010                                SymbolExportKind::Text,
1011                            )
1012                        }));
1013                    }
1014                });
1015        }
1016
1017        let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1018            CrateType::Executable | CrateType::Dylib | CrateType::Cdylib => {
1019                // These are crate types for which we invoke the linker and can embed
1020                // NatVis visualizers.
1021                true
1022            }
1023            CrateType::ProcMacro => {
1024                // We could embed NatVis for proc macro crates too (to improve the debugging
1025                // experience for them) but it does not seem like a good default, since
1026                // this is a rare use case and we don't want to slow down the common case.
1027                false
1028            }
1029            CrateType::Staticlib | CrateType::Rlib => {
1030                // We don't invoke the linker for these, so we don't need to collect the NatVis for
1031                // them.
1032                false
1033            }
1034        });
1035
1036        if target.is_like_msvc && embed_visualizers {
1037            info.natvis_debugger_visualizers =
1038                collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1039        }
1040
1041        info
1042    }
1043}
1044
1045pub(crate) fn provide(providers: &mut Providers) {
1046    providers.backend_optimization_level = |tcx, cratenum| {
1047        let for_speed = match tcx.sess.opts.optimize {
1048            // If globally no optimisation is done, #[optimize] has no effect.
1049            //
1050            // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the
1051            // pass manager and it is likely that some module-wide passes (such as inliner or
1052            // cross-function constant propagation) would ignore the `optnone` annotation we put
1053            // on the functions, thus necessarily involving these functions into optimisations.
1054            config::OptLevel::No => return config::OptLevel::No,
1055            // If globally optimise-speed is already specified, just use that level.
1056            config::OptLevel::Less => return config::OptLevel::Less,
1057            config::OptLevel::More => return config::OptLevel::More,
1058            config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1059            // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)
1060            // are present).
1061            config::OptLevel::Size => config::OptLevel::More,
1062            config::OptLevel::SizeMin => config::OptLevel::More,
1063        };
1064
1065        let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1066
1067        let any_for_speed = defids.items().any(|id| {
1068            let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1069            matches!(optimize, attr::OptimizeAttr::Speed)
1070        });
1071
1072        if any_for_speed {
1073            return for_speed;
1074        }
1075
1076        tcx.sess.opts.optimize
1077    };
1078}
1079
1080pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1081    if !tcx.dep_graph.is_fully_enabled() {
1082        return CguReuse::No;
1083    }
1084
1085    let work_product_id = &cgu.work_product_id();
1086    if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1087        // We don't have anything cached for this CGU. This can happen
1088        // if the CGU did not exist in the previous session.
1089        return CguReuse::No;
1090    }
1091
1092    // Try to mark the CGU as green. If it we can do so, it means that nothing
1093    // affecting the LLVM module has changed and we can re-use a cached version.
1094    // If we compile with any kind of LTO, this means we can re-use the bitcode
1095    // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
1096    // know that later). If we are not doing LTO, there is only one optimized
1097    // version of each module, so we re-use that.
1098    let dep_node = cgu.codegen_dep_node(tcx);
1099    assert!(
1100        !tcx.dep_graph.dep_node_exists(&dep_node),
1101        "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1102        cgu.name()
1103    );
1104
1105    if tcx.try_mark_green(&dep_node) {
1106        // We can re-use either the pre- or the post-thinlto state. If no LTO is
1107        // being performed then we can use post-LTO artifacts, otherwise we must
1108        // reuse pre-LTO artifacts
1109        match compute_per_cgu_lto_type(
1110            &tcx.sess.lto(),
1111            &tcx.sess.opts,
1112            tcx.crate_types(),
1113            ModuleKind::Regular,
1114        ) {
1115            ComputedLtoType::No => CguReuse::PostLto,
1116            _ => CguReuse::PreLto,
1117        }
1118    } else {
1119        CguReuse::No
1120    }
1121}