1use std::cmp;
2use std::collections::BTreeSet;
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use itertools::Itertools;
7use rustc_abi::FIRST_VARIANT;
8use rustc_ast::expand::allocator::{ALLOCATOR_METHODS, AllocatorKind, global_fn_name};
9use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
10use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
11use rustc_data_structures::sync::par_map;
12use rustc_data_structures::unord::UnordMap;
13use rustc_hir::def_id::{DefId, LOCAL_CRATE};
14use rustc_hir::lang_items::LangItem;
15use rustc_metadata::EncodedMetadata;
16use rustc_middle::bug;
17use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
18use rustc_middle::middle::debugger_visualizer::{DebuggerVisualizerFile, DebuggerVisualizerType};
19use rustc_middle::middle::exported_symbols::SymbolExportKind;
20use rustc_middle::middle::{exported_symbols, lang_items};
21use rustc_middle::mir::BinOp;
22use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};
23use rustc_middle::query::Providers;
24use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
25use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
26use rustc_session::Session;
27use rustc_session::config::{self, CrateType, EntryFnType, OptLevel, OutputType};
28use rustc_span::{DUMMY_SP, Symbol, sym};
29use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
30use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
31use tracing::{debug, info};
32use {rustc_ast as ast, rustc_attr_parsing as attr};
33
34use crate::assert_module_sources::CguReuse;
35use crate::back::link::are_upstream_rust_objects_already_included;
36use crate::back::metadata::create_compressed_metadata_file;
37use crate::back::write::{
38 ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
39 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
40};
41use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
42use crate::meth::load_vtable;
43use crate::mir::operand::OperandValue;
44use crate::mir::place::PlaceRef;
45use crate::traits::*;
46use crate::{
47 CachedModuleCodegen, CodegenLintLevels, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
48 errors, meth, mir,
49};
50
51pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
52 match (op, signed) {
53 (BinOp::Eq, _) => IntPredicate::IntEQ,
54 (BinOp::Ne, _) => IntPredicate::IntNE,
55 (BinOp::Lt, true) => IntPredicate::IntSLT,
56 (BinOp::Lt, false) => IntPredicate::IntULT,
57 (BinOp::Le, true) => IntPredicate::IntSLE,
58 (BinOp::Le, false) => IntPredicate::IntULE,
59 (BinOp::Gt, true) => IntPredicate::IntSGT,
60 (BinOp::Gt, false) => IntPredicate::IntUGT,
61 (BinOp::Ge, true) => IntPredicate::IntSGE,
62 (BinOp::Ge, false) => IntPredicate::IntUGE,
63 op => bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
64 }
65}
66
67pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
68 match op {
69 BinOp::Eq => RealPredicate::RealOEQ,
70 BinOp::Ne => RealPredicate::RealUNE,
71 BinOp::Lt => RealPredicate::RealOLT,
72 BinOp::Le => RealPredicate::RealOLE,
73 BinOp::Gt => RealPredicate::RealOGT,
74 BinOp::Ge => RealPredicate::RealOGE,
75 op => bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
76 }
77}
78
79pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
80 bx: &mut Bx,
81 lhs: Bx::Value,
82 rhs: Bx::Value,
83 t: Ty<'tcx>,
84 ret_ty: Bx::Type,
85 op: BinOp,
86) -> Bx::Value {
87 let signed = match t.kind() {
88 ty::Float(_) => {
89 let cmp = bin_op_to_fcmp_predicate(op);
90 let cmp = bx.fcmp(cmp, lhs, rhs);
91 return bx.sext(cmp, ret_ty);
92 }
93 ty::Uint(_) => false,
94 ty::Int(_) => true,
95 _ => bug!("compare_simd_types: invalid SIMD type"),
96 };
97
98 let cmp = bin_op_to_icmp_predicate(op, signed);
99 let cmp = bx.icmp(cmp, lhs, rhs);
100 bx.sext(cmp, ret_ty)
105}
106
107pub fn validate_trivial_unsize<'tcx>(
116 tcx: TyCtxt<'tcx>,
117 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
118 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
119) -> bool {
120 match (source_data.principal(), target_data.principal()) {
121 (Some(hr_source_principal), Some(hr_target_principal)) => {
122 let (infcx, param_env) =
123 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
124 let universe = infcx.universe();
125 let ocx = ObligationCtxt::new(&infcx);
126 infcx.enter_forall(hr_target_principal, |target_principal| {
127 let source_principal = infcx.instantiate_binder_with_fresh_vars(
128 DUMMY_SP,
129 BoundRegionConversionTime::HigherRankedType,
130 hr_source_principal,
131 );
132 let Ok(()) = ocx.eq(
133 &ObligationCause::dummy(),
134 param_env,
135 target_principal,
136 source_principal,
137 ) else {
138 return false;
139 };
140 if !ocx.select_all_or_error().is_empty() {
141 return false;
142 }
143 infcx.leak_check(universe, None).is_ok()
144 })
145 }
146 (_, None) => true,
147 _ => false,
148 }
149}
150
151fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
157 bx: &mut Bx,
158 source: Ty<'tcx>,
159 target: Ty<'tcx>,
160 old_info: Option<Bx::Value>,
161) -> Bx::Value {
162 let cx = bx.cx();
163 let (source, target) =
164 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
165 match (source.kind(), target.kind()) {
166 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
167 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
168 ),
169 (&ty::Dynamic(data_a, _, src_dyn_kind), &ty::Dynamic(data_b, _, target_dyn_kind))
170 if src_dyn_kind == target_dyn_kind =>
171 {
172 let old_info =
173 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
174 let b_principal_def_id = data_b.principal_def_id();
175 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
176 debug_assert!(
185 validate_trivial_unsize(cx.tcx(), data_a, data_b),
186 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
187 );
188
189 return old_info;
195 }
196
197 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
200
201 if let Some(entry_idx) = vptr_entry_idx {
202 let ptr_size = bx.data_layout().pointer_size;
203 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
204 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
205 } else {
206 old_info
207 }
208 }
209 (_, ty::Dynamic(data, _, _)) => meth::get_vtable(
210 cx,
211 source,
212 data.principal()
213 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
214 ),
215 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
216 }
217}
218
219pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
221 bx: &mut Bx,
222 src: Bx::Value,
223 src_ty: Ty<'tcx>,
224 dst_ty: Ty<'tcx>,
225 old_info: Option<Bx::Value>,
226) -> (Bx::Value, Bx::Value) {
227 debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
228 match (src_ty.kind(), dst_ty.kind()) {
229 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
230 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
231 assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
232 (src, unsized_info(bx, a, b, old_info))
233 }
234 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
235 assert_eq!(def_a, def_b); let src_layout = bx.cx().layout_of(src_ty);
237 let dst_layout = bx.cx().layout_of(dst_ty);
238 if src_ty == dst_ty {
239 return (src, old_info.unwrap());
240 }
241 let mut result = None;
242 for i in 0..src_layout.fields.count() {
243 let src_f = src_layout.field(bx.cx(), i);
244 if src_f.is_1zst() {
245 continue;
247 }
248
249 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
250 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
251 assert_eq!(src_layout.size, src_f.size);
252
253 let dst_f = dst_layout.field(bx.cx(), i);
254 assert_ne!(src_f.ty, dst_f.ty);
255 assert_eq!(result, None);
256 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
257 }
258 result.unwrap()
259 }
260 _ => bug!("unsize_ptr: called on bad types"),
261 }
262}
263
264pub(crate) fn cast_to_dyn_star<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
266 bx: &mut Bx,
267 src: Bx::Value,
268 src_ty_and_layout: TyAndLayout<'tcx>,
269 dst_ty: Ty<'tcx>,
270 old_info: Option<Bx::Value>,
271) -> (Bx::Value, Bx::Value) {
272 debug!("cast_to_dyn_star: {:?} => {:?}", src_ty_and_layout.ty, dst_ty);
273 assert!(
274 matches!(dst_ty.kind(), ty::Dynamic(_, _, ty::DynStar)),
275 "destination type must be a dyn*"
276 );
277 let src = match bx.cx().type_kind(bx.cx().backend_type(src_ty_and_layout)) {
278 TypeKind::Pointer => src,
279 TypeKind::Integer => bx.inttoptr(src, bx.type_ptr()),
280 kind => bug!("unexpected TypeKind for left-hand side of `dyn*` cast: {kind:?}"),
282 };
283 (src, unsized_info(bx, src_ty_and_layout.ty, dst_ty, old_info))
284}
285
286pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
289 bx: &mut Bx,
290 src: PlaceRef<'tcx, Bx::Value>,
291 dst: PlaceRef<'tcx, Bx::Value>,
292) {
293 let src_ty = src.layout.ty;
294 let dst_ty = dst.layout.ty;
295 match (src_ty.kind(), dst_ty.kind()) {
296 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
297 let (base, info) = match bx.load_operand(src).val {
298 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
299 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
300 OperandValue::Ref(..) | OperandValue::ZeroSized => bug!(),
301 };
302 OperandValue::Pair(base, info).store(bx, dst);
303 }
304
305 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
306 assert_eq!(def_a, def_b); for i in def_a.variant(FIRST_VARIANT).fields.indices() {
309 let src_f = src.project_field(bx, i.as_usize());
310 let dst_f = dst.project_field(bx, i.as_usize());
311
312 if dst_f.layout.is_zst() {
313 continue;
315 }
316
317 if src_f.layout.ty == dst_f.layout.ty {
318 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
319 } else {
320 coerce_unsized_into(bx, src_f, dst_f);
321 }
322 }
323 }
324 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
325 }
326}
327
328pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
344 bx: &mut Bx,
345 lhs: Bx::Value,
346 mut rhs: Bx::Value,
347 is_unchecked: bool,
348) -> Bx::Value {
349 let mut rhs_llty = bx.cx().val_ty(rhs);
351 let mut lhs_llty = bx.cx().val_ty(lhs);
352
353 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
354 if !is_unchecked {
355 rhs = bx.and(rhs, mask);
356 }
357
358 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
359 rhs_llty = bx.cx().element_type(rhs_llty)
360 }
361 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
362 lhs_llty = bx.cx().element_type(lhs_llty)
363 }
364 let rhs_sz = bx.cx().int_width(rhs_llty);
365 let lhs_sz = bx.cx().int_width(lhs_llty);
366 if lhs_sz < rhs_sz {
367 if is_unchecked && bx.sess().opts.optimize != OptLevel::No {
368 let inrange = bx.icmp(IntPredicate::IntULE, rhs, mask);
370 bx.assume(inrange);
371 }
372
373 bx.trunc(rhs, lhs_llty)
374 } else if lhs_sz > rhs_sz {
375 assert!(lhs_sz <= 256);
382 bx.zext(rhs, lhs_llty)
383 } else {
384 rhs
385 }
386}
387
388pub fn wants_wasm_eh(sess: &Session) -> bool {
392 sess.target.is_like_wasm
393 && (sess.target.os != "emscripten" || sess.opts.unstable_opts.emscripten_wasm_eh)
394}
395
396pub fn wants_msvc_seh(sess: &Session) -> bool {
402 sess.target.is_like_msvc
403}
404
405pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
409 wants_wasm_eh(sess) || wants_msvc_seh(sess)
410}
411
412pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
413 cx: &'a Bx::CodegenCx,
414 instance: Instance<'tcx>,
415) {
416 info!("codegen_instance({})", instance);
420
421 mir::codegen_mir::<Bx>(cx, instance);
422}
423
424pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
427 cx: &'a Bx::CodegenCx,
428) -> Option<Bx::Function> {
429 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
430 let main_is_local = main_def_id.is_local();
431 let instance = Instance::mono(cx.tcx(), main_def_id);
432
433 if main_is_local {
434 if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
437 return None;
438 }
439 } else if !cx.codegen_unit().is_primary() {
440 return None;
442 }
443
444 let main_llfn = cx.get_fn_addr(instance);
445
446 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
447 return Some(entry_fn);
448
449 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
450 cx: &'a Bx::CodegenCx,
451 rust_main: Bx::Value,
452 rust_main_def_id: DefId,
453 entry_type: EntryFnType,
454 ) -> Bx::Function {
455 let llfty = if cx.sess().target.os.contains("uefi") {
458 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
459 } else if cx.sess().target.main_needs_argc_argv {
460 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
461 } else {
462 cx.type_func(&[], cx.type_int())
463 };
464
465 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
466 let main_ret_ty = cx
472 .tcx()
473 .normalize_erasing_regions(cx.typing_env(), main_ret_ty.no_bound_vars().unwrap());
474
475 let Some(llfn) = cx.declare_c_main(llfty) else {
476 let span = cx.tcx().def_span(rust_main_def_id);
478 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
479 };
480
481 cx.set_frame_pointer_type(llfn);
483 cx.apply_target_cpu_attr(llfn);
484
485 let llbb = Bx::append_block(cx, llfn, "top");
486 let mut bx = Bx::build(cx, llbb);
487
488 bx.insert_reference_to_gdb_debug_scripts_section_global();
489
490 let isize_ty = cx.type_isize();
491 let ptr_ty = cx.type_ptr();
492 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
493
494 let EntryFnType::Main { sigpipe } = entry_type;
495 let (start_fn, start_ty, args, instance) = {
496 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, None);
497 let start_instance = ty::Instance::expect_resolve(
498 cx.tcx(),
499 cx.typing_env(),
500 start_def_id,
501 cx.tcx().mk_args(&[main_ret_ty.into()]),
502 DUMMY_SP,
503 );
504 let start_fn = cx.get_fn_addr(start_instance);
505
506 let i8_ty = cx.type_i8();
507 let arg_sigpipe = bx.const_u8(sigpipe);
508
509 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
510 (
511 start_fn,
512 start_ty,
513 vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
514 Some(start_instance),
515 )
516 };
517
518 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
519 if cx.sess().target.os.contains("uefi") {
520 bx.ret(result);
521 } else {
522 let cast = bx.intcast(result, cx.type_int(), true);
523 bx.ret(cast);
524 }
525
526 llfn
527 }
528}
529
530fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
533 if bx.cx().sess().target.os.contains("uefi") {
534 let param_handle = bx.get_param(0);
536 let param_system_table = bx.get_param(1);
537 let ptr_size = bx.tcx().data_layout.pointer_size;
538 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
539 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
540 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
541 bx.store(param_handle, arg_argv, ptr_align);
542 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
543 bx.store(param_system_table, arg_argv_el1, ptr_align);
544 (arg_argc, arg_argv)
545 } else if bx.cx().sess().target.main_needs_argc_argv {
546 let param_argc = bx.get_param(0);
548 let param_argv = bx.get_param(1);
549 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
550 let arg_argv = param_argv;
551 (arg_argc, arg_argv)
552 } else {
553 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
555 let arg_argv = bx.const_null(bx.cx().type_ptr());
556 (arg_argc, arg_argv)
557 }
558}
559
560pub fn collect_debugger_visualizers_transitive(
564 tcx: TyCtxt<'_>,
565 visualizer_type: DebuggerVisualizerType,
566) -> BTreeSet<DebuggerVisualizerFile> {
567 tcx.debugger_visualizers(LOCAL_CRATE)
568 .iter()
569 .chain(
570 tcx.crates(())
571 .iter()
572 .filter(|&cnum| {
573 let used_crate_source = tcx.used_crate_source(*cnum);
574 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
575 })
576 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
577 )
578 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
579 .cloned()
580 .collect::<BTreeSet<_>>()
581}
582
583pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
587 let any_dynamic_crate = tcx.dependency_formats(()).iter().any(|(_, list)| {
594 use rustc_middle::middle::dependency_format::Linkage;
595 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
596 });
597 if any_dynamic_crate { None } else { tcx.allocator_kind(()) }
598}
599
600pub fn codegen_crate<B: ExtraBackendMethods>(
601 backend: B,
602 tcx: TyCtxt<'_>,
603 target_cpu: String,
604 metadata: EncodedMetadata,
605 need_metadata_module: bool,
606) -> OngoingCodegen<B> {
607 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
609 let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, metadata, None);
610
611 ongoing_codegen.codegen_finished(tcx);
612
613 ongoing_codegen.check_for_errors(tcx.sess);
614
615 return ongoing_codegen;
616 }
617
618 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
619 tcx.dcx().emit_fatal(errors::CpuRequired);
621 }
622
623 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
624
625 let MonoItemPartitions { codegen_units, autodiff_items, .. } =
628 tcx.collect_and_partition_mono_items(());
629 let autodiff_fncs = autodiff_items.to_vec();
630
631 if tcx.dep_graph.is_fully_enabled() {
637 for cgu in codegen_units {
638 tcx.ensure_ok().codegen_unit(cgu.name());
639 }
640 }
641
642 let metadata_module = need_metadata_module.then(|| {
643 let metadata_cgu_name =
645 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
646 tcx.sess.time("write_compressed_metadata", || {
647 let file_name =
648 tcx.output_filenames(()).temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
649 let data = create_compressed_metadata_file(
650 tcx.sess,
651 &metadata,
652 &exported_symbols::metadata_symbol_name(tcx),
653 );
654 if let Err(error) = std::fs::write(&file_name, data) {
655 tcx.dcx().emit_fatal(errors::MetadataObjectFileWrite { error });
656 }
657 CompiledModule {
658 name: metadata_cgu_name,
659 kind: ModuleKind::Metadata,
660 object: Some(file_name),
661 dwarf_object: None,
662 bytecode: None,
663 assembly: None,
664 llvm_ir: None,
665 }
666 })
667 });
668
669 let ongoing_codegen =
670 start_async_codegen(backend.clone(), tcx, target_cpu, metadata, metadata_module);
671
672 if let Some(kind) = allocator_kind_for_codegen(tcx) {
674 let llmod_id =
675 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
676 let module_llvm = tcx.sess.time("write_allocator_module", || {
677 backend.codegen_allocator(
678 tcx,
679 &llmod_id,
680 kind,
681 tcx.alloc_error_handler_kind(()).unwrap(),
684 )
685 });
686
687 ongoing_codegen.wait_for_signal_to_codegen_item();
688 ongoing_codegen.check_for_errors(tcx.sess);
689
690 let cost = 0;
692 submit_codegened_module_to_llvm(
693 &backend,
694 &ongoing_codegen.coordinator.sender,
695 ModuleCodegen { name: llmod_id, module_llvm, kind: ModuleKind::Allocator },
696 cost,
697 );
698 }
699
700 if !autodiff_fncs.is_empty() {
701 ongoing_codegen.submit_autodiff_items(autodiff_fncs);
702 }
703
704 let codegen_units: Vec<_> = {
716 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
717 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
718
719 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
720 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
721 };
722
723 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
725 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
726 });
727
728 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
729 for (i, cgu) in codegen_units.iter().enumerate() {
730 let cgu_reuse = cgu_reuse[i];
731 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
732 }
733 });
734
735 let mut total_codegen_time = Duration::new(0, 0);
736 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
737
738 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
749 tcx.sess.time("compile_first_CGU_batch", || {
750 let cgus: Vec<_> = cgu_reuse
752 .iter()
753 .enumerate()
754 .filter(|&(_, reuse)| reuse == &CguReuse::No)
755 .take(tcx.sess.threads())
756 .collect();
757
758 let start_time = Instant::now();
760
761 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
762 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
763 (i, module)
764 });
765
766 total_codegen_time += start_time.elapsed();
767
768 pre_compiled_cgus
769 })
770 } else {
771 FxHashMap::default()
772 };
773
774 for (i, cgu) in codegen_units.iter().enumerate() {
775 ongoing_codegen.wait_for_signal_to_codegen_item();
776 ongoing_codegen.check_for_errors(tcx.sess);
777
778 let cgu_reuse = cgu_reuse[i];
779
780 match cgu_reuse {
781 CguReuse::No => {
782 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
783 cgu
784 } else {
785 let start_time = Instant::now();
786 let module = backend.compile_codegen_unit(tcx, cgu.name());
787 total_codegen_time += start_time.elapsed();
788 module
789 };
790 tcx.dcx().abort_if_errors();
794
795 submit_codegened_module_to_llvm(
796 &backend,
797 &ongoing_codegen.coordinator.sender,
798 module,
799 cost,
800 );
801 }
802 CguReuse::PreLto => {
803 submit_pre_lto_module_to_llvm(
804 &backend,
805 tcx,
806 &ongoing_codegen.coordinator.sender,
807 CachedModuleCodegen {
808 name: cgu.name().to_string(),
809 source: cgu.previous_work_product(tcx),
810 },
811 );
812 }
813 CguReuse::PostLto => {
814 submit_post_lto_module_to_llvm(
815 &backend,
816 &ongoing_codegen.coordinator.sender,
817 CachedModuleCodegen {
818 name: cgu.name().to_string(),
819 source: cgu.previous_work_product(tcx),
820 },
821 );
822 }
823 }
824 }
825
826 ongoing_codegen.codegen_finished(tcx);
827
828 if tcx.sess.opts.unstable_opts.time_passes {
831 let end_rss = get_resident_set_size();
832
833 print_time_passes_entry(
834 "codegen_to_LLVM_IR",
835 total_codegen_time,
836 start_rss.unwrap(),
837 end_rss,
838 tcx.sess.opts.unstable_opts.time_passes_format,
839 );
840 }
841
842 ongoing_codegen.check_for_errors(tcx.sess);
843 ongoing_codegen
844}
845
846pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
856 tcx: TyCtxt<'tcx>,
857 instance: Instance<'tcx>,
858) -> bool {
859 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
860 if let Some(name) = tcx.codegen_fn_attrs(def_id).link_name {
861 name.as_str().starts_with("llvm.")
862 } else {
863 false
864 }
865 }
866
867 let def_id = instance.def_id();
868 !def_id.is_local()
869 && tcx.is_compiler_builtins(LOCAL_CRATE)
870 && !is_llvm_intrinsic(tcx, def_id)
871 && !tcx.should_codegen_locally(instance)
872}
873
874impl CrateInfo {
875 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
876 let crate_types = tcx.crate_types().to_vec();
877 let exported_symbols = crate_types
878 .iter()
879 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
880 .collect();
881 let linked_symbols =
882 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
883 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
884 let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
885 let subsystem =
886 ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
887 let windows_subsystem = subsystem.map(|subsystem| {
888 if subsystem != sym::windows && subsystem != sym::console {
889 tcx.dcx().emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
890 }
891 subsystem.to_string()
892 });
893
894 let mut compiler_builtins = None;
903 let mut used_crates: Vec<_> = tcx
904 .postorder_cnums(())
905 .iter()
906 .rev()
907 .copied()
908 .filter(|&cnum| {
909 let link = !tcx.dep_kind(cnum).macros_only();
910 if link && tcx.is_compiler_builtins(cnum) {
911 compiler_builtins = Some(cnum);
912 return false;
913 }
914 link
915 })
916 .collect();
917 used_crates.extend(compiler_builtins);
919
920 let crates = tcx.crates(());
921 let n_crates = crates.len();
922 let mut info = CrateInfo {
923 target_cpu,
924 crate_types,
925 exported_symbols,
926 linked_symbols,
927 local_crate_name,
928 compiler_builtins,
929 profiler_runtime: None,
930 is_no_builtins: Default::default(),
931 native_libraries: Default::default(),
932 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
933 crate_name: UnordMap::with_capacity(n_crates),
934 used_crates,
935 used_crate_source: UnordMap::with_capacity(n_crates),
936 dependency_formats: Arc::clone(tcx.dependency_formats(())),
937 windows_subsystem,
938 natvis_debugger_visualizers: Default::default(),
939 lint_levels: CodegenLintLevels::from_tcx(tcx),
940 };
941
942 info.native_libraries.reserve(n_crates);
943
944 for &cnum in crates.iter() {
945 info.native_libraries
946 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
947 info.crate_name.insert(cnum, tcx.crate_name(cnum));
948
949 let used_crate_source = tcx.used_crate_source(cnum);
950 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
951 if tcx.is_profiler_runtime(cnum) {
952 info.profiler_runtime = Some(cnum);
953 }
954 if tcx.is_no_builtins(cnum) {
955 info.is_no_builtins.insert(cnum);
956 }
957 }
958
959 let target = &tcx.sess.target;
968 if !are_upstream_rust_objects_already_included(tcx.sess) {
969 let missing_weak_lang_items: FxIndexSet<Symbol> = info
970 .used_crates
971 .iter()
972 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
973 .filter(|l| l.is_weak())
974 .filter_map(|&l| {
975 let name = l.link_name()?;
976 lang_items::required(tcx, l).then_some(name)
977 })
978 .collect();
979 let prefix = match (target.is_like_windows, target.arch.as_ref()) {
980 (true, "x86") => "_",
981 (true, "arm64ec") => "#",
982 _ => "",
983 };
984
985 #[allow(rustc::potential_query_instability)]
988 info.linked_symbols
989 .iter_mut()
990 .filter(|(crate_type, _)| {
991 !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
992 })
993 .for_each(|(_, linked_symbols)| {
994 let mut symbols = missing_weak_lang_items
995 .iter()
996 .map(|item| (format!("{prefix}{item}"), SymbolExportKind::Text))
997 .collect::<Vec<_>>();
998 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
999 linked_symbols.extend(symbols);
1000 if tcx.allocator_kind(()).is_some() {
1001 linked_symbols.extend(ALLOCATOR_METHODS.iter().map(|method| {
1008 (
1009 format!("{prefix}{}", global_fn_name(method.name).as_str()),
1010 SymbolExportKind::Text,
1011 )
1012 }));
1013 }
1014 });
1015 }
1016
1017 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1018 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib => {
1019 true
1022 }
1023 CrateType::ProcMacro => {
1024 false
1028 }
1029 CrateType::Staticlib | CrateType::Rlib => {
1030 false
1033 }
1034 });
1035
1036 if target.is_like_msvc && embed_visualizers {
1037 info.natvis_debugger_visualizers =
1038 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1039 }
1040
1041 info
1042 }
1043}
1044
1045pub(crate) fn provide(providers: &mut Providers) {
1046 providers.backend_optimization_level = |tcx, cratenum| {
1047 let for_speed = match tcx.sess.opts.optimize {
1048 config::OptLevel::No => return config::OptLevel::No,
1055 config::OptLevel::Less => return config::OptLevel::Less,
1057 config::OptLevel::More => return config::OptLevel::More,
1058 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1059 config::OptLevel::Size => config::OptLevel::More,
1062 config::OptLevel::SizeMin => config::OptLevel::More,
1063 };
1064
1065 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1066
1067 let any_for_speed = defids.items().any(|id| {
1068 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1069 matches!(optimize, attr::OptimizeAttr::Speed)
1070 });
1071
1072 if any_for_speed {
1073 return for_speed;
1074 }
1075
1076 tcx.sess.opts.optimize
1077 };
1078}
1079
1080pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1081 if !tcx.dep_graph.is_fully_enabled() {
1082 return CguReuse::No;
1083 }
1084
1085 let work_product_id = &cgu.work_product_id();
1086 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1087 return CguReuse::No;
1090 }
1091
1092 let dep_node = cgu.codegen_dep_node(tcx);
1099 assert!(
1100 !tcx.dep_graph.dep_node_exists(&dep_node),
1101 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1102 cgu.name()
1103 );
1104
1105 if tcx.try_mark_green(&dep_node) {
1106 match compute_per_cgu_lto_type(
1110 &tcx.sess.lto(),
1111 &tcx.sess.opts,
1112 tcx.crate_types(),
1113 ModuleKind::Regular,
1114 ) {
1115 ComputedLtoType::No => CguReuse::PostLto,
1116 _ => CguReuse::PreLto,
1117 }
1118 } else {
1119 CguReuse::No
1120 }
1121}