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