1use std::collections::BTreeSet;
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4use std::{cmp, iter};
5
6use 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_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
13use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
14use rustc_data_structures::sync::{IntoDynSyncSend, par_map};
15use rustc_data_structures::unord::UnordMap;
16use rustc_hir::attrs::lang_items::LangItem;
17use rustc_hir::attrs::{DebuggerVisualizerType, EiiDecl, EiiImpl, OptimizeAttr};
18use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
19use rustc_hir::{ItemId, Target, find_attr};
20use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
21use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
22use rustc_middle::middle::dependency_format::{Dependencies, Linkage};
23use rustc_middle::middle::exported_symbols::{self, SymbolExportKind};
24use rustc_middle::middle::lang_items;
25use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, ErrorHandled, Scalar};
26use rustc_middle::mir::{BinOp, ConstValue};
27use rustc_middle::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};
28use rustc_middle::query::Providers;
29use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
30use rustc_middle::ty::{self, Instance, PatternKind, Ty, TyCtxt, UintTy, Unnormalized};
31use rustc_middle::{bug, span_bug};
32use rustc_session::Session;
33use rustc_session::config::{self, EntryFnType};
34use rustc_span::{DUMMY_SP, Symbol};
35use rustc_structures::CrateType;
36use rustc_symbol_mangling::mangle_internal_symbol;
37use rustc_target::spec::{Arch, Os};
38use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
39use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
40use tracing::{debug, info};
41
42use crate::assert_module_sources::CguReuse;
43use crate::back::link::are_upstream_rust_objects_already_included;
44use crate::back::write::{
45 ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
46 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
47};
48use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
49use crate::meth::load_vtable;
50use crate::mir::operand::OperandValue;
51use crate::mir::place::PlaceRef;
52use crate::traits::*;
53use crate::{
54 CachedModuleCodegen, CodegenLintLevelSpecs, CrateInfo, EiiLinkageImplInfo, EiiLinkageInfo,
55 ModuleCodegen, diagnostics, meth, mir,
56};
57
58pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
59 match (op, signed) {
60 (BinOp::Eq, _) => IntPredicate::IntEQ,
61 (BinOp::Ne, _) => IntPredicate::IntNE,
62 (BinOp::Lt, true) => IntPredicate::IntSLT,
63 (BinOp::Lt, false) => IntPredicate::IntULT,
64 (BinOp::Le, true) => IntPredicate::IntSLE,
65 (BinOp::Le, false) => IntPredicate::IntULE,
66 (BinOp::Gt, true) => IntPredicate::IntSGT,
67 (BinOp::Gt, false) => IntPredicate::IntUGT,
68 (BinOp::Ge, true) => IntPredicate::IntSGE,
69 (BinOp::Ge, false) => IntPredicate::IntUGE,
70 op => ::rustc_middle::util::bug::bug_fmt(format_args!("bin_op_to_icmp_predicate: expected comparison operator, found {0:?}",
op))bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
71 }
72}
73
74pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
75 match op {
76 BinOp::Eq => RealPredicate::RealOEQ,
77 BinOp::Ne => RealPredicate::RealUNE,
78 BinOp::Lt => RealPredicate::RealOLT,
79 BinOp::Le => RealPredicate::RealOLE,
80 BinOp::Gt => RealPredicate::RealOGT,
81 BinOp::Ge => RealPredicate::RealOGE,
82 op => ::rustc_middle::util::bug::bug_fmt(format_args!("bin_op_to_fcmp_predicate: expected comparison operator, found {0:?}",
op))bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
83 }
84}
85
86pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
87 bx: &mut Bx,
88 lhs: Bx::Value,
89 rhs: Bx::Value,
90 t: Ty<'tcx>,
91 ret_ty: Bx::Type,
92 op: BinOp,
93) -> Bx::Value {
94 let signed = match t.kind() {
95 ty::Float(_) => {
96 let cmp = bin_op_to_fcmp_predicate(op);
97 let cmp = bx.fcmp(cmp, lhs, rhs);
98 return bx.sext(cmp, ret_ty);
99 }
100 ty::Uint(_) => false,
101 ty::Int(_) => true,
102 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("compare_simd_types: invalid SIMD type"))bug!("compare_simd_types: invalid SIMD type"),
103 };
104
105 let cmp = bin_op_to_icmp_predicate(op, signed);
106 let cmp = bx.icmp(cmp, lhs, rhs);
107 bx.sext(cmp, ret_ty)
112}
113
114pub fn validate_trivial_unsize<'tcx>(
123 tcx: TyCtxt<'tcx>,
124 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
125 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
126) -> bool {
127 match (source_data.principal(), target_data.principal()) {
128 (Some(hr_source_principal), Some(hr_target_principal)) => {
129 let (infcx, param_env) =
130 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
131 let universe = infcx.universe();
132 let ocx = ObligationCtxt::new(&infcx);
133 infcx.enter_forall(hr_target_principal, |target_principal| {
134 let source_principal = infcx.instantiate_binder_with_fresh_vars(
135 DUMMY_SP,
136 BoundRegionConversionTime::HigherRankedType,
137 hr_source_principal,
138 );
139 let Ok(()) = ocx.eq(
140 &ObligationCause::dummy(),
141 param_env,
142 target_principal,
143 source_principal,
144 ) else {
145 return false;
146 };
147 if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
148 return false;
149 }
150 infcx.leak_check(universe, None).is_ok()
151 })
152 }
153 (_, None) => true,
154 _ => false,
155 }
156}
157
158fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
164 bx: &mut Bx,
165 source: Ty<'tcx>,
166 target: Ty<'tcx>,
167 old_info: Option<Bx::Value>,
168) -> Bx::Value {
169 let cx = bx.cx();
170 let (source, target) =
171 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
172 match (source.kind(), target.kind()) {
173 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
174 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
175 ),
176 (&ty::Dynamic(data_a, _), &ty::Dynamic(data_b, _)) => {
177 let old_info =
178 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
179 let b_principal_def_id = data_b.principal_def_id();
180 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
181 if true {
if !validate_trivial_unsize(cx.tcx(), data_a, data_b) {
{
::core::panicking::panic_fmt(format_args!("NOP unsize vtable changed principal trait ref: {0} -> {1}",
data_a, data_b));
}
};
};debug_assert!(
190 validate_trivial_unsize(cx.tcx(), data_a, data_b),
191 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
192 );
193
194 return old_info;
200 }
201
202 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
205
206 if let Some(entry_idx) = vptr_entry_idx {
207 let ptr_size = bx.data_layout().pointer_size();
208 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
209 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
210 } else {
211 old_info
212 }
213 }
214 (_, ty::Dynamic(data, _)) => meth::get_vtable(
215 cx,
216 source,
217 data.principal()
218 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
219 ),
220 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsized_info: invalid unsizing {0:?} -> {1:?}",
source, target))bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
221 }
222}
223
224pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
226 bx: &mut Bx,
227 src: Bx::Value,
228 src_ty: Ty<'tcx>,
229 dst_ty: Ty<'tcx>,
230 old_info: Option<Bx::Value>,
231) -> (Bx::Value, Bx::Value) {
232 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/base.rs:232",
"rustc_codegen_ssa::base", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/base.rs"),
::tracing_core::__macro_support::Option::Some(232u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::base"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("unsize_ptr: {0:?} => {1:?}",
src_ty, dst_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
233 match (src_ty.kind(), dst_ty.kind()) {
234 (&ty::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),
235 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
236 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
237 {
match (&bx.cx().type_is_sized(a), &old_info.is_none()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
238 (src, unsized_info(bx, a, b, old_info))
239 }
240 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
241 {
match (&def_a, &def_b) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(def_a, def_b); let src_layout = bx.cx().layout_of(src_ty);
243 let dst_layout = bx.cx().layout_of(dst_ty);
244 if src_ty == dst_ty {
245 return (src, old_info.unwrap());
246 }
247 let mut result = None;
248 for i in 0..src_layout.fields.count() {
249 let src_f = src_layout.field(bx.cx(), i);
250 if src_f.is_1zst() {
251 continue;
253 }
254
255 {
match (&src_layout.fields.offset(i).bytes(), &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(src_layout.fields.offset(i).bytes(), 0);
256 {
match (&dst_layout.fields.offset(i).bytes(), &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
257 {
match (&src_layout.size, &src_f.size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(src_layout.size, src_f.size);
258
259 let dst_f = dst_layout.field(bx.cx(), i);
260 {
match (&src_f.ty, &dst_f.ty) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_ne!(src_f.ty, dst_f.ty);
261 {
match (&result, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(result, None);
262 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
263 }
264 result.unwrap()
265 }
266 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsize_ptr: called on bad types"))bug!("unsize_ptr: called on bad types"),
267 }
268}
269
270pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
273 bx: &mut Bx,
274 src: PlaceRef<'tcx, Bx::Value>,
275 dst: PlaceRef<'tcx, Bx::Value>,
276) {
277 let src_ty = src.layout.ty;
278 let dst_ty = dst.layout.ty;
279 match (src_ty.kind(), dst_ty.kind()) {
280 (&ty::Pat(s, sp), &ty::Pat(d, dp))
281 if let (PatternKind::NotNull, PatternKind::NotNull) = (*sp, *dp) =>
282 {
283 let src = src.project_type(bx, s);
284 let dst = dst.project_type(bx, d);
285 coerce_unsized_into(bx, src, dst)
286 }
287 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
288 let (base, info) = match bx.load_operand(src).val {
289 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
290 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
291 OperandValue::Ref(..) | OperandValue::ZeroSized => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
292 };
293 OperandValue::Pair(base, info).store(bx, dst);
294 }
295
296 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
297 {
match (&def_a, &def_b) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(def_a, def_b); for i in def_a.variant(FIRST_VARIANT).fields.indices() {
300 let src_f = src.project_field(bx, i.as_usize());
301 let dst_f = dst.project_field(bx, i.as_usize());
302
303 if dst_f.layout.is_zst() {
304 continue;
306 }
307
308 if src_f.layout.ty == dst_f.layout.ty {
309 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
310 } else {
311 coerce_unsized_into(bx, src_f, dst_f);
312 }
313 }
314 }
315 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("coerce_unsized_into: invalid coercion {0:?} -> {1:?}",
src_ty, dst_ty))bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
316 }
317}
318
319pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
335 bx: &mut Bx,
336 lhs: Bx::Value,
337 mut rhs: Bx::Value,
338 is_unchecked: bool,
339) -> Bx::Value {
340 let mut rhs_llty = bx.cx().val_ty(rhs);
342 let mut lhs_llty = bx.cx().val_ty(lhs);
343
344 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
345 if !is_unchecked {
346 rhs = bx.and(rhs, mask);
347 }
348
349 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
350 rhs_llty = bx.cx().element_type(rhs_llty)
351 }
352 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
353 lhs_llty = bx.cx().element_type(lhs_llty)
354 }
355 let rhs_sz = bx.cx().int_width(rhs_llty);
356 let lhs_sz = bx.cx().int_width(lhs_llty);
357 if lhs_sz < rhs_sz {
358 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
359 } else if lhs_sz > rhs_sz {
360 if !(lhs_sz <= 256) {
::core::panicking::panic("assertion failed: lhs_sz <= 256")
};assert!(lhs_sz <= 256);
367 bx.zext(rhs, lhs_llty)
368 } else {
369 rhs
370 }
371}
372
373pub fn wants_wasm_eh(sess: &Session) -> bool {
377 sess.target.is_like_wasm
378}
379
380pub fn wants_msvc_seh(sess: &Session) -> bool {
386 sess.target.is_like_msvc
387}
388
389pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
393 wants_wasm_eh(sess) || wants_msvc_seh(sess)
394}
395
396pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
397 cx: &'a Bx::CodegenCx,
398 instance: Instance<'tcx>,
399) {
400 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/base.rs:403",
"rustc_codegen_ssa::base", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/base.rs"),
::tracing_core::__macro_support::Option::Some(403u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::base"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_instance({0})",
instance) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("codegen_instance({})", instance);
404
405 mir::codegen_mir::<Bx>(cx, instance);
406}
407
408pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: ItemId)
409where
410 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
411{
412 let item = cx.tcx().hir_item(item_id);
413 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
414 let operands: Vec<_> = asm
415 .operands
416 .iter()
417 .map(|(op, op_sp)| match *op {
418 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
419 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
420 Ok(const_value) => {
421 let ty =
422 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
423 let ConstValue::Scalar(scalar) = const_value else {
424 ::rustc_middle::util::bug::span_bug_fmt(*op_sp,
format_args!("expected Scalar for promoted asm const, but got {0:#?}",
const_value))span_bug!(
425 *op_sp,
426 "expected Scalar for promoted asm const, but got {:#?}",
427 const_value
428 )
429 };
430 GlobalAsmOperandRef::Const {
431 value: common::asm_const_ptr_clean(cx.tcx(), scalar),
432 ty,
433 }
434 }
435 Err(ErrorHandled::Reported { .. }) => {
436 GlobalAsmOperandRef::Const {
440 value: Scalar::from_u32(0),
441 ty: Ty::new_uint(cx.tcx(), UintTy::U32),
442 }
443 }
444 Err(ErrorHandled::TooGeneric(_)) => {
445 ::rustc_middle::util::bug::span_bug_fmt(*op_sp,
format_args!("asm const cannot be resolved; too generic"))span_bug!(*op_sp, "asm const cannot be resolved; too generic")
446 }
447 }
448 }
449 rustc_hir::InlineAsmOperand::SymFn { expr } => {
450 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
451 let instance = match ty.kind() {
452 &ty::FnDef(def_id, args) => Instance::expect_resolve(
453 cx.tcx(),
454 ty::TypingEnv::fully_monomorphized(),
455 def_id,
456 args.no_bound_vars().unwrap(),
457 expr.span,
458 ),
459 _ => ::rustc_middle::util::bug::span_bug_fmt(*op_sp,
format_args!("asm sym is not a function"))span_bug!(*op_sp, "asm sym is not a function"),
460 };
461
462 GlobalAsmOperandRef::Const {
463 value: Scalar::from_pointer(
464 cx.tcx().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT).into(),
465 cx,
466 ),
467 ty: Ty::new_fn_ptr(cx.tcx(), ty.fn_sig(cx.tcx())),
468 }
469 }
470 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
471 if cx.tcx().is_thread_local_static(def_id) {
472 GlobalAsmOperandRef::SymThreadLocalStatic { def_id }
473 } else {
474 GlobalAsmOperandRef::Const {
475 value: Scalar::from_pointer(
476 cx.tcx().reserve_and_set_static_alloc(def_id).into(),
477 cx,
478 ),
479 ty: cx.tcx().static_ptr_ty(def_id, cx.typing_env()),
480 }
481 }
482 }
483 rustc_hir::InlineAsmOperand::In { .. }
484 | rustc_hir::InlineAsmOperand::Out { .. }
485 | rustc_hir::InlineAsmOperand::InOut { .. }
486 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
487 | rustc_hir::InlineAsmOperand::Label { .. } => {
488 ::rustc_middle::util::bug::span_bug_fmt(*op_sp,
format_args!("invalid operand type for global_asm!"))span_bug!(*op_sp, "invalid operand type for global_asm!")
489 }
490 })
491 .collect();
492
493 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans, &[]);
494 } else {
495 ::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("Mismatch between hir::Item type and MonoItem type"))span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
496 }
497}
498
499pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
502 cx: &'a Bx::CodegenCx,
503 cgu: &CodegenUnit<'tcx>,
504) -> Option<Bx::Function> {
505 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
506 let main_is_local = main_def_id.is_local();
507 let instance = Instance::mono(cx.tcx(), main_def_id);
508
509 if main_is_local {
510 if !cgu.contains_item(&MonoItem::Fn(instance)) {
513 return None;
514 }
515 } else if !cgu.is_primary() {
516 return None;
518 }
519
520 let main_llfn = cx.get_fn_addr(instance, cx.sess().pointer_authentication_functions());
521
522 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
523 return Some(entry_fn);
524
525 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
526 cx: &'a Bx::CodegenCx,
527 rust_main: Bx::Value,
528 rust_main_def_id: DefId,
529 entry_type: EntryFnType,
530 ) -> Bx::Function {
531 let llfty = if cx.sess().target.os == Os::Uefi {
534 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
535 } else if cx.sess().target.main_needs_argc_argv {
536 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
537 } else {
538 cx.type_func(&[], cx.type_int())
539 };
540
541 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
542 let main_ret_ty = cx.tcx().normalize_erasing_regions(
548 cx.typing_env(),
549 Unnormalized::new_wip(main_ret_ty.no_bound_vars().unwrap()),
550 );
551
552 let Some(llfn) = cx.declare_c_main(llfty) else {
553 let span = cx.tcx().def_span(rust_main_def_id);
555 cx.tcx().dcx().emit_fatal(diagnostics::MultipleMainFunctions { span });
556 };
557
558 cx.set_frame_pointer_type(llfn);
560 cx.apply_target_cpu_attr(llfn);
561
562 let llbb = Bx::append_block(cx, llfn, "top");
563 let mut bx = Bx::build(cx, llbb);
564
565 bx.insert_reference_to_gdb_debug_scripts_section_global();
566
567 let isize_ty = cx.type_isize();
568 let ptr_ty = cx.type_ptr();
569 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
570
571 let EntryFnType::Main { sigpipe } = entry_type;
572 let (start_fn, start_ty, args, instance) = {
573 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
574 let start_instance = ty::Instance::expect_resolve(
575 cx.tcx(),
576 cx.typing_env(),
577 start_def_id,
578 cx.tcx().mk_args(&[main_ret_ty.into()]),
579 DUMMY_SP,
580 );
581 let start_fn =
582 cx.get_fn_addr(start_instance, cx.sess().pointer_authentication_functions());
583
584 let i8_ty = cx.type_i8();
585 let arg_sigpipe = bx.const_u8(sigpipe);
586
587 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
588 (
589 start_fn,
590 start_ty,
591 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[rust_main, arg_argc, arg_argv, arg_sigpipe]))vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
592 Some(start_instance),
593 )
594 };
595
596 let result = bx.call(start_ty, None, None, start_fn, &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 }
603
604 llfn
605 }
606}
607
608fn 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 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 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 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}
637
638pub 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}
660
661pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
665 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}
680
681pub(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_crate
692}
693
694pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
695 let mut methods = Vec::new();
696
697 if kind == AllocatorKind::Default {
698 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
699 }
700
701 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 }
711
712 methods
713}
714
715pub 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 tcx.dcx().emit_fatal(diagnostics::CpuRequired);
725 }
726
727 if let Some(target_cpu) = &tcx.sess.opts.cg.target_cpu
728 && tcx.sess.target.unsupported_cpus.contains(&target_cpu.into())
729 {
730 tcx.dcx().emit_fatal(diagnostics::CpuUnsupported { target_cpu: target_cpu.clone() });
732 }
733
734 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
735
736 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
739
740 if tcx.dep_graph.is_fully_enabled() {
746 for cgu in codegen_units {
747 tcx.ensure_ok().codegen_unit(cgu.name());
748 }
749 }
750
751 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();
755
756 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 None
763 };
764
765 let ongoing_codegen = start_async_codegen(backend.clone(), tcx, allocator_module);
766
767 let codegen_units: Vec<_> = {
779 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
780 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
781
782 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
783 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
784 };
785
786 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
788 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
789 });
790
791 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
792 for (i, cgu) in codegen_units.iter().enumerate() {
793 let cgu_reuse = cgu_reuse[i];
794 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
795 }
796 });
797
798 let mut total_codegen_time = Duration::new(0, 0);
799 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
800
801 let mut pre_compiled_cgus = if let Some(threads) = tcx.sess.opts.jobs.frontend {
812 tcx.sess.time("compile_first_CGU_batch", || {
813 let cgus: Vec<_> = cgu_reuse
815 .iter()
816 .enumerate()
817 .filter(|&(_, reuse)| reuse == &CguReuse::No)
818 .take(threads.get())
819 .collect();
820
821 let start_time = Instant::now();
823
824 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
825 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
826 (i, IntoDynSyncSend(module))
827 });
828
829 total_codegen_time += start_time.elapsed();
830
831 pre_compiled_cgus
832 })
833 } else {
834 FxHashMap::default()
835 };
836
837 for (i, cgu) in codegen_units.iter().enumerate() {
838 ongoing_codegen.wait_for_signal_to_codegen_item();
839 ongoing_codegen.check_for_errors(tcx.sess);
840
841 let cgu_reuse = cgu_reuse[i];
842
843 match cgu_reuse {
844 CguReuse::No => {
845 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
846 cgu.0
847 } else {
848 let start_time = Instant::now();
849 let module = backend.compile_codegen_unit(tcx, cgu.name());
850 total_codegen_time += start_time.elapsed();
851 module
852 };
853 tcx.dcx().abort_if_errors();
857
858 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
859 }
860 CguReuse::PreLto => {
861 submit_pre_lto_module_to_llvm(
862 tcx,
863 &ongoing_codegen.coordinator,
864 CachedModuleCodegen {
865 name: cgu.name().to_string(),
866 source: cgu.previous_work_product(tcx),
867 },
868 );
869 }
870 CguReuse::PostLto => {
871 submit_post_lto_module_to_llvm(
872 &ongoing_codegen.coordinator,
873 CachedModuleCodegen {
874 name: cgu.name().to_string(),
875 source: cgu.previous_work_product(tcx),
876 },
877 );
878 }
879 }
880 }
881
882 ongoing_codegen.codegen_finished(tcx);
883
884 if tcx.sess.opts.unstable_opts.time_passes {
887 let end_rss = get_resident_set_size();
888
889 print_time_passes_entry(
890 "codegen_to_LLVM_IR",
891 total_codegen_time,
892 start_rss.unwrap(),
893 end_rss,
894 tcx.sess.opts.unstable_opts.time_passes_format,
895 );
896 }
897
898 ongoing_codegen.check_for_errors(tcx.sess);
899 ongoing_codegen
900}
901
902pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
916 tcx: TyCtxt<'tcx>,
917 instance: Instance<'tcx>,
918) -> bool {
919 if let ty::InstanceKind::LlvmIntrinsic(_) = instance.def {
920 return false;
921 }
922
923 fn is_extern_call_to_local_crate<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
924 tcx.is_foreign_item(instance.def_id())
925 && tcx.exported_non_generic_symbols(LOCAL_CRATE).iter().any(|(sym, _info)| {
926 sym.symbol_name_for_local_instance(tcx) == tcx.symbol_name(instance)
927 })
928 }
929
930 let def_id = instance.def_id();
931 !def_id.is_local()
932 && tcx.is_compiler_builtins(LOCAL_CRATE)
933 && !tcx.should_codegen_locally(instance)
934 && !is_extern_call_to_local_crate(tcx, instance)
935}
936
937fn collect_eii_linkage(tcx: TyCtxt<'_>) -> Vec<EiiLinkageInfo> {
938 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for FoundImpl {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "FoundImpl",
"imp", &self.imp, "impl_crate", &&self.impl_crate)
}
}Debug)]
939 struct FoundImpl {
940 imp: EiiImpl,
941 impl_crate: CrateNum,
942 }
943
944 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for FoundEii {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "FoundEii",
"decl", &self.decl, "impls", &&self.impls)
}
}Debug)]
945 struct FoundEii {
946 decl: EiiDecl,
947 impls: FxIndexMap<DefId, FoundImpl>,
948 }
949
950 let mut eiis = FxIndexMap::<DefId, FoundEii>::default();
951
952 for &cnum in tcx.crates(()).iter().chain(iter::once(&LOCAL_CRATE)) {
953 for (&did, &(decl, ref impls)) in tcx.externally_implementable_items(cnum) {
954 eiis.entry(did)
955 .or_insert_with(|| FoundEii { decl, impls: Default::default() })
956 .impls
957 .extend(
958 impls
959 .into_iter()
960 .map(|(&did, &imp)| (did, FoundImpl { imp, impl_crate: cnum })),
961 );
962 }
963 }
964
965 eiis.into_iter()
966 .filter_map(|(_, FoundEii { decl, impls })| {
967 let mut explicit_impls = Vec::new();
968 let mut default_impl = None;
969
970 for (impl_did, FoundImpl { imp, impl_crate }) in impls {
971 let impl_info = EiiLinkageImplInfo { span: tcx.def_span(impl_did), impl_crate };
972 if imp.is_default {
973 default_impl = Some(impl_info);
974 } else {
975 explicit_impls.push(impl_info);
976 }
977 }
978
979 if let Some(default_impl) = default_impl {
982 Some(EiiLinkageInfo {
983 name: decl.name.name,
984 impls: explicit_impls,
985 default_impl: Some(default_impl),
986 })
987 } else {
988 None
989 }
990 })
991 .collect()
992}
993
994fn eii_linkage_needed(dependency_formats: &Dependencies) -> bool {
995 dependency_formats.values().any(|formats| {
996 formats
997 .iter()
998 .any(|&linkage| #[allow(non_exhaustive_omitted_patterns)] match linkage {
Linkage::Dynamic | Linkage::IncludedFromDylib => true,
_ => false,
}matches!(linkage, Linkage::Dynamic | Linkage::IncludedFromDylib))
999 })
1000}
1001
1002impl CrateInfo {
1003 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
1004 let crate_types = tcx.crate_types().to_vec();
1005 let exported_symbols = crate_types
1006 .iter()
1007 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
1008 .collect();
1009 let linked_symbols =
1010 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
1011 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
1012 let windows_subsystem = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(WindowsSubsystem(kind)) =>
{
break 'done Some(*kind);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(tcx, crate, WindowsSubsystem(kind) => *kind);
1013 let dependency_formats = Arc::clone(tcx.dependency_formats(()));
1014 let eii_linkage = if eii_linkage_needed(&dependency_formats) {
1015 collect_eii_linkage(tcx)
1016 } else {
1017 Vec::new()
1018 };
1019
1020 let mut compiler_builtins = None;
1029 let mut used_crates: Vec<_> = tcx
1030 .postorder_cnums(())
1031 .iter()
1032 .rev()
1033 .copied()
1034 .filter(|&cnum| {
1035 let link = !tcx.crate_dep_kind(cnum).macros_only();
1036 if link && tcx.is_compiler_builtins(cnum) {
1037 compiler_builtins = Some(cnum);
1038 return false;
1039 }
1040 link
1041 })
1042 .collect();
1043 used_crates.extend(compiler_builtins);
1045
1046 let crates = tcx.crates(());
1047 let n_crates = crates.len();
1048 let mut info = CrateInfo {
1049 target_cpu,
1050 target_features: tcx.global_backend_features(()).clone(),
1051 crate_types,
1052 exported_symbols,
1053 linked_symbols,
1054 local_crate_name,
1055 compiler_builtins,
1056 profiler_runtime: None,
1057 is_no_builtins: Default::default(),
1058 native_libraries: Default::default(),
1059 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
1060 crate_name: UnordMap::with_capacity(n_crates),
1061 used_crates,
1062 used_crate_source: UnordMap::with_capacity(n_crates),
1063 dependency_formats,
1064 eii_linkage,
1065 windows_subsystem,
1066 natvis_debugger_visualizers: Default::default(),
1067 lint_level_specs: CodegenLintLevelSpecs::from_tcx(tcx),
1068 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
1069 symbol_rename_suffix: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(".rs{0:x}",
tcx.stable_crate_id(LOCAL_CRATE)))
})format!(".rs{:x}", tcx.stable_crate_id(LOCAL_CRATE)),
1070 each_linked_rlib_file_for_lto: Default::default(),
1071 exported_symbols_for_lto: Default::default(),
1072 };
1073
1074 info.native_libraries.reserve(n_crates);
1075
1076 for &cnum in crates.iter() {
1077 info.native_libraries
1078 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
1079 info.crate_name.insert(cnum, tcx.crate_name(cnum));
1080
1081 let used_crate_source = tcx.used_crate_source(cnum);
1082 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
1083 if tcx.is_profiler_runtime(cnum) {
1084 info.profiler_runtime = Some(cnum);
1085 }
1086 if tcx.is_no_builtins(cnum) {
1087 info.is_no_builtins.insert(cnum);
1088 }
1089 }
1090
1091 let target = &tcx.sess.target;
1100 if !are_upstream_rust_objects_already_included(tcx.sess) {
1101 let add_prefix = match (target.is_like_windows, &target.arch) {
1102 (true, Arch::X86) => |name: String, _: SymbolExportKind| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_{0}", name))
})format!("_{name}"),
1103 (true, Arch::Arm64EC) => {
1104 |name: String, export_kind: SymbolExportKind| match export_kind {
1106 SymbolExportKind::Text => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0}", name))
})format!("#{name}"),
1107 _ => name,
1108 }
1109 }
1110 _ => |name: String, _: SymbolExportKind| name,
1111 };
1112 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
1113 .used_crates
1114 .iter()
1115 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1116 .filter(|l| l.is_weak())
1117 .filter_map(|&l| {
1118 let name = l.link_name()?;
1119 let export_kind = match l.target() {
1120 Target::ForeignFn | Target::Fn => SymbolExportKind::Text,
1121 Target::Static => SymbolExportKind::Data,
1122 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Don\'t know what the export kind is for lang item of kind {0:?}",
l.target()))bug!(
1123 "Don't know what the export kind is for lang item of kind {:?}",
1124 l.target()
1125 ),
1126 };
1127 lang_items::required(tcx, l).then_some((name, export_kind))
1128 })
1129 .collect();
1130
1131 #[allow(rustc::potential_query_instability)]
1134 info.linked_symbols
1135 .iter_mut()
1136 .filter(|(crate_type, _)| {
1137 !#[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib)
1138 })
1139 .for_each(|(_, linked_symbols)| {
1140 let mut symbols = missing_weak_lang_items
1141 .iter()
1142 .map(|(item, export_kind)| {
1143 (
1144 add_prefix(
1145 mangle_internal_symbol(tcx, item.as_str()),
1146 *export_kind,
1147 ),
1148 *export_kind,
1149 )
1150 })
1151 .collect::<Vec<_>>();
1152 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1153 linked_symbols.extend(symbols);
1154 });
1155 }
1156
1157 let mut each_linked_rlib_for_lto = Vec::new();
1158 let mut each_linked_rlib_file_for_lto = Vec::new();
1159 if tcx.sess.lto() != config::Lto::No && tcx.sess.lto() != config::Lto::ThinLocal {
1160 drop(crate::back::link::each_linked_rlib(&info, None, &mut |cnum, path| {
1161 if crate::back::link::ignored_for_lto(tcx.sess, &info, cnum) {
1162 return;
1163 }
1164
1165 each_linked_rlib_for_lto.push(cnum);
1166 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1167 }));
1168 }
1169 info.each_linked_rlib_file_for_lto = each_linked_rlib_file_for_lto;
1170
1171 info.exported_symbols_for_lto =
1174 crate::back::lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto);
1175
1176 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1177 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1178 true
1181 }
1182 CrateType::ProcMacro => {
1183 false
1187 }
1188 CrateType::StaticLib | CrateType::Rlib => {
1189 false
1192 }
1193 });
1194
1195 if target.is_like_msvc && embed_visualizers {
1196 info.natvis_debugger_visualizers =
1197 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1198 }
1199
1200 info
1201 }
1202}
1203
1204pub(crate) fn provide(providers: &mut Providers) {
1205 providers.backend_optimization_level = |tcx, cratenum| {
1206 let for_speed = match tcx.sess.opts.optimize {
1207 config::OptLevel::No => return config::OptLevel::No,
1214 config::OptLevel::Less => return config::OptLevel::Less,
1216 config::OptLevel::More => return config::OptLevel::More,
1217 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1218 config::OptLevel::Size => config::OptLevel::More,
1221 config::OptLevel::SizeMin => config::OptLevel::More,
1222 };
1223
1224 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1225
1226 let any_for_speed = defids.items().any(|id| {
1227 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1228 #[allow(non_exhaustive_omitted_patterns)] match optimize {
OptimizeAttr::Speed => true,
_ => false,
}matches!(optimize, OptimizeAttr::Speed)
1229 });
1230
1231 if any_for_speed {
1232 return for_speed;
1233 }
1234
1235 tcx.sess.opts.optimize
1236 };
1237}
1238
1239pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1240 if !tcx.dep_graph.is_fully_enabled()
1241 || tcx.sess.opts.unstable_opts.disable_incr_comp_backend_caching
1242 {
1243 return CguReuse::No;
1244 }
1245
1246 let work_product_id = &cgu.work_product_id();
1247 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1248 return CguReuse::No;
1251 }
1252
1253 let dep_node = cgu.codegen_dep_node(tcx);
1260 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
1261 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("CompileCodegenUnit dep-node for CGU `{0}` already exists before marking.",
cgu.name()))
})format!(
1262 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1263 cgu.name()
1264 )
1265 });
1266
1267 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
1268 match compute_per_cgu_lto_type(
1272 &tcx.sess.lto(),
1273 tcx.sess.opts.cg.linker_plugin_lto.enabled(),
1274 tcx.crate_types(),
1275 ) {
1276 ComputedLtoType::No => CguReuse::PostLto,
1277 _ => CguReuse::PreLto,
1278 }
1279 } else {
1280 CguReuse::No
1281 }
1282}