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_session::config::{self, EntryFnType};
32use rustc_span::{DUMMY_SP, Symbol, bug, span_bug};
33use rustc_structures::CrateType;
34use rustc_symbol_mangling::mangle_internal_symbol;
35use rustc_target::spec::{Arch, Os, Target as TargetSpec};
36use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
37use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
38use tracing::{debug, info};
39
40use crate::assert_module_sources::CguReuse;
41use crate::back::link::are_upstream_rust_objects_already_included;
42use crate::back::write::{
43 ComputedLtoType, ModuleConfig, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
44 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
45};
46use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
47use crate::meth::load_vtable;
48use crate::mir::operand::OperandValue;
49use crate::mir::place::PlaceRef;
50use crate::traits::*;
51use crate::{
52 CachedModuleCodegen, CodegenLintLevelSpecs, CrateInfo, EiiLinkageImplInfo, EiiLinkageInfo,
53 ModuleCodegen, ModuleKind, diagnostics, meth, mir,
54};
55
56pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
57 match (op, signed) {
58 (BinOp::Eq, _) => IntPredicate::IntEQ,
59 (BinOp::Ne, _) => IntPredicate::IntNE,
60 (BinOp::Lt, true) => IntPredicate::IntSLT,
61 (BinOp::Lt, false) => IntPredicate::IntULT,
62 (BinOp::Le, true) => IntPredicate::IntSLE,
63 (BinOp::Le, false) => IntPredicate::IntULE,
64 (BinOp::Gt, true) => IntPredicate::IntSGT,
65 (BinOp::Gt, false) => IntPredicate::IntUGT,
66 (BinOp::Ge, true) => IntPredicate::IntSGE,
67 (BinOp::Ge, false) => IntPredicate::IntUGE,
68 op => bug_impl(None,
format_args!("bin_op_to_icmp_predicate: expected comparison operator, found {0:?}",
op), Location::caller())bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
69 }
70}
71
72pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
73 match op {
74 BinOp::Eq => RealPredicate::RealOEQ,
75 BinOp::Ne => RealPredicate::RealUNE,
76 BinOp::Lt => RealPredicate::RealOLT,
77 BinOp::Le => RealPredicate::RealOLE,
78 BinOp::Gt => RealPredicate::RealOGT,
79 BinOp::Ge => RealPredicate::RealOGE,
80 op => bug_impl(None,
format_args!("bin_op_to_fcmp_predicate: expected comparison operator, found {0:?}",
op), Location::caller())bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
81 }
82}
83
84pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
85 bx: &mut Bx,
86 lhs: Bx::Value,
87 rhs: Bx::Value,
88 t: Ty<'tcx>,
89 ret_ty: Bx::Type,
90 op: BinOp,
91) -> Bx::Value {
92 let signed = match t.kind() {
93 ty::Float(_) => {
94 let cmp = bin_op_to_fcmp_predicate(op);
95 let cmp = bx.fcmp(cmp, lhs, rhs);
96 return bx.sext(cmp, ret_ty);
97 }
98 ty::Uint(_) => false,
99 ty::Int(_) => true,
100 _ => bug_impl(None, format_args!("compare_simd_types: invalid SIMD type"),
Location::caller())bug!("compare_simd_types: invalid SIMD type"),
101 };
102
103 let cmp = bin_op_to_icmp_predicate(op, signed);
104 let cmp = bx.icmp(cmp, lhs, rhs);
105 bx.sext(cmp, ret_ty)
110}
111
112pub fn validate_trivial_unsize<'tcx>(
121 tcx: TyCtxt<'tcx>,
122 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
123 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
124) -> bool {
125 match (source_data.principal(), target_data.principal()) {
126 (Some(hr_source_principal), Some(hr_target_principal)) => {
127 let (infcx, param_env) =
128 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
129 let universe = infcx.universe();
130 let ocx = ObligationCtxt::new(&infcx);
131 infcx.enter_forall(hr_target_principal, |target_principal| {
132 let source_principal = infcx.instantiate_binder_with_fresh_vars(
133 DUMMY_SP,
134 BoundRegionConversionTime::HigherRankedType,
135 hr_source_principal,
136 );
137 let Ok(()) = ocx.eq(
138 &ObligationCause::dummy(),
139 param_env,
140 target_principal,
141 source_principal,
142 ) else {
143 return false;
144 };
145 if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
146 return false;
147 }
148 infcx.leak_check(universe, None).is_ok()
149 })
150 }
151 (_, None) => true,
152 _ => false,
153 }
154}
155
156fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
162 bx: &mut Bx,
163 source: Ty<'tcx>,
164 target: Ty<'tcx>,
165 old_info: Option<Bx::Value>,
166) -> Bx::Value {
167 let cx = bx.cx();
168 let (source, target) =
169 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
170 match (source.kind(), target.kind()) {
171 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
172 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
173 ),
174 (&ty::Dynamic(data_a, _), &ty::Dynamic(data_b, _)) => {
175 let old_info =
176 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
177 let b_principal_def_id = data_b.principal_def_id();
178 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
179 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!(
188 validate_trivial_unsize(cx.tcx(), data_a, data_b),
189 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
190 );
191
192 return old_info;
198 }
199
200 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
203
204 if let Some(entry_idx) = vptr_entry_idx {
205 let ptr_size = bx.data_layout().pointer_size();
206 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
207 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
208 } else {
209 old_info
210 }
211 }
212 (_, ty::Dynamic(data, _)) => meth::get_vtable(
213 cx,
214 source,
215 data.principal()
216 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
217 ),
218 _ => bug_impl(None,
format_args!("unsized_info: invalid unsizing {0:?} -> {1:?}", source,
target), Location::caller())bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
219 }
220}
221
222pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
224 bx: &mut Bx,
225 src: Bx::Value,
226 src_ty: Ty<'tcx>,
227 dst_ty: Ty<'tcx>,
228 old_info: Option<Bx::Value>,
229) -> (Bx::Value, Bx::Value) {
230 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/base.rs:230",
"rustc_codegen_ssa::base", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/base.rs"),
::tracing_core::__macro_support::Option::Some(230u32),
::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);
231 match (src_ty.kind(), dst_ty.kind()) {
232 (&ty::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),
233 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
234 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
235 {
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());
236 (src, unsized_info(bx, a, b, old_info))
237 }
238 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
239 {
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);
241 let dst_layout = bx.cx().layout_of(dst_ty);
242 if src_ty == dst_ty {
243 return (src, old_info.unwrap());
244 }
245 let mut result = None;
246 for i in 0..src_layout.fields.count() {
247 let src_f = src_layout.field(bx.cx(), i);
248 if src_f.is_1zst() {
249 continue;
251 }
252
253 {
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);
254 {
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);
255 {
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);
256
257 let dst_f = dst_layout.field(bx.cx(), i);
258 {
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);
259 {
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);
260 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
261 }
262 result.unwrap()
263 }
264 _ => bug_impl(None, format_args!("unsize_ptr: called on bad types"),
Location::caller())bug!("unsize_ptr: called on bad types"),
265 }
266}
267
268pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
271 bx: &mut Bx,
272 src: PlaceRef<'tcx, Bx::Value>,
273 dst: PlaceRef<'tcx, Bx::Value>,
274) {
275 let src_ty = src.layout.ty;
276 let dst_ty = dst.layout.ty;
277 match (src_ty.kind(), dst_ty.kind()) {
278 (&ty::Pat(s, sp), &ty::Pat(d, dp))
279 if let (PatternKind::NotNull, PatternKind::NotNull) = (*sp, *dp) =>
280 {
281 let src = src.project_type(bx, s);
282 let dst = dst.project_type(bx, d);
283 coerce_unsized_into(bx, src, dst)
284 }
285 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
286 let (base, info) = match bx.load_operand(src).val {
287 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
288 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
289 OperandValue::Ref(..) | OperandValue::ZeroSized => bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!(),
290 };
291 OperandValue::Pair(base, info).store(bx, dst);
292 }
293
294 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
295 {
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() {
298 let src_f = src.project_field(bx, i.as_usize());
299 let dst_f = dst.project_field(bx, i.as_usize());
300
301 if dst_f.layout.is_zst() {
302 continue;
304 }
305
306 if src_f.layout.ty == dst_f.layout.ty {
307 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
308 } else {
309 coerce_unsized_into(bx, src_f, dst_f);
310 }
311 }
312 }
313 _ => bug_impl(None,
format_args!("coerce_unsized_into: invalid coercion {0:?} -> {1:?}",
src_ty, dst_ty), Location::caller())bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
314 }
315}
316
317pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
333 bx: &mut Bx,
334 lhs: Bx::Value,
335 mut rhs: Bx::Value,
336 is_unchecked: bool,
337) -> Bx::Value {
338 let mut rhs_llty = bx.cx().val_ty(rhs);
340 let mut lhs_llty = bx.cx().val_ty(lhs);
341
342 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
343 if !is_unchecked {
344 rhs = bx.and(rhs, mask);
345 }
346
347 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
348 rhs_llty = bx.cx().element_type(rhs_llty)
349 }
350 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
351 lhs_llty = bx.cx().element_type(lhs_llty)
352 }
353 let rhs_sz = bx.cx().int_width(rhs_llty);
354 let lhs_sz = bx.cx().int_width(lhs_llty);
355 if lhs_sz < rhs_sz {
356 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
357 } else if lhs_sz > rhs_sz {
358 if !(lhs_sz <= 256) {
::core::panicking::panic("assertion failed: lhs_sz <= 256")
};assert!(lhs_sz <= 256);
365 bx.zext(rhs, lhs_llty)
366 } else {
367 rhs
368 }
369}
370
371pub fn wants_wasm_eh(target: &TargetSpec) -> bool {
375 target.is_like_wasm
376}
377
378pub fn wants_msvc_seh(target: &TargetSpec) -> bool {
384 target.is_like_msvc
385}
386
387pub(crate) fn wants_new_eh_instructions(target: &TargetSpec) -> bool {
391 wants_wasm_eh(target) || wants_msvc_seh(target)
392}
393
394pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
395 cx: &'a Bx::CodegenCx,
396 instance: Instance<'tcx>,
397) {
398 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/base.rs:401",
"rustc_codegen_ssa::base", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/base.rs"),
::tracing_core::__macro_support::Option::Some(401u32),
::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);
402
403 mir::codegen_mir::<Bx>(cx, instance);
404}
405
406pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: ItemId)
407where
408 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
409{
410 let item = cx.tcx().hir_item(item_id);
411 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
412 let operands: Vec<_> = asm
413 .operands
414 .iter()
415 .map(|(op, op_sp)| match *op {
416 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
417 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
418 Ok(const_value) => {
419 let ty =
420 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
421 let ConstValue::Scalar(scalar) = const_value else {
422 bug_impl(Some(*op_sp),
format_args!("expected Scalar for promoted asm const, but got {0:#?}",
const_value), Location::caller())span_bug!(
423 *op_sp,
424 "expected Scalar for promoted asm const, but got {:#?}",
425 const_value
426 )
427 };
428 GlobalAsmOperandRef::Const {
429 value: common::asm_const_ptr_clean(cx.tcx(), scalar),
430 ty,
431 }
432 }
433 Err(ErrorHandled::Reported { .. }) => {
434 GlobalAsmOperandRef::Const {
438 value: Scalar::from_u32(0),
439 ty: Ty::new_uint(cx.tcx(), UintTy::U32),
440 }
441 }
442 Err(ErrorHandled::TooGeneric(_)) => {
443 bug_impl(Some(*op_sp),
format_args!("asm const cannot be resolved; too generic"),
Location::caller())span_bug!(*op_sp, "asm const cannot be resolved; too generic")
444 }
445 }
446 }
447 rustc_hir::InlineAsmOperand::SymFn { expr } => {
448 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
449 let instance = match ty.kind() {
450 &ty::FnDef(def_id, args) => Instance::expect_resolve(
451 cx.tcx(),
452 ty::TypingEnv::fully_monomorphized(),
453 def_id,
454 args.no_bound_vars().unwrap(),
455 expr.span,
456 ),
457 _ => bug_impl(Some(*op_sp), format_args!("asm sym is not a function"),
Location::caller())span_bug!(*op_sp, "asm sym is not a function"),
458 };
459
460 GlobalAsmOperandRef::Const {
461 value: Scalar::from_pointer(
462 cx.tcx().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT).into(),
463 cx,
464 ),
465 ty: Ty::new_fn_ptr(cx.tcx(), ty.fn_sig(cx.tcx())),
466 }
467 }
468 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
469 if cx.tcx().is_thread_local_static(def_id) {
470 GlobalAsmOperandRef::SymThreadLocalStatic { def_id }
471 } else {
472 GlobalAsmOperandRef::Const {
473 value: Scalar::from_pointer(
474 cx.tcx().reserve_and_set_static_alloc(def_id).into(),
475 cx,
476 ),
477 ty: cx.tcx().static_ptr_ty(def_id, cx.typing_env()),
478 }
479 }
480 }
481 rustc_hir::InlineAsmOperand::In { .. }
482 | rustc_hir::InlineAsmOperand::Out { .. }
483 | rustc_hir::InlineAsmOperand::InOut { .. }
484 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
485 | rustc_hir::InlineAsmOperand::Label { .. } => {
486 bug_impl(Some(*op_sp), format_args!("invalid operand type for global_asm!"),
Location::caller())span_bug!(*op_sp, "invalid operand type for global_asm!")
487 }
488 })
489 .collect();
490
491 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans, &[]);
492 } else {
493 bug_impl(Some(item.span),
format_args!("Mismatch between hir::Item type and MonoItem type"),
Location::caller())span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
494 }
495}
496
497pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
500 cx: &'a Bx::CodegenCx,
501 cgu: &CodegenUnit<'tcx>,
502) -> Option<Bx::Function> {
503 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
504 let main_is_local = main_def_id.is_local();
505 let instance = Instance::mono(cx.tcx(), main_def_id);
506
507 if main_is_local {
508 if !cgu.contains_item(&MonoItem::Fn(instance)) {
511 return None;
512 }
513 } else if !cgu.is_primary() {
514 return None;
516 }
517
518 let main_llfn = cx.get_fn_addr(instance, cx.sess().pointer_authentication_functions());
519
520 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
521 return Some(entry_fn);
522
523 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
524 cx: &'a Bx::CodegenCx,
525 rust_main: Bx::Value,
526 rust_main_def_id: DefId,
527 entry_type: EntryFnType,
528 ) -> Bx::Function {
529 let llfty = if cx.sess().target.os == Os::Uefi {
532 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
533 } else if cx.sess().target.main_needs_argc_argv {
534 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
535 } else {
536 cx.type_func(&[], cx.type_int())
537 };
538
539 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
540 let main_ret_ty = cx.tcx().normalize_erasing_regions(
546 cx.typing_env(),
547 Unnormalized::new_wip(main_ret_ty.no_bound_vars().unwrap()),
548 );
549
550 let Some(llfn) = cx.declare_c_main(llfty) else {
551 let span = cx.tcx().def_span(rust_main_def_id);
553 cx.tcx().dcx().emit_fatal(diagnostics::MultipleMainFunctions { span });
554 };
555
556 cx.set_frame_pointer_type(llfn);
558 cx.apply_target_cpu_attr(llfn);
559
560 let llbb = Bx::append_block(cx, llfn, "top");
561 let mut bx = Bx::build(cx, llbb);
562
563 bx.insert_reference_to_gdb_debug_scripts_section_global();
564
565 let isize_ty = cx.type_isize();
566 let ptr_ty = cx.type_ptr();
567 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
568
569 let EntryFnType::Main { sigpipe } = entry_type;
570 let (start_fn, start_ty, args, instance) = {
571 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
572 let start_instance = ty::Instance::expect_resolve(
573 cx.tcx(),
574 cx.typing_env(),
575 start_def_id,
576 cx.tcx().mk_args(&[main_ret_ty.into()]),
577 DUMMY_SP,
578 );
579 let start_fn =
580 cx.get_fn_addr(start_instance, cx.sess().pointer_authentication_functions());
581
582 let i8_ty = cx.type_i8();
583 let arg_sigpipe = bx.const_u8(sigpipe);
584
585 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
586 (
587 start_fn,
588 start_ty,
589 ::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],
590 Some(start_instance),
591 )
592 };
593
594 let result =
595 bx.call(start_ty, None, None, start_fn, ReturnSlot::Direct, &args, None, instance);
596 if cx.sess().target.os == Os::Uefi {
597 bx.ret(result);
598 } else {
599 let cast = bx.intcast(result, cx.type_int(), true);
600 bx.ret(cast);
601 }
602
603 llfn
604 }
605}
606
607fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
610 if bx.cx().sess().target.os == Os::Uefi {
611 let param_handle = bx.get_param(0);
613 let param_system_table = bx.get_param(1);
614 let ptr_size = bx.tcx().data_layout.pointer_size();
615 let ptr_align = bx.tcx().data_layout.pointer_align().abi;
616 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
617 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
618 bx.store(param_handle, arg_argv, ptr_align);
619 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
620 bx.store(param_system_table, arg_argv_el1, ptr_align);
621 (arg_argc, arg_argv)
622 } else if bx.cx().sess().target.main_needs_argc_argv {
623 let param_argc = bx.get_param(0);
625 let param_argv = bx.get_param(1);
626 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
627 let arg_argv = param_argv;
628 (arg_argc, arg_argv)
629 } else {
630 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
632 let arg_argv = bx.const_null(bx.cx().type_ptr());
633 (arg_argc, arg_argv)
634 }
635}
636
637pub fn collect_debugger_visualizers_transitive(
641 tcx: TyCtxt<'_>,
642 visualizer_type: DebuggerVisualizerType,
643) -> BTreeSet<DebuggerVisualizerFile> {
644 tcx.debugger_visualizers(LOCAL_CRATE)
645 .iter()
646 .chain(
647 tcx.crates(())
648 .iter()
649 .filter(|&cnum| {
650 let used_crate_source = tcx.used_crate_source(*cnum);
651 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
652 })
653 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
654 )
655 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
656 .cloned()
657 .collect::<BTreeSet<_>>()
658}
659
660pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
664 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
674 use rustc_middle::middle::dependency_format::Linkage;
675 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
676 });
677 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
678}
679
680pub(crate) fn needs_allocator_shim_for_linking(
684 dependency_formats: &Dependencies,
685 crate_type: CrateType,
686) -> bool {
687 use rustc_middle::middle::dependency_format::Linkage;
688 let any_dynamic_crate =
689 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
690 !any_dynamic_crate
691}
692
693pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
694 let mut methods = Vec::new();
695
696 if kind == AllocatorKind::Default {
697 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
698 }
699
700 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
703 methods.push(AllocatorMethod {
704 name: ALLOC_ERROR_HANDLER,
705 special: None,
706 inputs: &[AllocatorMethodInput { name: "layout", ty: AllocatorTy::Layout }],
707 output: AllocatorTy::Never,
708 });
709 }
710
711 methods
712}
713
714pub fn codegen_crate<
715 B: ExtraBackendMethods<Module = M> + WriteBackendMethods<Module = M>,
716 M: Send,
717>(
718 backend: B,
719 tcx: TyCtxt<'_>,
720) -> OngoingCodegen<B> {
721 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
722 tcx.dcx().emit_fatal(diagnostics::CpuRequired);
724 }
725
726 if let Some(target_cpu) = &tcx.sess.opts.cg.target_cpu
727 && tcx.sess.target.unsupported_cpus.contains(&target_cpu.into())
728 {
729 tcx.dcx().emit_fatal(diagnostics::CpuUnsupported { target_cpu: target_cpu.clone() });
731 }
732
733 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
734
735 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
738
739 if tcx.dep_graph.is_fully_enabled() {
745 for cgu in codegen_units {
746 tcx.ensure_ok().codegen_unit(cgu.name());
747 }
748 }
749
750 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
752 let llmod_id =
753 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
754
755 tcx.sess.time("write_allocator_module", || {
756 let module =
757 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
758 Some(ModuleCodegen::new_allocator(llmod_id, module))
759 })
760 } else {
761 None
762 };
763
764 let no_builtins = {
'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(NoBuiltins) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, NoBuiltins);
765 let regular_module_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
766 let bitcode_needed = regular_module_config.bitcode_needed();
767 let allocator_module_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
768
769 let ongoing_codegen = start_async_codegen(
770 backend.clone(),
771 tcx,
772 Arc::new(regular_module_config),
773 Arc::new(allocator_module_config),
774 allocator_module,
775 );
776
777 let codegen_units: Vec<_> = {
789 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
790 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
791
792 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
793 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
794 };
795
796 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
798 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
799 });
800
801 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
802 for (i, cgu) in codegen_units.iter().enumerate() {
803 let cgu_reuse = cgu_reuse[i];
804 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
805 }
806 });
807
808 let mut total_codegen_time = Duration::new(0, 0);
809 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
810
811 let mut pre_compiled_cgus = if let Some(threads) = tcx.sess.opts.jobs.frontend {
822 tcx.sess.time("compile_first_CGU_batch", || {
823 let cgus: Vec<_> = cgu_reuse
825 .iter()
826 .enumerate()
827 .filter(|&(_, reuse)| reuse == &CguReuse::No)
828 .take(threads.get())
829 .collect();
830
831 let start_time = Instant::now();
833
834 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
835 let module =
836 backend.compile_codegen_unit(tcx, codegen_units[i].name(), bitcode_needed);
837 (i, IntoDynSyncSend(module))
838 });
839
840 total_codegen_time += start_time.elapsed();
841
842 pre_compiled_cgus
843 })
844 } else {
845 FxHashMap::default()
846 };
847
848 for (i, cgu) in codegen_units.iter().enumerate() {
849 ongoing_codegen.wait_for_signal_to_codegen_item();
850 ongoing_codegen.check_for_errors(tcx.sess);
851
852 let cgu_reuse = cgu_reuse[i];
853
854 match cgu_reuse {
855 CguReuse::No => {
856 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
857 cgu.0
858 } else {
859 let start_time = Instant::now();
860 let module = backend.compile_codegen_unit(tcx, cgu.name(), bitcode_needed);
861 total_codegen_time += start_time.elapsed();
862 module
863 };
864 tcx.dcx().abort_if_errors();
868
869 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
870 }
871 CguReuse::PreLto => {
872 submit_pre_lto_module_to_llvm(
873 tcx,
874 &ongoing_codegen.coordinator,
875 CachedModuleCodegen {
876 name: cgu.name().to_string(),
877 source: cgu.previous_work_product(tcx),
878 },
879 );
880 }
881 CguReuse::PostLto => {
882 submit_post_lto_module_to_llvm(
883 &ongoing_codegen.coordinator,
884 CachedModuleCodegen {
885 name: cgu.name().to_string(),
886 source: cgu.previous_work_product(tcx),
887 },
888 );
889 }
890 }
891 }
892
893 ongoing_codegen.codegen_finished(tcx);
894
895 if tcx.sess.opts.unstable_opts.time_passes {
898 let end_rss = get_resident_set_size();
899
900 print_time_passes_entry(
901 "codegen_to_LLVM_IR",
902 total_codegen_time,
903 start_rss.unwrap(),
904 end_rss,
905 tcx.sess.opts.unstable_opts.time_passes_format,
906 );
907 }
908
909 ongoing_codegen.check_for_errors(tcx.sess);
910 ongoing_codegen
911}
912
913pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
927 tcx: TyCtxt<'tcx>,
928 instance: Instance<'tcx>,
929) -> bool {
930 if let ty::InstanceKind::LlvmIntrinsic(_) = instance.def {
931 return false;
932 }
933
934 fn is_extern_call_to_local_crate<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
935 tcx.is_foreign_item(instance.def_id())
936 && tcx.exported_non_generic_symbols(LOCAL_CRATE).iter().any(|(sym, _info)| {
937 sym.symbol_name_for_local_instance(tcx) == tcx.symbol_name(instance)
938 })
939 }
940
941 let def_id = instance.def_id();
942 !def_id.is_local()
943 && tcx.is_compiler_builtins(LOCAL_CRATE)
944 && !tcx.should_codegen_locally(instance)
945 && !is_extern_call_to_local_crate(tcx, instance)
946}
947
948fn collect_eii_linkage(tcx: TyCtxt<'_>) -> Vec<EiiLinkageInfo> {
949 #[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)]
950 struct FoundImpl {
951 imp: EiiImpl,
952 impl_crate: CrateNum,
953 }
954
955 #[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)]
956 struct FoundEii {
957 decl: EiiDecl,
958 impls: FxIndexMap<DefId, FoundImpl>,
959 }
960
961 let mut eiis = FxIndexMap::<DefId, FoundEii>::default();
962
963 for &cnum in tcx.crates(()).iter().chain(iter::once(&LOCAL_CRATE)) {
964 for (&did, &(decl, ref impls)) in tcx.externally_implementable_items(cnum) {
965 eiis.entry(did)
966 .or_insert_with(|| FoundEii { decl, impls: Default::default() })
967 .impls
968 .extend(
969 impls
970 .into_iter()
971 .map(|(&did, &imp)| (did, FoundImpl { imp, impl_crate: cnum })),
972 );
973 }
974 }
975
976 eiis.into_iter()
977 .filter_map(|(_, FoundEii { decl, impls })| {
978 let mut explicit_impls = Vec::new();
979 let mut default_impl = None;
980
981 for (impl_did, FoundImpl { imp, impl_crate }) in impls {
982 let impl_info = EiiLinkageImplInfo { span: tcx.def_span(impl_did), impl_crate };
983 if imp.is_default {
984 default_impl = Some(impl_info);
985 } else {
986 explicit_impls.push(impl_info);
987 }
988 }
989
990 if let Some(default_impl) = default_impl {
993 Some(EiiLinkageInfo {
994 name: decl.name.name,
995 impls: explicit_impls,
996 default_impl: Some(default_impl),
997 })
998 } else {
999 None
1000 }
1001 })
1002 .collect()
1003}
1004
1005fn eii_linkage_needed(dependency_formats: &Dependencies) -> bool {
1006 dependency_formats.values().any(|formats| {
1007 formats
1008 .iter()
1009 .any(|&linkage| #[allow(non_exhaustive_omitted_patterns)] match linkage {
Linkage::Dynamic | Linkage::IncludedFromDylib => true,
_ => false,
}matches!(linkage, Linkage::Dynamic | Linkage::IncludedFromDylib))
1010 })
1011}
1012
1013impl CrateInfo {
1014 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
1015 let crate_types = tcx.crate_types().to_vec();
1016 let exported_symbols = crate_types
1017 .iter()
1018 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
1019 .collect();
1020 let linked_symbols =
1021 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
1022 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
1023 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);
1024 let dependency_formats = Arc::clone(tcx.dependency_formats(()));
1025 let eii_linkage = if eii_linkage_needed(&dependency_formats) {
1026 collect_eii_linkage(tcx)
1027 } else {
1028 Vec::new()
1029 };
1030
1031 let mut compiler_builtins = None;
1040 let mut used_crates: Vec<_> = tcx
1041 .postorder_cnums(())
1042 .iter()
1043 .rev()
1044 .copied()
1045 .filter(|&cnum| {
1046 let link = !tcx.crate_dep_kind(cnum).macros_only();
1047 if link && tcx.is_compiler_builtins(cnum) {
1048 compiler_builtins = Some(cnum);
1049 return false;
1050 }
1051 link
1052 })
1053 .collect();
1054 used_crates.extend(compiler_builtins);
1056
1057 let crates = tcx.crates(());
1058 let n_crates = crates.len();
1059 let mut info = CrateInfo {
1060 target_cpu,
1061 target_features: tcx.sess.global_backend_features.clone(),
1062 crate_types,
1063 exported_symbols,
1064 linked_symbols,
1065 local_crate_name,
1066 compiler_builtins,
1067 profiler_runtime: None,
1068 is_no_builtins: Default::default(),
1069 native_libraries: Default::default(),
1070 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
1071 crate_name: UnordMap::with_capacity(n_crates),
1072 used_crates,
1073 used_crate_source: UnordMap::with_capacity(n_crates),
1074 dependency_formats,
1075 eii_linkage,
1076 windows_subsystem,
1077 natvis_debugger_visualizers: Default::default(),
1078 lint_level_specs: CodegenLintLevelSpecs::from_tcx(tcx),
1079 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
1080 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)),
1081 each_linked_rlib_file_for_lto: Default::default(),
1082 exported_symbols_for_lto: Default::default(),
1083 };
1084
1085 info.native_libraries.reserve(n_crates);
1086
1087 for &cnum in crates.iter() {
1088 info.native_libraries
1089 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
1090 info.crate_name.insert(cnum, tcx.crate_name(cnum));
1091
1092 let used_crate_source = tcx.used_crate_source(cnum);
1093 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
1094 if tcx.is_profiler_runtime(cnum) {
1095 info.profiler_runtime = Some(cnum);
1096 }
1097 if tcx.is_no_builtins(cnum) {
1098 info.is_no_builtins.insert(cnum);
1099 }
1100 }
1101
1102 let target = &tcx.sess.target;
1111 if !are_upstream_rust_objects_already_included(tcx.sess) {
1112 let add_prefix = match (target.is_like_windows, &target.arch) {
1113 (true, Arch::X86) => |name: String, _: SymbolExportKind| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_{0}", name))
})format!("_{name}"),
1114 (true, Arch::Arm64EC) => {
1115 |name: String, export_kind: SymbolExportKind| match export_kind {
1117 SymbolExportKind::Text => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0}", name))
})format!("#{name}"),
1118 _ => name,
1119 }
1120 }
1121 _ => |name: String, _: SymbolExportKind| name,
1122 };
1123 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
1124 .used_crates
1125 .iter()
1126 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1127 .filter(|l| l.is_weak())
1128 .filter_map(|&l| {
1129 let name = l.link_name()?;
1130 let export_kind = match l.target() {
1131 Target::ForeignFn | Target::Fn => SymbolExportKind::Text,
1132 Target::Static => SymbolExportKind::Data,
1133 _ => bug_impl(None,
format_args!("Don\'t know what the export kind is for lang item of kind {0:?}",
l.target()), Location::caller())bug!(
1134 "Don't know what the export kind is for lang item of kind {:?}",
1135 l.target()
1136 ),
1137 };
1138 lang_items::required(tcx, l).then_some((name, export_kind))
1139 })
1140 .collect();
1141
1142 #[allow(rustc::potential_query_instability)]
1145 info.linked_symbols
1146 .iter_mut()
1147 .filter(|(crate_type, _)| {
1148 !#[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib)
1149 })
1150 .for_each(|(_, linked_symbols)| {
1151 let mut symbols = missing_weak_lang_items
1152 .iter()
1153 .map(|(item, export_kind)| {
1154 (
1155 add_prefix(
1156 mangle_internal_symbol(tcx, item.as_str()),
1157 *export_kind,
1158 ),
1159 *export_kind,
1160 )
1161 })
1162 .collect::<Vec<_>>();
1163 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1164 linked_symbols.extend(symbols);
1165 });
1166 }
1167
1168 let mut each_linked_rlib_for_lto = Vec::new();
1169 let mut each_linked_rlib_file_for_lto = Vec::new();
1170 if tcx.sess.lto() != config::Lto::No && tcx.sess.lto() != config::Lto::ThinLocal {
1171 drop(crate::back::link::each_linked_rlib(&info, None, &mut |cnum, path| {
1172 if crate::back::link::ignored_for_lto(tcx.sess, &info, cnum) {
1173 return;
1174 }
1175
1176 each_linked_rlib_for_lto.push(cnum);
1177 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1178 }));
1179 }
1180 info.each_linked_rlib_file_for_lto = each_linked_rlib_file_for_lto;
1181
1182 info.exported_symbols_for_lto =
1185 crate::back::lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto);
1186
1187 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1188 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1189 true
1192 }
1193 CrateType::ProcMacro => {
1194 false
1198 }
1199 CrateType::StaticLib | CrateType::Rlib => {
1200 false
1203 }
1204 });
1205
1206 if target.is_like_msvc && embed_visualizers {
1207 info.natvis_debugger_visualizers =
1208 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1209 }
1210
1211 info
1212 }
1213}
1214
1215pub(crate) fn provide(providers: &mut Providers) {
1216 providers.backend_optimization_level = |tcx, cratenum| {
1217 let for_speed = match tcx.sess.opts.optimize {
1218 config::OptLevel::No => return config::OptLevel::No,
1225 config::OptLevel::Less => return config::OptLevel::Less,
1227 config::OptLevel::More => return config::OptLevel::More,
1228 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1229 config::OptLevel::Size => config::OptLevel::More,
1232 config::OptLevel::SizeMin => config::OptLevel::More,
1233 };
1234
1235 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1236
1237 let any_for_speed = defids.items().any(|id| {
1238 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1239 #[allow(non_exhaustive_omitted_patterns)] match optimize {
OptimizeAttr::Speed => true,
_ => false,
}matches!(optimize, OptimizeAttr::Speed)
1240 });
1241
1242 if any_for_speed {
1243 return for_speed;
1244 }
1245
1246 tcx.sess.opts.optimize
1247 };
1248}
1249
1250pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1251 if !tcx.dep_graph.is_fully_enabled()
1252 || tcx.sess.opts.unstable_opts.disable_incr_comp_backend_caching
1253 {
1254 return CguReuse::No;
1255 }
1256
1257 let work_product_id = &cgu.work_product_id();
1258 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1259 return CguReuse::No;
1262 }
1263
1264 let dep_node = cgu.codegen_dep_node(tcx);
1271 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
1272 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("CompileCodegenUnit dep-node for CGU `{0}` already exists before marking.",
cgu.name()))
})format!(
1273 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1274 cgu.name()
1275 )
1276 });
1277
1278 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
1279 match compute_per_cgu_lto_type(
1283 &tcx.sess.lto(),
1284 tcx.sess.opts.cg.linker_plugin_lto.enabled(),
1285 tcx.crate_types(),
1286 ) {
1287 ComputedLtoType::No => CguReuse::PostLto,
1288 _ => CguReuse::PreLto,
1289 }
1290 } else {
1291 CguReuse::No
1292 }
1293}