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