1use std::collections::BTreeSet;2use std::sync::Arc;3use std::time::{Duration, Instant};4use std::{cmp, iter};56use itertools::Itertools;7use rustc_abi::FIRST_VARIANT;8use rustc_ast::expand::allocator::{9 ALLOC_ERROR_HANDLER, ALLOCATOR_METHODS, AllocatorKind, AllocatorMethod, AllocatorMethodInput,10 AllocatorTy,11};12use rustc_attr_ir::lang_items::LangItem;13use rustc_attr_ir::target::Target;14use rustc_attr_ir::{DebuggerVisualizerType, EiiDecl, EiiImpl, OptimizeAttr, find_attr};15use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};16use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};17use rustc_data_structures::sync::{IntoDynSyncSend, par_map};18use rustc_data_structures::unord::UnordMap;19use rustc_hir as hir;20use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};21use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;22use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;23use rustc_middle::middle::dependency_format::{Dependencies, Linkage};24use rustc_middle::middle::exported_symbols::{self, SymbolExportKind};25use rustc_middle::middle::lang_items;26use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, ErrorHandled, Scalar};27use rustc_middle::mir::{BinOp, ConstValue};28use rustc_middle::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};29use rustc_middle::query::Providers;30use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};31use rustc_middle::ty::{self, Instance, PatternKind, Ty, TyCtxt, UintTy, Unnormalized};32use rustc_session::config::{self, EntryFnType};33use rustc_span::{DUMMY_SP, Symbol, bug, span_bug};34use rustc_structures::CrateType;35use rustc_symbol_mangling::mangle_internal_symbol;36use rustc_target::spec::{Arch, Os, Target as TargetSpec};37use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};38use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};39use tracing::{debug, info};4041use crate::assert_module_sources::CguReuse;42use crate::back::link::are_upstream_rust_objects_already_included;43use crate::back::write::{44 ComputedLtoType, ModuleConfig, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,45 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,46};47use crate::common::{self, IntPredicate, RealPredicate, TypeKind};48use crate::meth::load_vtable;49use crate::mir::operand::OperandValue;50use crate::mir::place::PlaceRef;51use crate::traits::*;52use crate::{53 CachedModuleCodegen, CodegenLintLevelSpecs, CrateInfo, EiiLinkageImplInfo, EiiLinkageInfo,54 ModuleCodegen, ModuleKind, diagnostics, meth, mir,55};5657pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {58 match (op, signed) {59 (BinOp::Eq, _) => IntPredicate::IntEQ,60 (BinOp::Ne, _) => IntPredicate::IntNE,61 (BinOp::Lt, true) => IntPredicate::IntSLT,62 (BinOp::Lt, false) => IntPredicate::IntULT,63 (BinOp::Le, true) => IntPredicate::IntSLE,64 (BinOp::Le, false) => IntPredicate::IntULE,65 (BinOp::Gt, true) => IntPredicate::IntSGT,66 (BinOp::Gt, false) => IntPredicate::IntUGT,67 (BinOp::Ge, true) => IntPredicate::IntSGE,68 (BinOp::Ge, false) => IntPredicate::IntUGE,69 op => bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),70 }71}7273pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {74 match op {75 BinOp::Eq => RealPredicate::RealOEQ,76 BinOp::Ne => RealPredicate::RealUNE,77 BinOp::Lt => RealPredicate::RealOLT,78 BinOp::Le => RealPredicate::RealOLE,79 BinOp::Gt => RealPredicate::RealOGT,80 BinOp::Ge => RealPredicate::RealOGE,81 op => bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),82 }83}8485pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(86 bx: &mut Bx,87 lhs: Bx::Value,88 rhs: Bx::Value,89 t: Ty<'tcx>,90 ret_ty: Bx::Type,91 op: BinOp,92) -> Bx::Value {93 let signed = match t.kind() {94 ty::Float(_) => {95 let cmp = bin_op_to_fcmp_predicate(op);96 let cmp = bx.fcmp(cmp, lhs, rhs);97 return bx.sext(cmp, ret_ty);98 }99 ty::Uint(_) => false,100 ty::Int(_) => true,101 _ => bug!("compare_simd_types: invalid SIMD type"),102 };103104 let cmp = bin_op_to_icmp_predicate(op, signed);105 let cmp = bx.icmp(cmp, lhs, rhs);106 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension107 // to get the correctly sized type. This will compile to a single instruction108 // once the IR is converted to assembly if the SIMD instruction is supported109 // by the target architecture.110 bx.sext(cmp, ret_ty)111}112113/// Codegen takes advantage of the additional assumption, where if the114/// principal trait def id of what's being casted doesn't change,115/// then we don't need to adjust the vtable at all. This116/// corresponds to the fact that `dyn Tr<A>: Unsize<dyn Tr<B>>`117/// requires that `A = B`; we don't allow *upcasting* objects118/// between the same trait with different args. If we, for119/// some reason, were to relax the `Unsize` trait, it could become120/// unsound, so let's validate here that the trait refs are subtypes.121pub fn validate_trivial_unsize<'tcx>(122 tcx: TyCtxt<'tcx>,123 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,124 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,125) -> bool {126 match (source_data.principal(), target_data.principal()) {127 (Some(hr_source_principal), Some(hr_target_principal)) => {128 let (infcx, param_env) =129 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());130 let universe = infcx.universe();131 let ocx = ObligationCtxt::new(&infcx);132 infcx.enter_forall(hr_target_principal, |target_principal| {133 let source_principal = infcx.instantiate_binder_with_fresh_vars(134 DUMMY_SP,135 BoundRegionConversionTime::HigherRankedType,136 hr_source_principal,137 );138 let Ok(()) = ocx.eq(139 &ObligationCause::dummy(),140 param_env,141 target_principal,142 source_principal,143 ) else {144 return false;145 };146 if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {147 return false;148 }149 infcx.leak_check(universe, None).is_ok()150 })151 }152 (_, None) => true,153 _ => false,154 }155}156157/// Retrieves the information we are losing (making dynamic) in an unsizing158/// adjustment.159///160/// The `old_info` argument is a bit odd. It is intended for use in an upcast,161/// where the new vtable for an object will be derived from the old one.162fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(163 bx: &mut Bx,164 source: Ty<'tcx>,165 target: Ty<'tcx>,166 old_info: Option<Bx::Value>,167) -> Bx::Value {168 let cx = bx.cx();169 let (source, target) =170 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());171 match (source.kind(), target.kind()) {172 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(173 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),174 ),175 (&ty::Dynamic(data_a, _), &ty::Dynamic(data_b, _)) => {176 let old_info =177 old_info.expect("unsized_info: missing old info for trait upcasting coercion");178 let b_principal_def_id = data_b.principal_def_id();179 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {180 // Codegen takes advantage of the additional assumption, where if the181 // principal trait def id of what's being casted doesn't change,182 // then we don't need to adjust the vtable at all. This183 // corresponds to the fact that `dyn Tr<A>: Unsize<dyn Tr<B>>`184 // requires that `A = B`; we don't allow *upcasting* objects185 // between the same trait with different args. If we, for186 // some reason, were to relax the `Unsize` trait, it could become187 // unsound, so let's assert here that the trait refs are *equal*.188 debug_assert!(189 validate_trivial_unsize(cx.tcx(), data_a, data_b),190 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"191 );192193 // A NOP cast that doesn't actually change anything, let's avoid any194 // unnecessary work. This relies on the assumption that if the principal195 // traits are equal, then the associated type bounds (`dyn Trait<Assoc=T>`)196 // are also equal, which is ensured by the fact that normalization is197 // a function and we do not allow overlapping impls.198 return old_info;199 }200201 // trait upcasting coercion202203 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));204205 if let Some(entry_idx) = vptr_entry_idx {206 let ptr_size = bx.data_layout().pointer_size();207 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();208 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)209 } else {210 old_info211 }212 }213 (_, ty::Dynamic(data, _)) => meth::get_vtable(214 cx,215 source,216 data.principal()217 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),218 ),219 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),220 }221}222223/// Coerces `src` to `dst_ty`. `src_ty` must be a pointer.224pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(225 bx: &mut Bx,226 src: Bx::Value,227 src_ty: Ty<'tcx>,228 dst_ty: Ty<'tcx>,229 old_info: Option<Bx::Value>,230) -> (Bx::Value, Bx::Value) {231 debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);232 match (src_ty.kind(), dst_ty.kind()) {233 (&ty::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),234 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))235 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {236 assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());237 (src, unsized_info(bx, a, b, old_info))238 }239 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {240 assert_eq!(def_a, def_b); // implies same number of fields241 let src_layout = bx.cx().layout_of(src_ty);242 let dst_layout = bx.cx().layout_of(dst_ty);243 if src_ty == dst_ty {244 return (src, old_info.unwrap());245 }246 let mut result = None;247 for i in 0..src_layout.fields.count() {248 let src_f = src_layout.field(bx.cx(), i);249 if src_f.is_1zst() {250 // We are looking for the one non-1-ZST field; this is not it.251 continue;252 }253254 assert_eq!(src_layout.fields.offset(i).bytes(), 0);255 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);256 assert_eq!(src_layout.size, src_f.size);257258 let dst_f = dst_layout.field(bx.cx(), i);259 assert_ne!(src_f.ty, dst_f.ty);260 assert_eq!(result, None);261 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));262 }263 result.unwrap()264 }265 _ => bug!("unsize_ptr: called on bad types"),266 }267}268269/// Coerces `src`, which is a reference to a value of type `src_ty`,270/// to a value of type `dst_ty`, and stores the result in `dst`.271pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(272 bx: &mut Bx,273 src: PlaceRef<'tcx, Bx::Value>,274 dst: PlaceRef<'tcx, Bx::Value>,275) {276 let src_ty = src.layout.ty;277 let dst_ty = dst.layout.ty;278 match (src_ty.kind(), dst_ty.kind()) {279 (&ty::Pat(s, sp), &ty::Pat(d, dp))280 if let (PatternKind::NotNull, PatternKind::NotNull) = (*sp, *dp) =>281 {282 let src = src.project_type(bx, s);283 let dst = dst.project_type(bx, d);284 coerce_unsized_into(bx, src, dst)285 }286 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {287 let (base, info) = match bx.load_operand(src).val {288 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),289 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),290 OperandValue::Ref(..) | OperandValue::ZeroSized => bug!(),291 };292 OperandValue::Pair(base, info).store(bx, dst);293 }294295 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {296 assert_eq!(def_a, def_b); // implies same number of fields297298 for i in def_a.variant(FIRST_VARIANT).fields.indices() {299 let src_f = src.project_field(bx, i.as_usize());300 let dst_f = dst.project_field(bx, i.as_usize());301302 if dst_f.layout.is_zst() {303 // No data here, nothing to copy/coerce.304 continue;305 }306307 if src_f.layout.ty == dst_f.layout.ty {308 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);309 } else {310 coerce_unsized_into(bx, src_f, dst_f);311 }312 }313 }314 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),315 }316}317318/// Returns `rhs` sufficiently masked, truncated, and/or extended so that it can be used to shift319/// `lhs`: it has the same size as `lhs`, and the value, when interpreted unsigned (no matter its320/// type), will not exceed the size of `lhs`.321///322/// Shifts in MIR are all allowed to have mismatched LHS & RHS types, and signed RHS.323/// The shift methods in `BuilderMethods`, however, are fully homogeneous324/// (both parameters and the return type are all the same size) and assume an unsigned RHS.325///326/// If `is_unchecked` is false, this masks the RHS to ensure it stays in-bounds,327/// as the `BuilderMethods` shifts are UB for out-of-bounds shift amounts.328/// For 32- and 64-bit types, this matches the semantics329/// of Java. (See related discussion on #1877 and #10183.)330///331/// If `is_unchecked` is true, this does no masking, and adds sufficient `assume`332/// calls or operation flags to preserve as much freedom to optimize as possible.333pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(334 bx: &mut Bx,335 lhs: Bx::Value,336 mut rhs: Bx::Value,337 is_unchecked: bool,338) -> Bx::Value {339 // Shifts may have any size int on the rhs340 let mut rhs_llty = bx.cx().val_ty(rhs);341 let mut lhs_llty = bx.cx().val_ty(lhs);342343 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);344 if !is_unchecked {345 rhs = bx.and(rhs, mask);346 }347348 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {349 rhs_llty = bx.cx().element_type(rhs_llty)350 }351 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {352 lhs_llty = bx.cx().element_type(lhs_llty)353 }354 let rhs_sz = bx.cx().int_width(rhs_llty);355 let lhs_sz = bx.cx().int_width(lhs_llty);356 if lhs_sz < rhs_sz {357 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }358 } else if lhs_sz > rhs_sz {359 // We zero-extend even if the RHS is signed. So e.g. `(x: i32) << -1i8` will zero-extend the360 // RHS to `255i32`. But then we mask the shift amount to be within the size of the LHS361 // anyway so the result is `31` as it should be. All the extra bits introduced by zext362 // are masked off so their value does not matter.363 // FIXME: if we ever support 512bit integers, this will be wrong! For such large integers,364 // the extra bits introduced by zext are *not* all masked away any more.365 assert!(lhs_sz <= 256);366 bx.zext(rhs, lhs_llty)367 } else {368 rhs369 }370}371372// Returns `true` if this session's target will use native wasm373// exceptions. This means that the VM does the unwinding for374// us375pub fn wants_wasm_eh(target: &TargetSpec) -> bool {376 target.is_like_wasm377}378379/// Returns `true` if this session's target will use SEH-based unwinding.380///381/// This is only true for MSVC targets, and even then the 64-bit MSVC target382/// currently uses SEH-ish unwinding with DWARF info tables to the side (same as383/// 64-bit MinGW) instead of "full SEH".384pub fn wants_msvc_seh(target: &TargetSpec) -> bool {385 target.is_like_msvc386}387388/// Returns `true` if this session's target requires the new exception389/// handling LLVM IR instructions (catchpad / cleanuppad / ... instead390/// of landingpad)391pub(crate) fn wants_new_eh_instructions(target: &TargetSpec) -> bool {392 wants_wasm_eh(target) || wants_msvc_seh(target)393}394395pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(396 cx: &'a Bx::CodegenCx,397 instance: Instance<'tcx>,398) {399 // this is an info! to allow collecting monomorphization statistics400 // and to allow finding the last function before LLVM aborts from401 // release builds.402 info!("codegen_instance({})", instance);403404 mir::codegen_mir::<Bx>(cx, instance);405}406407pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: hir::ItemId)408where409 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,410{411 let item = cx.tcx().hir_item(item_id);412 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {413 let operands: Vec<_> = asm414 .operands415 .iter()416 .map(|(op, op_sp)| match *op {417 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {418 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {419 Ok(const_value) => {420 let ty =421 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);422 let ConstValue::Scalar(scalar) = const_value else {423 span_bug!(424 *op_sp,425 "expected Scalar for promoted asm const, but got {:#?}",426 const_value427 )428 };429 GlobalAsmOperandRef::Const {430 value: common::asm_const_ptr_clean(cx.tcx(), scalar),431 ty,432 }433 }434 Err(ErrorHandled::Reported { .. }) => {435 // An error has already been reported and436 // compilation is guaranteed to fail if execution437 // hits this path. So anything will suffice.438 GlobalAsmOperandRef::Const {439 value: Scalar::from_u32(0),440 ty: Ty::new_uint(cx.tcx(), UintTy::U32),441 }442 }443 Err(ErrorHandled::TooGeneric(_)) => {444 span_bug!(*op_sp, "asm const cannot be resolved; too generic")445 }446 }447 }448 rustc_hir::InlineAsmOperand::SymFn { expr } => {449 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);450 let instance = match ty.kind() {451 &ty::FnDef(def_id, args) => Instance::expect_resolve(452 cx.tcx(),453 cx.typing_env(),454 def_id,455 args.no_bound_vars().unwrap(),456 expr.span,457 ),458 _ => span_bug!(*op_sp, "asm sym is not a function"),459 };460461 GlobalAsmOperandRef::Const {462 value: Scalar::from_pointer(463 cx.tcx().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT).into(),464 cx,465 ),466 ty: Ty::new_fn_ptr(cx.tcx(), ty.fn_sig(cx.tcx())),467 }468 }469 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {470 if cx.tcx().is_thread_local_static(def_id) {471 GlobalAsmOperandRef::SymThreadLocalStatic { def_id }472 } else {473 GlobalAsmOperandRef::Const {474 value: Scalar::from_pointer(475 cx.tcx().reserve_and_set_static_alloc(def_id).into(),476 cx,477 ),478 ty: cx.tcx().static_ptr_ty(def_id, cx.typing_env()),479 }480 }481 }482 rustc_hir::InlineAsmOperand::In { .. }483 | rustc_hir::InlineAsmOperand::Out { .. }484 | rustc_hir::InlineAsmOperand::InOut { .. }485 | rustc_hir::InlineAsmOperand::SplitInOut { .. }486 | rustc_hir::InlineAsmOperand::Label { .. } => {487 span_bug!(*op_sp, "invalid operand type for global_asm!")488 }489 })490 .collect();491492 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans, &[]);493 } else {494 span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")495 }496}497498/// Creates the `main` function which will initialize the rust runtime and call499/// users main function.500pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(501 cx: &'a Bx::CodegenCx,502 cgu: &CodegenUnit<'tcx>,503) -> Option<Bx::Function> {504 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;505 let main_is_local = main_def_id.is_local();506 let instance = Instance::mono(cx.tcx(), main_def_id);507508 if main_is_local {509 // We want to create the wrapper in the same codegen unit as Rust's main510 // function.511 if !cgu.contains_item(&MonoItem::Fn(instance)) {512 return None;513 }514 } else if !cgu.is_primary() {515 // We want to create the wrapper only when the codegen unit is the primary one516 return None;517 }518519 let main_llfn = cx.get_fn_addr(instance, cx.sess().pointer_authentication_functions());520521 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);522 return Some(entry_fn);523524 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(525 cx: &'a Bx::CodegenCx,526 rust_main: Bx::Value,527 rust_main_def_id: DefId,528 entry_type: EntryFnType,529 ) -> Bx::Function {530 // The entry function is either `int main(void)` or `int main(int argc, char **argv)`, or531 // `usize efi_main(void *handle, void *system_table)` depending on the target.532 let llfty = if cx.sess().target.os == Os::Uefi {533 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())534 } else if cx.sess().target.main_needs_argc_argv {535 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())536 } else {537 cx.type_func(&[], cx.type_int())538 };539540 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();541 // Given that `main()` has no arguments,542 // then its return type cannot have543 // late-bound regions, since late-bound544 // regions must appear in the argument545 // listing.546 let main_ret_ty = cx.tcx().normalize_erasing_regions(547 cx.typing_env(),548 Unnormalized::new_wip(main_ret_ty.no_bound_vars().unwrap()),549 );550551 let Some(llfn) = cx.declare_c_main(llfty) else {552 // FIXME: We should be smart and show a better diagnostic here.553 let span = cx.tcx().def_span(rust_main_def_id);554 cx.tcx().dcx().emit_fatal(diagnostics::MultipleMainFunctions { span });555 };556557 // `main` should respect same config for frame pointer elimination as rest of code558 cx.set_frame_pointer_type(llfn);559 cx.apply_target_cpu_attr(llfn);560561 let llbb = Bx::append_block(cx, llfn, "top");562 let mut bx = Bx::build(cx, llbb);563564 bx.insert_reference_to_gdb_debug_scripts_section_global();565566 let isize_ty = cx.type_isize();567 let ptr_ty = cx.type_ptr();568 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);569570 let EntryFnType::Main { sigpipe } = entry_type;571 let (start_fn, start_ty, args, instance) = {572 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);573 let start_instance = ty::Instance::expect_resolve(574 cx.tcx(),575 cx.typing_env(),576 start_def_id,577 cx.tcx().mk_args(&[main_ret_ty.into()]),578 DUMMY_SP,579 );580 let start_fn =581 cx.get_fn_addr(start_instance, cx.sess().pointer_authentication_functions());582583 let i8_ty = cx.type_i8();584 let arg_sigpipe = bx.const_u8(sigpipe);585586 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);587 (588 start_fn,589 start_ty,590 vec![rust_main, arg_argc, arg_argv, arg_sigpipe],591 Some(start_instance),592 )593 };594595 let result =596 bx.call(start_ty, None, None, start_fn, ReturnSlot::Direct, &args, None, instance);597 if cx.sess().target.os == Os::Uefi {598 bx.ret(result);599 } else {600 let cast = bx.intcast(result, cx.type_int(), true);601 bx.ret(cast);602 }603604 llfn605 }606}607608/// Obtain the `argc` and `argv` values to pass to the rust start function609/// (i.e., the "start" lang item).610fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {611 if bx.cx().sess().target.os == Os::Uefi {612 // Params for UEFI613 let param_handle = bx.get_param(0);614 let param_system_table = bx.get_param(1);615 let ptr_size = bx.tcx().data_layout.pointer_size();616 let ptr_align = bx.tcx().data_layout.pointer_align().abi;617 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);618 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);619 bx.store(param_handle, arg_argv, ptr_align);620 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));621 bx.store(param_system_table, arg_argv_el1, ptr_align);622 (arg_argc, arg_argv)623 } else if bx.cx().sess().target.main_needs_argc_argv {624 // Params from native `main()` used as args for rust start function625 let param_argc = bx.get_param(0);626 let param_argv = bx.get_param(1);627 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);628 let arg_argv = param_argv;629 (arg_argc, arg_argv)630 } else {631 // The Rust start function doesn't need `argc` and `argv`, so just pass zeros.632 let arg_argc = bx.const_int(bx.cx().type_int(), 0);633 let arg_argv = bx.const_null(bx.cx().type_ptr());634 (arg_argc, arg_argv)635 }636}637638/// This function returns all of the debugger visualizers specified for the639/// current crate as well as all upstream crates transitively that match the640/// `visualizer_type` specified.641pub fn collect_debugger_visualizers_transitive(642 tcx: TyCtxt<'_>,643 visualizer_type: DebuggerVisualizerType,644) -> BTreeSet<DebuggerVisualizerFile> {645 tcx.debugger_visualizers(LOCAL_CRATE)646 .iter()647 .chain(648 tcx.crates(())649 .iter()650 .filter(|&cnum| {651 let used_crate_source = tcx.used_crate_source(*cnum);652 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()653 })654 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),655 )656 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)657 .cloned()658 .collect::<BTreeSet<_>>()659}660661/// Decide allocator kind to codegen. If `Some(_)` this will be the same as662/// `tcx.allocator_kind`, but it may be `None` in more cases (e.g. if using663/// allocator definitions from a dylib dependency).664pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {665 // If the crate doesn't have an `allocator_kind` set then there's definitely666 // no shim to generate. Otherwise we also check our dependency graph for all667 // our output crate types. If anything there looks like its a `Dynamic`668 // linkage for all crate types we may link as, then it's already got an669 // allocator shim and we'll be using that one instead. If nothing exists670 // then it's our job to generate the allocator! If crate types disagree671 // about whether an allocator shim is necessary or not, we generate one672 // and let needs_allocator_shim_for_linking decide at link time whether or673 // not to use it for any particular linker invocation.674 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {675 use rustc_middle::middle::dependency_format::Linkage;676 list.iter().any(|&linkage| linkage == Linkage::Dynamic)677 });678 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }679}680681/// Decide if this particular crate type needs an allocator shim linked in.682/// This may return true even when allocator_kind_for_codegen returns false. In683/// this case no allocator shim shall be linked.684pub(crate) fn needs_allocator_shim_for_linking(685 dependency_formats: &Dependencies,686 crate_type: CrateType,687) -> bool {688 use rustc_middle::middle::dependency_format::Linkage;689 let any_dynamic_crate =690 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);691 !any_dynamic_crate692}693694pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {695 let mut methods = Vec::new();696697 if kind == AllocatorKind::Default {698 methods.extend(ALLOCATOR_METHODS.into_iter().copied());699 }700701 // If the return value of allocator_kind_for_codegen is Some then702 // alloc_error_handler_kind must also be Some.703 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {704 methods.push(AllocatorMethod {705 name: ALLOC_ERROR_HANDLER,706 special: None,707 inputs: &[AllocatorMethodInput { name: "layout", ty: AllocatorTy::Layout }],708 output: AllocatorTy::Never,709 });710 }711712 methods713}714715pub fn codegen_crate<716 B: ExtraBackendMethods<Module = M> + WriteBackendMethods<Module = M>,717 M: Send,718>(719 backend: B,720 tcx: TyCtxt<'_>,721) -> OngoingCodegen<B> {722 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {723 // The target has no default cpu, but none is set explicitly724 tcx.dcx().emit_fatal(diagnostics::CpuRequired);725 }726727 if let Some(target_cpu) = &tcx.sess.opts.cg.target_cpu728 && tcx.sess.target.unsupported_cpus.contains(&target_cpu.into())729 {730 // The target cpu is explicitly listed as an unsupported cpu731 tcx.dcx().emit_fatal(diagnostics::CpuUnsupported { target_cpu: target_cpu.clone() });732 }733734 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);735736 // Run the monomorphization collector and partition the collected items into737 // codegen units.738 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());739740 // Force all codegen_unit queries so they are already either red or green741 // when compile_codegen_unit accesses them. We are not able to re-execute742 // the codegen_unit query from just the DepNode, so an unknown color would743 // lead to having to re-execute compile_codegen_unit, possibly744 // unnecessarily.745 if tcx.dep_graph.is_fully_enabled() {746 for cgu in codegen_units {747 tcx.ensure_ok().codegen_unit(cgu.name());748 }749 }750751 // Codegen an allocator shim, if necessary.752 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {753 let llmod_id =754 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();755756 tcx.sess.time("write_allocator_module", || {757 let module =758 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));759 Some(ModuleCodegen::new_allocator(llmod_id, module))760 })761 } else {762 None763 };764765 let no_builtins = find_attr!(tcx, crate, NoBuiltins);766 let regular_module_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);767 let bitcode_needed = regular_module_config.bitcode_needed();768 let allocator_module_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);769770 let ongoing_codegen = start_async_codegen(771 backend.clone(),772 tcx,773 Arc::new(regular_module_config),774 Arc::new(allocator_module_config),775 allocator_module,776 );777778 // For better throughput during parallel processing by LLVM, we used to sort779 // CGUs largest to smallest. This would lead to better thread utilization780 // by, for example, preventing a large CGU from being processed last and781 // having only one LLVM thread working while the rest remained idle.782 //783 // However, this strategy would lead to high memory usage, as it meant the784 // LLVM-IR for all of the largest CGUs would be resident in memory at once.785 //786 // Instead, we can compromise by ordering CGUs such that the largest and787 // smallest are first, second largest and smallest are next, etc. If there788 // are large size variations, this can reduce memory usage significantly.789 let codegen_units: Vec<_> = {790 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();791 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));792793 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);794 first_half.iter().interleave(second_half.iter().rev()).copied().collect()795 };796797 // Calculate the CGU reuse798 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {799 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()800 });801802 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {803 for (i, cgu) in codegen_units.iter().enumerate() {804 let cgu_reuse = cgu_reuse[i];805 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);806 }807 });808809 let mut total_codegen_time = Duration::new(0, 0);810 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());811812 // The non-parallel compiler can only translate codegen units to LLVM IR813 // on a single thread, leading to a staircase effect where the N LLVM814 // threads have to wait on the single codegen threads to generate work815 // for them. The parallel compiler does not have this restriction, so816 // we can pre-load the LLVM queue in parallel before handing off817 // coordination to the OnGoingCodegen scheduler.818 //819 // This likely is a temporary measure. Once we don't have to support the820 // non-parallel compiler anymore, we can compile CGUs end-to-end in821 // parallel and get rid of the complicated scheduling logic.822 let mut pre_compiled_cgus = if let Some(threads) = tcx.sess.opts.jobs.frontend {823 tcx.sess.time("compile_first_CGU_batch", || {824 // Try to find one CGU to compile per thread.825 let cgus: Vec<_> = cgu_reuse826 .iter()827 .enumerate()828 .filter(|&(_, reuse)| reuse == &CguReuse::No)829 .take(threads.get())830 .collect();831832 // Compile the found CGUs in parallel.833 let start_time = Instant::now();834835 let pre_compiled_cgus = par_map(cgus, |(i, _)| {836 let module =837 backend.compile_codegen_unit(tcx, codegen_units[i].name(), bitcode_needed);838 (i, IntoDynSyncSend(module))839 });840841 total_codegen_time += start_time.elapsed();842843 pre_compiled_cgus844 })845 } else {846 FxHashMap::default()847 };848849 for (i, cgu) in codegen_units.iter().enumerate() {850 ongoing_codegen.wait_for_signal_to_codegen_item();851 ongoing_codegen.check_for_errors(tcx.sess);852853 let cgu_reuse = cgu_reuse[i];854855 match cgu_reuse {856 CguReuse::No => {857 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {858 cgu.0859 } else {860 let start_time = Instant::now();861 let module = backend.compile_codegen_unit(tcx, cgu.name(), bitcode_needed);862 total_codegen_time += start_time.elapsed();863 module864 };865 // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`866 // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes867 // compilation hang on post-monomorphization errors.868 tcx.dcx().abort_if_errors();869870 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);871 }872 CguReuse::PreLto => {873 submit_pre_lto_module_to_llvm(874 tcx,875 &ongoing_codegen.coordinator,876 CachedModuleCodegen {877 name: cgu.name().to_string(),878 source: cgu.previous_work_product(tcx),879 },880 );881 // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`882 // guard. Unfortunately, just skipping the `submit_pre_lto_module_to_llvm` makes883 // compilation hang on post-monomorphization errors.884 tcx.dcx().abort_if_errors();885 }886 CguReuse::PostLto => {887 submit_post_lto_module_to_llvm(888 &ongoing_codegen.coordinator,889 CachedModuleCodegen {890 name: cgu.name().to_string(),891 source: cgu.previous_work_product(tcx),892 },893 );894 }895 }896 }897898 ongoing_codegen.codegen_finished(tcx);899900 // Since the main thread is sometimes blocked during codegen, we keep track901 // -Ztime-passes output manually.902 if tcx.sess.opts.unstable_opts.time_passes {903 let end_rss = get_resident_set_size();904905 print_time_passes_entry(906 "codegen_to_LLVM_IR",907 total_codegen_time,908 start_rss.unwrap(),909 end_rss,910 tcx.sess.opts.unstable_opts.time_passes_format,911 );912 }913914 ongoing_codegen.check_for_errors(tcx.sess);915 ongoing_codegen916}917918/// Returns whether a call from the current crate to the [`Instance`] would produce a call919/// from `compiler_builtins` to a symbol the linker must resolve.920///921/// Such calls from `compiler_builtins` are effectively impossible for the linker to handle. Some922/// linkers will optimize such that dead calls to unresolved symbols are not an error, but this is923/// not guaranteed. So we use this function in codegen backends to ensure we do not generate any924/// unlinkable calls.925///926/// Note that calls to LLVM intrinsics are uniquely okay because they won't make it to the linker.927/// Note also that calls to foreign items that are actually exported by the local crate are also928/// okay. This situation arises because compiler-builtins calls functions in core that are929/// `#[inline]` wrappers for `extern "C"` declarations in core, which resolve to a symbol exported930/// by compiler-builtins.931pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(932 tcx: TyCtxt<'tcx>,933 instance: Instance<'tcx>,934) -> bool {935 if let ty::InstanceKind::LlvmIntrinsic(_) = instance.def {936 return false;937 }938939 fn is_extern_call_to_local_crate<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {940 tcx.is_foreign_item(instance.def_id())941 && tcx.exported_non_generic_symbols(LOCAL_CRATE).iter().any(|(sym, _info)| {942 sym.symbol_name_for_local_instance(tcx) == tcx.symbol_name(instance)943 })944 }945946 let def_id = instance.def_id();947 !def_id.is_local()948 && tcx.is_compiler_builtins(LOCAL_CRATE)949 && !tcx.should_codegen_locally(instance)950 && !is_extern_call_to_local_crate(tcx, instance)951}952953fn collect_eii_linkage(tcx: TyCtxt<'_>) -> Vec<EiiLinkageInfo> {954 #[derive(Debug)]955 struct FoundImpl {956 imp: EiiImpl,957 impl_crate: CrateNum,958 }959960 #[derive(Debug)]961 struct FoundEii {962 decl: EiiDecl,963 impls: FxIndexMap<DefId, FoundImpl>,964 }965966 let mut eiis = FxIndexMap::<DefId, FoundEii>::default();967968 for &cnum in tcx.crates(()).iter().chain(iter::once(&LOCAL_CRATE)) {969 for (&did, &(decl, ref impls)) in tcx.externally_implementable_items(cnum) {970 eiis.entry(did)971 .or_insert_with(|| FoundEii { decl, impls: Default::default() })972 .impls973 .extend(974 impls975 .into_iter()976 .map(|(&did, &imp)| (did, FoundImpl { imp, impl_crate: cnum })),977 );978 }979 }980981 eiis.into_iter()982 .filter_map(|(_, FoundEii { decl, impls })| {983 let mut explicit_impls = Vec::new();984 let mut default_impl = None;985986 for (impl_did, FoundImpl { imp, impl_crate }) in impls {987 let impl_info = EiiLinkageImplInfo { span: tcx.def_span(impl_did), impl_crate };988 if imp.is_default {989 default_impl = Some(impl_info);990 } else {991 explicit_impls.push(impl_info);992 }993 }994995 // Link time check is only needed when there may be a default impl in a dylib.996 // Other cases emit an error in `rustc_passes` already.997 if let Some(default_impl) = default_impl {998 Some(EiiLinkageInfo {999 name: decl.name.name,1000 impls: explicit_impls,1001 default_impl: Some(default_impl),1002 })1003 } else {1004 None1005 }1006 })1007 .collect()1008}10091010fn eii_linkage_needed(dependency_formats: &Dependencies) -> bool {1011 dependency_formats.values().any(|formats| {1012 formats1013 .iter()1014 .any(|&linkage| matches!(linkage, Linkage::Dynamic | Linkage::IncludedFromDylib))1015 })1016}10171018impl CrateInfo {1019 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {1020 let crate_types = tcx.crate_types().to_vec();1021 let exported_symbols = crate_types1022 .iter()1023 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))1024 .collect();1025 let linked_symbols =1026 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();1027 let local_crate_name = tcx.crate_name(LOCAL_CRATE);1028 let windows_subsystem = find_attr!(tcx, crate, WindowsSubsystem(kind) => *kind);1029 let dependency_formats = Arc::clone(tcx.dependency_formats(()));1030 let eii_linkage = if eii_linkage_needed(&dependency_formats) {1031 collect_eii_linkage(tcx)1032 } else {1033 Vec::new()1034 };10351036 // This list is used when generating the command line to pass through to1037 // system linker. The linker expects undefined symbols on the left of the1038 // command line to be defined in libraries on the right, not the other way1039 // around. For more info, see some comments in the add_used_library function1040 // below.1041 //1042 // In order to get this left-to-right dependency ordering, we use the reverse1043 // postorder of all crates putting the leaves at the rightmost positions.1044 let mut compiler_builtins = None;1045 let mut used_crates: Vec<_> = tcx1046 .postorder_cnums(())1047 .iter()1048 .rev()1049 .copied()1050 .filter(|&cnum| {1051 let link = !tcx.crate_dep_kind(cnum).macros_only();1052 if link && tcx.is_compiler_builtins(cnum) {1053 compiler_builtins = Some(cnum);1054 return false;1055 }1056 link1057 })1058 .collect();1059 // `compiler_builtins` are always placed last to ensure that they're linked correctly.1060 used_crates.extend(compiler_builtins);10611062 let crates = tcx.crates(());1063 let n_crates = crates.len();1064 let mut info = CrateInfo {1065 target_cpu,1066 target_features: tcx.sess.global_backend_features.clone(),1067 crate_types,1068 exported_symbols,1069 linked_symbols,1070 local_crate_name,1071 compiler_builtins,1072 profiler_runtime: None,1073 is_no_builtins: Default::default(),1074 native_libraries: Default::default(),1075 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),1076 crate_name: UnordMap::with_capacity(n_crates),1077 used_crates,1078 used_crate_source: UnordMap::with_capacity(n_crates),1079 dependency_formats,1080 eii_linkage,1081 windows_subsystem,1082 natvis_debugger_visualizers: Default::default(),1083 lint_level_specs: CodegenLintLevelSpecs::from_tcx(tcx),1084 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),1085 symbol_rename_suffix: format!(".rs{:x}", tcx.stable_crate_id(LOCAL_CRATE)),1086 each_linked_rlib_file_for_lto: Default::default(),1087 exported_symbols_for_lto: Default::default(),1088 };10891090 info.native_libraries.reserve(n_crates);10911092 for &cnum in crates.iter() {1093 info.native_libraries1094 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());1095 info.crate_name.insert(cnum, tcx.crate_name(cnum));10961097 let used_crate_source = tcx.used_crate_source(cnum);1098 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));1099 if tcx.is_profiler_runtime(cnum) {1100 info.profiler_runtime = Some(cnum);1101 }1102 if tcx.is_no_builtins(cnum) {1103 info.is_no_builtins.insert(cnum);1104 }1105 }11061107 // Handle circular dependencies in the standard library.1108 // See comment before `add_linked_symbol_object` function for the details.1109 // If global LTO is enabled then almost everything (*) is glued into a single object file,1110 // so this logic is not necessary and can cause issues on some targets (due to weak lang1111 // item symbols being "privatized" to that object file), so we disable it.1112 // (*) Native libs, and `#[compiler_builtins]` and `#[no_builtins]` crates are not glued,1113 // and we assume that they cannot define weak lang items. This is not currently enforced1114 // by the compiler, but that's ok because all this stuff is unstable anyway.1115 let target = &tcx.sess.target;1116 if !are_upstream_rust_objects_already_included(tcx.sess) {1117 let add_prefix = match (target.is_like_windows, &target.arch) {1118 (true, Arch::X86) => |name: String, _: SymbolExportKind| format!("_{name}"),1119 (true, Arch::Arm64EC) => {1120 // Only functions are decorated for arm64ec.1121 |name: String, export_kind: SymbolExportKind| match export_kind {1122 SymbolExportKind::Text => format!("#{name}"),1123 _ => name,1124 }1125 }1126 _ => |name: String, _: SymbolExportKind| name,1127 };1128 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info1129 .used_crates1130 .iter()1131 .flat_map(|&cnum| tcx.missing_lang_items(cnum))1132 .filter(|l| l.is_weak())1133 .filter_map(|&l| {1134 let name = l.link_name()?;1135 let export_kind = match l.target() {1136 Target::ForeignFn | Target::Fn => SymbolExportKind::Text,1137 Target::Static => SymbolExportKind::Data,1138 _ => bug!(1139 "Don't know what the export kind is for lang item of kind {:?}",1140 l.target()1141 ),1142 };1143 lang_items::required(tcx, l).then_some((name, export_kind))1144 })1145 .collect();11461147 // This loop only adds new items to values of the hash map, so the order in which we1148 // iterate over the values is not important.1149 #[allow(rustc::potential_query_instability)]1150 info.linked_symbols1151 .iter_mut()1152 .filter(|(crate_type, _)| {1153 !matches!(crate_type, CrateType::Rlib | CrateType::StaticLib)1154 })1155 .for_each(|(_, linked_symbols)| {1156 let mut symbols = missing_weak_lang_items1157 .iter()1158 .map(|(item, export_kind)| {1159 (1160 add_prefix(1161 mangle_internal_symbol(tcx, item.as_str()),1162 *export_kind,1163 ),1164 *export_kind,1165 )1166 })1167 .collect::<Vec<_>>();1168 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));1169 linked_symbols.extend(symbols);1170 });1171 }11721173 let mut each_linked_rlib_for_lto = Vec::new();1174 let mut each_linked_rlib_file_for_lto = Vec::new();1175 if tcx.sess.lto() != config::Lto::No && tcx.sess.lto() != config::Lto::ThinLocal {1176 drop(crate::back::link::each_linked_rlib(&info, None, &mut |cnum, path| {1177 if crate::back::link::ignored_for_lto(tcx.sess, &info, cnum) {1178 return;1179 }11801181 each_linked_rlib_for_lto.push(cnum);1182 each_linked_rlib_file_for_lto.push(path.to_path_buf());1183 }));1184 }1185 info.each_linked_rlib_file_for_lto = each_linked_rlib_file_for_lto;11861187 // FIXME move to -Zlink-only half such that each_linked_rlib_file_for_lto can be moved there too1188 // Compute the set of symbols we need to retain when doing LTO (if we need to)1189 info.exported_symbols_for_lto =1190 crate::back::lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto);11911192 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {1193 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {1194 // These are crate types for which we invoke the linker and can embed1195 // NatVis visualizers.1196 true1197 }1198 CrateType::ProcMacro => {1199 // We could embed NatVis for proc macro crates too (to improve the debugging1200 // experience for them) but it does not seem like a good default, since1201 // this is a rare use case and we don't want to slow down the common case.1202 false1203 }1204 CrateType::StaticLib | CrateType::Rlib => {1205 // We don't invoke the linker for these, so we don't need to collect the NatVis for1206 // them.1207 false1208 }1209 });12101211 if target.is_like_msvc && embed_visualizers {1212 info.natvis_debugger_visualizers =1213 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);1214 }12151216 info1217 }1218}12191220pub(crate) fn provide(providers: &mut Providers) {1221 providers.backend_optimization_level = |tcx, cratenum| {1222 let for_speed = match tcx.sess.opts.optimize {1223 // If globally no optimisation is done, #[optimize] has no effect.1224 //1225 // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the1226 // pass manager and it is likely that some module-wide passes (such as inliner or1227 // cross-function constant propagation) would ignore the `optnone` annotation we put1228 // on the functions, thus necessarily involving these functions into optimisations.1229 config::OptLevel::No => return config::OptLevel::No,1230 // If globally optimise-speed is already specified, just use that level.1231 config::OptLevel::Less => return config::OptLevel::Less,1232 config::OptLevel::More => return config::OptLevel::More,1233 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,1234 // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)1235 // are present).1236 config::OptLevel::Size => config::OptLevel::More,1237 config::OptLevel::SizeMin => config::OptLevel::More,1238 };12391240 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;12411242 let any_for_speed = defids.items().any(|id| {1243 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);1244 matches!(optimize, OptimizeAttr::Speed)1245 });12461247 if any_for_speed {1248 return for_speed;1249 }12501251 tcx.sess.opts.optimize1252 };1253}12541255pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {1256 if !tcx.dep_graph.is_fully_enabled()1257 || tcx.sess.opts.unstable_opts.disable_incr_comp_backend_caching1258 {1259 return CguReuse::No;1260 }12611262 let work_product_id = &cgu.work_product_id();1263 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {1264 // We don't have anything cached for this CGU. This can happen1265 // if the CGU did not exist in the previous session.1266 return CguReuse::No;1267 }12681269 // Try to mark the CGU as green. If it we can do so, it means that nothing1270 // affecting the LLVM module has changed and we can re-use a cached version.1271 // If we compile with any kind of LTO, this means we can re-use the bitcode1272 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only1273 // know that later). If we are not doing LTO, there is only one optimized1274 // version of each module, so we re-use that.1275 let dep_node = cgu.codegen_dep_node(tcx);1276 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {1277 format!(1278 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",1279 cgu.name()1280 )1281 });12821283 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {1284 // We can re-use either the pre- or the post-thinlto state. If no LTO is1285 // being performed then we can use post-LTO artifacts, otherwise we must1286 // reuse pre-LTO artifacts1287 match compute_per_cgu_lto_type(1288 &tcx.sess.lto(),1289 tcx.sess.opts.cg.linker_plugin_lto.enabled(),1290 tcx.crate_types(),1291 ) {1292 ComputedLtoType::No => CguReuse::PostLto,1293 _ => CguReuse::PreLto,1294 }1295 } else {1296 CguReuse::No1297 }1298}