1use std::cmp;
2use std::collections::BTreeSet;
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use itertools::Itertools;
7use rustc_abi::FIRST_VARIANT;
8use rustc_ast as ast;
9use rustc_ast::expand::allocator::AllocatorKind;
10use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
11use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
12use rustc_data_structures::sync::{IntoDynSyncSend, par_map};
13use rustc_data_structures::unord::UnordMap;
14use rustc_hir::attrs::OptimizeAttr;
15use rustc_hir::def_id::{DefId, LOCAL_CRATE};
16use rustc_hir::lang_items::LangItem;
17use rustc_hir::{ItemId, Target};
18use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
19use rustc_middle::middle::debugger_visualizer::{DebuggerVisualizerFile, DebuggerVisualizerType};
20use rustc_middle::middle::dependency_format::Dependencies;
21use rustc_middle::middle::exported_symbols::{self, SymbolExportKind};
22use rustc_middle::middle::lang_items;
23use rustc_middle::mir::BinOp;
24use rustc_middle::mir::interpret::ErrorHandled;
25use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};
26use rustc_middle::query::Providers;
27use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
28use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
29use rustc_middle::{bug, span_bug};
30use rustc_session::Session;
31use rustc_session::config::{self, CrateType, EntryFnType};
32use rustc_span::{DUMMY_SP, Symbol, sym};
33use rustc_symbol_mangling::mangle_internal_symbol;
34use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
35use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
36use tracing::{debug, info};
37
38use crate::assert_module_sources::CguReuse;
39use crate::back::link::are_upstream_rust_objects_already_included;
40use crate::back::write::{
41 ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
42 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
43};
44use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
45use crate::meth::load_vtable;
46use crate::mir::operand::OperandValue;
47use crate::mir::place::PlaceRef;
48use crate::traits::*;
49use crate::{
50 CachedModuleCodegen, CodegenLintLevels, CrateInfo, ModuleCodegen, ModuleKind, errors, meth, mir,
51};
52
53pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
54 match (op, signed) {
55 (BinOp::Eq, _) => IntPredicate::IntEQ,
56 (BinOp::Ne, _) => IntPredicate::IntNE,
57 (BinOp::Lt, true) => IntPredicate::IntSLT,
58 (BinOp::Lt, false) => IntPredicate::IntULT,
59 (BinOp::Le, true) => IntPredicate::IntSLE,
60 (BinOp::Le, false) => IntPredicate::IntULE,
61 (BinOp::Gt, true) => IntPredicate::IntSGT,
62 (BinOp::Gt, false) => IntPredicate::IntUGT,
63 (BinOp::Ge, true) => IntPredicate::IntSGE,
64 (BinOp::Ge, false) => IntPredicate::IntUGE,
65 op => bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
66 }
67}
68
69pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
70 match op {
71 BinOp::Eq => RealPredicate::RealOEQ,
72 BinOp::Ne => RealPredicate::RealUNE,
73 BinOp::Lt => RealPredicate::RealOLT,
74 BinOp::Le => RealPredicate::RealOLE,
75 BinOp::Gt => RealPredicate::RealOGT,
76 BinOp::Ge => RealPredicate::RealOGE,
77 op => bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
78 }
79}
80
81pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
82 bx: &mut Bx,
83 lhs: Bx::Value,
84 rhs: Bx::Value,
85 t: Ty<'tcx>,
86 ret_ty: Bx::Type,
87 op: BinOp,
88) -> Bx::Value {
89 let signed = match t.kind() {
90 ty::Float(_) => {
91 let cmp = bin_op_to_fcmp_predicate(op);
92 let cmp = bx.fcmp(cmp, lhs, rhs);
93 return bx.sext(cmp, ret_ty);
94 }
95 ty::Uint(_) => false,
96 ty::Int(_) => true,
97 _ => bug!("compare_simd_types: invalid SIMD type"),
98 };
99
100 let cmp = bin_op_to_icmp_predicate(op, signed);
101 let cmp = bx.icmp(cmp, lhs, rhs);
102 bx.sext(cmp, ret_ty)
107}
108
109pub fn validate_trivial_unsize<'tcx>(
118 tcx: TyCtxt<'tcx>,
119 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
120 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
121) -> bool {
122 match (source_data.principal(), target_data.principal()) {
123 (Some(hr_source_principal), Some(hr_target_principal)) => {
124 let (infcx, param_env) =
125 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
126 let universe = infcx.universe();
127 let ocx = ObligationCtxt::new(&infcx);
128 infcx.enter_forall(hr_target_principal, |target_principal| {
129 let source_principal = infcx.instantiate_binder_with_fresh_vars(
130 DUMMY_SP,
131 BoundRegionConversionTime::HigherRankedType,
132 hr_source_principal,
133 );
134 let Ok(()) = ocx.eq(
135 &ObligationCause::dummy(),
136 param_env,
137 target_principal,
138 source_principal,
139 ) else {
140 return false;
141 };
142 if !ocx.select_all_or_error().is_empty() {
143 return false;
144 }
145 infcx.leak_check(universe, None).is_ok()
146 })
147 }
148 (_, None) => true,
149 _ => false,
150 }
151}
152
153fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
159 bx: &mut Bx,
160 source: Ty<'tcx>,
161 target: Ty<'tcx>,
162 old_info: Option<Bx::Value>,
163) -> Bx::Value {
164 let cx = bx.cx();
165 let (source, target) =
166 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
167 match (source.kind(), target.kind()) {
168 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
169 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
170 ),
171 (&ty::Dynamic(data_a, _, src_dyn_kind), &ty::Dynamic(data_b, _, target_dyn_kind))
172 if src_dyn_kind == target_dyn_kind =>
173 {
174 let old_info =
175 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
176 let b_principal_def_id = data_b.principal_def_id();
177 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
178 debug_assert!(
187 validate_trivial_unsize(cx.tcx(), data_a, data_b),
188 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
189 );
190
191 return old_info;
197 }
198
199 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
202
203 if let Some(entry_idx) = vptr_entry_idx {
204 let ptr_size = bx.data_layout().pointer_size();
205 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
206 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
207 } else {
208 old_info
209 }
210 }
211 (_, ty::Dynamic(data, _, _)) => meth::get_vtable(
212 cx,
213 source,
214 data.principal()
215 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
216 ),
217 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
218 }
219}
220
221pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
223 bx: &mut Bx,
224 src: Bx::Value,
225 src_ty: Ty<'tcx>,
226 dst_ty: Ty<'tcx>,
227 old_info: Option<Bx::Value>,
228) -> (Bx::Value, Bx::Value) {
229 debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
230 match (src_ty.kind(), dst_ty.kind()) {
231 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
232 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
233 assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
234 (src, unsized_info(bx, a, b, old_info))
235 }
236 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
237 assert_eq!(def_a, def_b); let src_layout = bx.cx().layout_of(src_ty);
239 let dst_layout = bx.cx().layout_of(dst_ty);
240 if src_ty == dst_ty {
241 return (src, old_info.unwrap());
242 }
243 let mut result = None;
244 for i in 0..src_layout.fields.count() {
245 let src_f = src_layout.field(bx.cx(), i);
246 if src_f.is_1zst() {
247 continue;
249 }
250
251 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
252 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
253 assert_eq!(src_layout.size, src_f.size);
254
255 let dst_f = dst_layout.field(bx.cx(), i);
256 assert_ne!(src_f.ty, dst_f.ty);
257 assert_eq!(result, None);
258 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
259 }
260 result.unwrap()
261 }
262 _ => bug!("unsize_ptr: called on bad types"),
263 }
264}
265
266pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
269 bx: &mut Bx,
270 src: PlaceRef<'tcx, Bx::Value>,
271 dst: PlaceRef<'tcx, Bx::Value>,
272) {
273 let src_ty = src.layout.ty;
274 let dst_ty = dst.layout.ty;
275 match (src_ty.kind(), dst_ty.kind()) {
276 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
277 let (base, info) = match bx.load_operand(src).val {
278 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
279 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
280 OperandValue::Ref(..) | OperandValue::ZeroSized => bug!(),
281 };
282 OperandValue::Pair(base, info).store(bx, dst);
283 }
284
285 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
286 assert_eq!(def_a, def_b); for i in def_a.variant(FIRST_VARIANT).fields.indices() {
289 let src_f = src.project_field(bx, i.as_usize());
290 let dst_f = dst.project_field(bx, i.as_usize());
291
292 if dst_f.layout.is_zst() {
293 continue;
295 }
296
297 if src_f.layout.ty == dst_f.layout.ty {
298 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
299 } else {
300 coerce_unsized_into(bx, src_f, dst_f);
301 }
302 }
303 }
304 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
305 }
306}
307
308pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
324 bx: &mut Bx,
325 lhs: Bx::Value,
326 mut rhs: Bx::Value,
327 is_unchecked: bool,
328) -> Bx::Value {
329 let mut rhs_llty = bx.cx().val_ty(rhs);
331 let mut lhs_llty = bx.cx().val_ty(lhs);
332
333 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
334 if !is_unchecked {
335 rhs = bx.and(rhs, mask);
336 }
337
338 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
339 rhs_llty = bx.cx().element_type(rhs_llty)
340 }
341 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
342 lhs_llty = bx.cx().element_type(lhs_llty)
343 }
344 let rhs_sz = bx.cx().int_width(rhs_llty);
345 let lhs_sz = bx.cx().int_width(lhs_llty);
346 if lhs_sz < rhs_sz {
347 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
348 } else if lhs_sz > rhs_sz {
349 assert!(lhs_sz <= 256);
356 bx.zext(rhs, lhs_llty)
357 } else {
358 rhs
359 }
360}
361
362pub fn wants_wasm_eh(sess: &Session) -> bool {
366 sess.target.is_like_wasm
367 && (sess.target.os != "emscripten" || sess.opts.unstable_opts.emscripten_wasm_eh)
368}
369
370pub fn wants_msvc_seh(sess: &Session) -> bool {
376 sess.target.is_like_msvc
377}
378
379pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
383 wants_wasm_eh(sess) || wants_msvc_seh(sess)
384}
385
386pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
387 cx: &'a Bx::CodegenCx,
388 instance: Instance<'tcx>,
389) {
390 info!("codegen_instance({})", instance);
394
395 mir::codegen_mir::<Bx>(cx, instance);
396}
397
398pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: ItemId)
399where
400 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
401{
402 let item = cx.tcx().hir_item(item_id);
403 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
404 let operands: Vec<_> = asm
405 .operands
406 .iter()
407 .map(|(op, op_sp)| match *op {
408 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
409 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
410 Ok(const_value) => {
411 let ty =
412 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
413 let string = common::asm_const_to_str(
414 cx.tcx(),
415 *op_sp,
416 const_value,
417 cx.layout_of(ty),
418 );
419 GlobalAsmOperandRef::Const { string }
420 }
421 Err(ErrorHandled::Reported { .. }) => {
422 GlobalAsmOperandRef::Const { string: String::new() }
427 }
428 Err(ErrorHandled::TooGeneric(_)) => {
429 span_bug!(*op_sp, "asm const cannot be resolved; too generic")
430 }
431 }
432 }
433 rustc_hir::InlineAsmOperand::SymFn { expr } => {
434 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
435 let instance = match ty.kind() {
436 &ty::FnDef(def_id, args) => Instance::expect_resolve(
437 cx.tcx(),
438 ty::TypingEnv::fully_monomorphized(),
439 def_id,
440 args,
441 expr.span,
442 ),
443 _ => span_bug!(*op_sp, "asm sym is not a function"),
444 };
445
446 GlobalAsmOperandRef::SymFn { instance }
447 }
448 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
449 GlobalAsmOperandRef::SymStatic { def_id }
450 }
451 rustc_hir::InlineAsmOperand::In { .. }
452 | rustc_hir::InlineAsmOperand::Out { .. }
453 | rustc_hir::InlineAsmOperand::InOut { .. }
454 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
455 | rustc_hir::InlineAsmOperand::Label { .. } => {
456 span_bug!(*op_sp, "invalid operand type for global_asm!")
457 }
458 })
459 .collect();
460
461 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans);
462 } else {
463 span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
464 }
465}
466
467pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
470 cx: &'a Bx::CodegenCx,
471 cgu: &CodegenUnit<'tcx>,
472) -> Option<Bx::Function> {
473 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
474 let main_is_local = main_def_id.is_local();
475 let instance = Instance::mono(cx.tcx(), main_def_id);
476
477 if main_is_local {
478 if !cgu.contains_item(&MonoItem::Fn(instance)) {
481 return None;
482 }
483 } else if !cgu.is_primary() {
484 return None;
486 }
487
488 let main_llfn = cx.get_fn_addr(instance);
489
490 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
491 return Some(entry_fn);
492
493 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
494 cx: &'a Bx::CodegenCx,
495 rust_main: Bx::Value,
496 rust_main_def_id: DefId,
497 entry_type: EntryFnType,
498 ) -> Bx::Function {
499 let llfty = if cx.sess().target.os.contains("uefi") {
502 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
503 } else if cx.sess().target.main_needs_argc_argv {
504 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
505 } else {
506 cx.type_func(&[], cx.type_int())
507 };
508
509 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
510 let main_ret_ty = cx
516 .tcx()
517 .normalize_erasing_regions(cx.typing_env(), main_ret_ty.no_bound_vars().unwrap());
518
519 let Some(llfn) = cx.declare_c_main(llfty) else {
520 let span = cx.tcx().def_span(rust_main_def_id);
522 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
523 };
524
525 cx.set_frame_pointer_type(llfn);
527 cx.apply_target_cpu_attr(llfn);
528
529 let llbb = Bx::append_block(cx, llfn, "top");
530 let mut bx = Bx::build(cx, llbb);
531
532 bx.insert_reference_to_gdb_debug_scripts_section_global();
533
534 let isize_ty = cx.type_isize();
535 let ptr_ty = cx.type_ptr();
536 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
537
538 let EntryFnType::Main { sigpipe } = entry_type;
539 let (start_fn, start_ty, args, instance) = {
540 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
541 let start_instance = ty::Instance::expect_resolve(
542 cx.tcx(),
543 cx.typing_env(),
544 start_def_id,
545 cx.tcx().mk_args(&[main_ret_ty.into()]),
546 DUMMY_SP,
547 );
548 let start_fn = cx.get_fn_addr(start_instance);
549
550 let i8_ty = cx.type_i8();
551 let arg_sigpipe = bx.const_u8(sigpipe);
552
553 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
554 (
555 start_fn,
556 start_ty,
557 vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
558 Some(start_instance),
559 )
560 };
561
562 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
563 if cx.sess().target.os.contains("uefi") {
564 bx.ret(result);
565 } else {
566 let cast = bx.intcast(result, cx.type_int(), true);
567 bx.ret(cast);
568 }
569
570 llfn
571 }
572}
573
574fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
577 if bx.cx().sess().target.os.contains("uefi") {
578 let param_handle = bx.get_param(0);
580 let param_system_table = bx.get_param(1);
581 let ptr_size = bx.tcx().data_layout.pointer_size();
582 let ptr_align = bx.tcx().data_layout.pointer_align().abi;
583 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
584 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
585 bx.store(param_handle, arg_argv, ptr_align);
586 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
587 bx.store(param_system_table, arg_argv_el1, ptr_align);
588 (arg_argc, arg_argv)
589 } else if bx.cx().sess().target.main_needs_argc_argv {
590 let param_argc = bx.get_param(0);
592 let param_argv = bx.get_param(1);
593 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
594 let arg_argv = param_argv;
595 (arg_argc, arg_argv)
596 } else {
597 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
599 let arg_argv = bx.const_null(bx.cx().type_ptr());
600 (arg_argc, arg_argv)
601 }
602}
603
604pub fn collect_debugger_visualizers_transitive(
608 tcx: TyCtxt<'_>,
609 visualizer_type: DebuggerVisualizerType,
610) -> BTreeSet<DebuggerVisualizerFile> {
611 tcx.debugger_visualizers(LOCAL_CRATE)
612 .iter()
613 .chain(
614 tcx.crates(())
615 .iter()
616 .filter(|&cnum| {
617 let used_crate_source = tcx.used_crate_source(*cnum);
618 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
619 })
620 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
621 )
622 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
623 .cloned()
624 .collect::<BTreeSet<_>>()
625}
626
627pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
631 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
641 use rustc_middle::middle::dependency_format::Linkage;
642 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
643 });
644 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
645}
646
647pub(crate) fn needs_allocator_shim_for_linking(
651 dependency_formats: &Dependencies,
652 crate_type: CrateType,
653) -> bool {
654 use rustc_middle::middle::dependency_format::Linkage;
655 let any_dynamic_crate =
656 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
657 !any_dynamic_crate
658}
659
660pub fn codegen_crate<B: ExtraBackendMethods>(
661 backend: B,
662 tcx: TyCtxt<'_>,
663 target_cpu: String,
664) -> OngoingCodegen<B> {
665 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
667 let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, None);
668
669 ongoing_codegen.codegen_finished(tcx);
670
671 ongoing_codegen.check_for_errors(tcx.sess);
672
673 return ongoing_codegen;
674 }
675
676 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
677 tcx.dcx().emit_fatal(errors::CpuRequired);
679 }
680
681 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
682
683 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
686
687 if tcx.dep_graph.is_fully_enabled() {
693 for cgu in codegen_units {
694 tcx.ensure_ok().codegen_unit(cgu.name());
695 }
696 }
697
698 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
700 let llmod_id =
701 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
702
703 tcx.sess.time("write_allocator_module", || {
704 let module = backend.codegen_allocator(
705 tcx,
706 &llmod_id,
707 kind,
708 tcx.alloc_error_handler_kind(()).unwrap(),
711 );
712 Some(ModuleCodegen::new_allocator(llmod_id, module))
713 })
714 } else {
715 None
716 };
717
718 let ongoing_codegen = start_async_codegen(backend.clone(), tcx, target_cpu, allocator_module);
719
720 let codegen_units: Vec<_> = {
732 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
733 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
734
735 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
736 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
737 };
738
739 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
741 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
742 });
743
744 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
745 for (i, cgu) in codegen_units.iter().enumerate() {
746 let cgu_reuse = cgu_reuse[i];
747 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
748 }
749 });
750
751 let mut total_codegen_time = Duration::new(0, 0);
752 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
753
754 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
765 tcx.sess.time("compile_first_CGU_batch", || {
766 let cgus: Vec<_> = cgu_reuse
768 .iter()
769 .enumerate()
770 .filter(|&(_, reuse)| reuse == &CguReuse::No)
771 .take(tcx.sess.threads())
772 .collect();
773
774 let start_time = Instant::now();
776
777 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
778 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
779 (i, IntoDynSyncSend(module))
780 });
781
782 total_codegen_time += start_time.elapsed();
783
784 pre_compiled_cgus
785 })
786 } else {
787 FxHashMap::default()
788 };
789
790 for (i, cgu) in codegen_units.iter().enumerate() {
791 ongoing_codegen.wait_for_signal_to_codegen_item();
792 ongoing_codegen.check_for_errors(tcx.sess);
793
794 let cgu_reuse = cgu_reuse[i];
795
796 match cgu_reuse {
797 CguReuse::No => {
798 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
799 cgu.0
800 } else {
801 let start_time = Instant::now();
802 let module = backend.compile_codegen_unit(tcx, cgu.name());
803 total_codegen_time += start_time.elapsed();
804 module
805 };
806 tcx.dcx().abort_if_errors();
810
811 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
812 }
813 CguReuse::PreLto => {
814 submit_pre_lto_module_to_llvm(
815 tcx,
816 &ongoing_codegen.coordinator,
817 CachedModuleCodegen {
818 name: cgu.name().to_string(),
819 source: cgu.previous_work_product(tcx),
820 },
821 );
822 }
823 CguReuse::PostLto => {
824 submit_post_lto_module_to_llvm(
825 &ongoing_codegen.coordinator,
826 CachedModuleCodegen {
827 name: cgu.name().to_string(),
828 source: cgu.previous_work_product(tcx),
829 },
830 );
831 }
832 }
833 }
834
835 ongoing_codegen.codegen_finished(tcx);
836
837 if tcx.sess.opts.unstable_opts.time_passes {
840 let end_rss = get_resident_set_size();
841
842 print_time_passes_entry(
843 "codegen_to_LLVM_IR",
844 total_codegen_time,
845 start_rss.unwrap(),
846 end_rss,
847 tcx.sess.opts.unstable_opts.time_passes_format,
848 );
849 }
850
851 ongoing_codegen.check_for_errors(tcx.sess);
852 ongoing_codegen
853}
854
855pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
865 tcx: TyCtxt<'tcx>,
866 instance: Instance<'tcx>,
867) -> bool {
868 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
869 if let Some(name) = tcx.codegen_fn_attrs(def_id).symbol_name {
870 name.as_str().starts_with("llvm.")
871 } else {
872 false
873 }
874 }
875
876 let def_id = instance.def_id();
877 !def_id.is_local()
878 && tcx.is_compiler_builtins(LOCAL_CRATE)
879 && !is_llvm_intrinsic(tcx, def_id)
880 && !tcx.should_codegen_locally(instance)
881}
882
883impl CrateInfo {
884 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
885 let crate_types = tcx.crate_types().to_vec();
886 let exported_symbols = crate_types
887 .iter()
888 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
889 .collect();
890 let linked_symbols =
891 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
892 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
893 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
894 let subsystem =
895 ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
896 let windows_subsystem = subsystem.map(|subsystem| {
897 if subsystem != sym::windows && subsystem != sym::console {
898 tcx.dcx().emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
899 }
900 subsystem.to_string()
901 });
902
903 let mut compiler_builtins = None;
912 let mut used_crates: Vec<_> = tcx
913 .postorder_cnums(())
914 .iter()
915 .rev()
916 .copied()
917 .filter(|&cnum| {
918 let link = !tcx.dep_kind(cnum).macros_only();
919 if link && tcx.is_compiler_builtins(cnum) {
920 compiler_builtins = Some(cnum);
921 return false;
922 }
923 link
924 })
925 .collect();
926 used_crates.extend(compiler_builtins);
928
929 let crates = tcx.crates(());
930 let n_crates = crates.len();
931 let mut info = CrateInfo {
932 target_cpu,
933 target_features: tcx.global_backend_features(()).clone(),
934 crate_types,
935 exported_symbols,
936 linked_symbols,
937 local_crate_name,
938 compiler_builtins,
939 profiler_runtime: None,
940 is_no_builtins: Default::default(),
941 native_libraries: Default::default(),
942 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
943 crate_name: UnordMap::with_capacity(n_crates),
944 used_crates,
945 used_crate_source: UnordMap::with_capacity(n_crates),
946 dependency_formats: Arc::clone(tcx.dependency_formats(())),
947 windows_subsystem,
948 natvis_debugger_visualizers: Default::default(),
949 lint_levels: CodegenLintLevels::from_tcx(tcx),
950 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
951 };
952
953 info.native_libraries.reserve(n_crates);
954
955 for &cnum in crates.iter() {
956 info.native_libraries
957 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
958 info.crate_name.insert(cnum, tcx.crate_name(cnum));
959
960 let used_crate_source = tcx.used_crate_source(cnum);
961 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
962 if tcx.is_profiler_runtime(cnum) {
963 info.profiler_runtime = Some(cnum);
964 }
965 if tcx.is_no_builtins(cnum) {
966 info.is_no_builtins.insert(cnum);
967 }
968 }
969
970 let target = &tcx.sess.target;
979 if !are_upstream_rust_objects_already_included(tcx.sess) {
980 let add_prefix = match (target.is_like_windows, target.arch.as_ref()) {
981 (true, "x86") => |name: String, _: SymbolExportKind| format!("_{name}"),
982 (true, "arm64ec") => {
983 |name: String, export_kind: SymbolExportKind| match export_kind {
985 SymbolExportKind::Text => format!("#{name}"),
986 _ => name,
987 }
988 }
989 _ => |name: String, _: SymbolExportKind| name,
990 };
991 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
992 .used_crates
993 .iter()
994 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
995 .filter(|l| l.is_weak())
996 .filter_map(|&l| {
997 let name = l.link_name()?;
998 let export_kind = match l.target() {
999 Target::Fn => SymbolExportKind::Text,
1000 Target::Static => SymbolExportKind::Data,
1001 _ => bug!(
1002 "Don't know what the export kind is for lang item of kind {:?}",
1003 l.target()
1004 ),
1005 };
1006 lang_items::required(tcx, l).then_some((name, export_kind))
1007 })
1008 .collect();
1009
1010 #[allow(rustc::potential_query_instability)]
1013 info.linked_symbols
1014 .iter_mut()
1015 .filter(|(crate_type, _)| {
1016 !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
1017 })
1018 .for_each(|(_, linked_symbols)| {
1019 let mut symbols = missing_weak_lang_items
1020 .iter()
1021 .map(|(item, export_kind)| {
1022 (
1023 add_prefix(
1024 mangle_internal_symbol(tcx, item.as_str()),
1025 *export_kind,
1026 ),
1027 *export_kind,
1028 )
1029 })
1030 .collect::<Vec<_>>();
1031 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1032 linked_symbols.extend(symbols);
1033 });
1034 }
1035
1036 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1037 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1038 true
1041 }
1042 CrateType::ProcMacro => {
1043 false
1047 }
1048 CrateType::Staticlib | CrateType::Rlib => {
1049 false
1052 }
1053 });
1054
1055 if target.is_like_msvc && embed_visualizers {
1056 info.natvis_debugger_visualizers =
1057 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1058 }
1059
1060 info
1061 }
1062}
1063
1064pub(crate) fn provide(providers: &mut Providers) {
1065 providers.backend_optimization_level = |tcx, cratenum| {
1066 let for_speed = match tcx.sess.opts.optimize {
1067 config::OptLevel::No => return config::OptLevel::No,
1074 config::OptLevel::Less => return config::OptLevel::Less,
1076 config::OptLevel::More => return config::OptLevel::More,
1077 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1078 config::OptLevel::Size => config::OptLevel::More,
1081 config::OptLevel::SizeMin => config::OptLevel::More,
1082 };
1083
1084 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1085
1086 let any_for_speed = defids.items().any(|id| {
1087 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1088 matches!(optimize, OptimizeAttr::Speed)
1089 });
1090
1091 if any_for_speed {
1092 return for_speed;
1093 }
1094
1095 tcx.sess.opts.optimize
1096 };
1097}
1098
1099pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1100 if !tcx.dep_graph.is_fully_enabled() {
1101 return CguReuse::No;
1102 }
1103
1104 let work_product_id = &cgu.work_product_id();
1105 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1106 return CguReuse::No;
1109 }
1110
1111 let dep_node = cgu.codegen_dep_node(tcx);
1118 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(&dep_node, || {
1119 format!(
1120 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1121 cgu.name()
1122 )
1123 });
1124
1125 if tcx.try_mark_green(&dep_node) {
1126 match compute_per_cgu_lto_type(
1130 &tcx.sess.lto(),
1131 &tcx.sess.opts,
1132 tcx.crate_types(),
1133 ModuleKind::Regular,
1134 ) {
1135 ComputedLtoType::No => CguReuse::PostLto,
1136 _ => CguReuse::PreLto,
1137 }
1138 } else {
1139 CguReuse::No
1140 }
1141}