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::{
10 ALLOC_ERROR_HANDLER, ALLOCATOR_METHODS, AllocatorKind, AllocatorMethod, AllocatorTy,
11};
12use rustc_data_structures::fx::{FxHashMap, 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::{DebuggerVisualizerType, OptimizeAttr};
17use rustc_hir::def_id::{DefId, LOCAL_CRATE};
18use rustc_hir::lang_items::LangItem;
19use rustc_hir::{ItemId, Target};
20use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
21use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
22use rustc_middle::middle::dependency_format::Dependencies;
23use rustc_middle::middle::exported_symbols::{self, SymbolExportKind};
24use rustc_middle::middle::lang_items;
25use rustc_middle::mir::BinOp;
26use rustc_middle::mir::interpret::ErrorHandled;
27use rustc_middle::mir::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, Ty, TyCtxt};
31use rustc_middle::{bug, span_bug};
32use rustc_session::Session;
33use rustc_session::config::{self, CrateType, EntryFnType};
34use rustc_span::{DUMMY_SP, Symbol, sym};
35use rustc_symbol_mangling::mangle_internal_symbol;
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, 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, CodegenLintLevels, CrateInfo, ModuleCodegen, ModuleKind, errors, meth, mir,
53};
54
55pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
56 match (op, signed) {
57 (BinOp::Eq, _) => IntPredicate::IntEQ,
58 (BinOp::Ne, _) => IntPredicate::IntNE,
59 (BinOp::Lt, true) => IntPredicate::IntSLT,
60 (BinOp::Lt, false) => IntPredicate::IntULT,
61 (BinOp::Le, true) => IntPredicate::IntSLE,
62 (BinOp::Le, false) => IntPredicate::IntULE,
63 (BinOp::Gt, true) => IntPredicate::IntSGT,
64 (BinOp::Gt, false) => IntPredicate::IntUGT,
65 (BinOp::Ge, true) => IntPredicate::IntSGE,
66 (BinOp::Ge, false) => IntPredicate::IntUGE,
67 op => bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
68 }
69}
70
71pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
72 match op {
73 BinOp::Eq => RealPredicate::RealOEQ,
74 BinOp::Ne => RealPredicate::RealUNE,
75 BinOp::Lt => RealPredicate::RealOLT,
76 BinOp::Le => RealPredicate::RealOLE,
77 BinOp::Gt => RealPredicate::RealOGT,
78 BinOp::Ge => RealPredicate::RealOGE,
79 op => bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
80 }
81}
82
83pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
84 bx: &mut Bx,
85 lhs: Bx::Value,
86 rhs: Bx::Value,
87 t: Ty<'tcx>,
88 ret_ty: Bx::Type,
89 op: BinOp,
90) -> Bx::Value {
91 let signed = match t.kind() {
92 ty::Float(_) => {
93 let cmp = bin_op_to_fcmp_predicate(op);
94 let cmp = bx.fcmp(cmp, lhs, rhs);
95 return bx.sext(cmp, ret_ty);
96 }
97 ty::Uint(_) => false,
98 ty::Int(_) => true,
99 _ => bug!("compare_simd_types: invalid SIMD type"),
100 };
101
102 let cmp = bin_op_to_icmp_predicate(op, signed);
103 let cmp = bx.icmp(cmp, lhs, rhs);
104 bx.sext(cmp, ret_ty)
109}
110
111pub fn validate_trivial_unsize<'tcx>(
120 tcx: TyCtxt<'tcx>,
121 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
122 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
123) -> bool {
124 match (source_data.principal(), target_data.principal()) {
125 (Some(hr_source_principal), Some(hr_target_principal)) => {
126 let (infcx, param_env) =
127 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
128 let universe = infcx.universe();
129 let ocx = ObligationCtxt::new(&infcx);
130 infcx.enter_forall(hr_target_principal, |target_principal| {
131 let source_principal = infcx.instantiate_binder_with_fresh_vars(
132 DUMMY_SP,
133 BoundRegionConversionTime::HigherRankedType,
134 hr_source_principal,
135 );
136 let Ok(()) = ocx.eq(
137 &ObligationCause::dummy(),
138 param_env,
139 target_principal,
140 source_principal,
141 ) else {
142 return false;
143 };
144 if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
145 return false;
146 }
147 infcx.leak_check(universe, None).is_ok()
148 })
149 }
150 (_, None) => true,
151 _ => false,
152 }
153}
154
155fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
161 bx: &mut Bx,
162 source: Ty<'tcx>,
163 target: Ty<'tcx>,
164 old_info: Option<Bx::Value>,
165) -> Bx::Value {
166 let cx = bx.cx();
167 let (source, target) =
168 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
169 match (source.kind(), target.kind()) {
170 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
171 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
172 ),
173 (&ty::Dynamic(data_a, _), &ty::Dynamic(data_b, _)) => {
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 allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
661 let mut methods = Vec::new();
662
663 if kind == AllocatorKind::Default {
664 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
665 }
666
667 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
670 methods.push(AllocatorMethod {
671 name: ALLOC_ERROR_HANDLER,
672 special: None,
673 inputs: &[],
674 output: AllocatorTy::Never,
675 });
676 }
677
678 methods
679}
680
681pub fn codegen_crate<B: ExtraBackendMethods>(
682 backend: B,
683 tcx: TyCtxt<'_>,
684 target_cpu: String,
685) -> OngoingCodegen<B> {
686 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
688 let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, None);
689
690 ongoing_codegen.codegen_finished(tcx);
691
692 ongoing_codegen.check_for_errors(tcx.sess);
693
694 return ongoing_codegen;
695 }
696
697 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
698 tcx.dcx().emit_fatal(errors::CpuRequired);
700 }
701
702 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
703
704 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
707
708 if tcx.dep_graph.is_fully_enabled() {
714 for cgu in codegen_units {
715 tcx.ensure_ok().codegen_unit(cgu.name());
716 }
717 }
718
719 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
721 let llmod_id =
722 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
723
724 tcx.sess.time("write_allocator_module", || {
725 let module =
726 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
727 Some(ModuleCodegen::new_allocator(llmod_id, module))
728 })
729 } else {
730 None
731 };
732
733 let ongoing_codegen = start_async_codegen(backend.clone(), tcx, target_cpu, allocator_module);
734
735 let codegen_units: Vec<_> = {
747 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
748 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
749
750 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
751 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
752 };
753
754 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
756 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
757 });
758
759 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
760 for (i, cgu) in codegen_units.iter().enumerate() {
761 let cgu_reuse = cgu_reuse[i];
762 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
763 }
764 });
765
766 let mut total_codegen_time = Duration::new(0, 0);
767 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
768
769 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
780 tcx.sess.time("compile_first_CGU_batch", || {
781 let cgus: Vec<_> = cgu_reuse
783 .iter()
784 .enumerate()
785 .filter(|&(_, reuse)| reuse == &CguReuse::No)
786 .take(tcx.sess.threads())
787 .collect();
788
789 let start_time = Instant::now();
791
792 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
793 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
794 (i, IntoDynSyncSend(module))
795 });
796
797 total_codegen_time += start_time.elapsed();
798
799 pre_compiled_cgus
800 })
801 } else {
802 FxHashMap::default()
803 };
804
805 for (i, cgu) in codegen_units.iter().enumerate() {
806 ongoing_codegen.wait_for_signal_to_codegen_item();
807 ongoing_codegen.check_for_errors(tcx.sess);
808
809 let cgu_reuse = cgu_reuse[i];
810
811 match cgu_reuse {
812 CguReuse::No => {
813 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
814 cgu.0
815 } else {
816 let start_time = Instant::now();
817 let module = backend.compile_codegen_unit(tcx, cgu.name());
818 total_codegen_time += start_time.elapsed();
819 module
820 };
821 tcx.dcx().abort_if_errors();
825
826 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
827 }
828 CguReuse::PreLto => {
829 submit_pre_lto_module_to_llvm(
830 tcx,
831 &ongoing_codegen.coordinator,
832 CachedModuleCodegen {
833 name: cgu.name().to_string(),
834 source: cgu.previous_work_product(tcx),
835 },
836 );
837 }
838 CguReuse::PostLto => {
839 submit_post_lto_module_to_llvm(
840 &ongoing_codegen.coordinator,
841 CachedModuleCodegen {
842 name: cgu.name().to_string(),
843 source: cgu.previous_work_product(tcx),
844 },
845 );
846 }
847 }
848 }
849
850 ongoing_codegen.codegen_finished(tcx);
851
852 if tcx.sess.opts.unstable_opts.time_passes {
855 let end_rss = get_resident_set_size();
856
857 print_time_passes_entry(
858 "codegen_to_LLVM_IR",
859 total_codegen_time,
860 start_rss.unwrap(),
861 end_rss,
862 tcx.sess.opts.unstable_opts.time_passes_format,
863 );
864 }
865
866 ongoing_codegen.check_for_errors(tcx.sess);
867 ongoing_codegen
868}
869
870pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
880 tcx: TyCtxt<'tcx>,
881 instance: Instance<'tcx>,
882) -> bool {
883 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
884 if let Some(name) = tcx.codegen_fn_attrs(def_id).symbol_name {
885 name.as_str().starts_with("llvm.")
886 } else {
887 false
888 }
889 }
890
891 let def_id = instance.def_id();
892 !def_id.is_local()
893 && tcx.is_compiler_builtins(LOCAL_CRATE)
894 && !is_llvm_intrinsic(tcx, def_id)
895 && !tcx.should_codegen_locally(instance)
896}
897
898impl CrateInfo {
899 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
900 let crate_types = tcx.crate_types().to_vec();
901 let exported_symbols = crate_types
902 .iter()
903 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
904 .collect();
905 let linked_symbols =
906 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
907 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
908 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
909 let subsystem =
910 ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
911 let windows_subsystem = subsystem.map(|subsystem| {
912 if subsystem != sym::windows && subsystem != sym::console {
913 tcx.dcx().emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
914 }
915 subsystem.to_string()
916 });
917
918 let mut compiler_builtins = None;
927 let mut used_crates: Vec<_> = tcx
928 .postorder_cnums(())
929 .iter()
930 .rev()
931 .copied()
932 .filter(|&cnum| {
933 let link = !tcx.dep_kind(cnum).macros_only();
934 if link && tcx.is_compiler_builtins(cnum) {
935 compiler_builtins = Some(cnum);
936 return false;
937 }
938 link
939 })
940 .collect();
941 used_crates.extend(compiler_builtins);
943
944 let crates = tcx.crates(());
945 let n_crates = crates.len();
946 let mut info = CrateInfo {
947 target_cpu,
948 target_features: tcx.global_backend_features(()).clone(),
949 crate_types,
950 exported_symbols,
951 linked_symbols,
952 local_crate_name,
953 compiler_builtins,
954 profiler_runtime: None,
955 is_no_builtins: Default::default(),
956 native_libraries: Default::default(),
957 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
958 crate_name: UnordMap::with_capacity(n_crates),
959 used_crates,
960 used_crate_source: UnordMap::with_capacity(n_crates),
961 dependency_formats: Arc::clone(tcx.dependency_formats(())),
962 windows_subsystem,
963 natvis_debugger_visualizers: Default::default(),
964 lint_levels: CodegenLintLevels::from_tcx(tcx),
965 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
966 };
967
968 info.native_libraries.reserve(n_crates);
969
970 for &cnum in crates.iter() {
971 info.native_libraries
972 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
973 info.crate_name.insert(cnum, tcx.crate_name(cnum));
974
975 let used_crate_source = tcx.used_crate_source(cnum);
976 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
977 if tcx.is_profiler_runtime(cnum) {
978 info.profiler_runtime = Some(cnum);
979 }
980 if tcx.is_no_builtins(cnum) {
981 info.is_no_builtins.insert(cnum);
982 }
983 }
984
985 let target = &tcx.sess.target;
994 if !are_upstream_rust_objects_already_included(tcx.sess) {
995 let add_prefix = match (target.is_like_windows, target.arch.as_ref()) {
996 (true, "x86") => |name: String, _: SymbolExportKind| format!("_{name}"),
997 (true, "arm64ec") => {
998 |name: String, export_kind: SymbolExportKind| match export_kind {
1000 SymbolExportKind::Text => format!("#{name}"),
1001 _ => name,
1002 }
1003 }
1004 _ => |name: String, _: SymbolExportKind| name,
1005 };
1006 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
1007 .used_crates
1008 .iter()
1009 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1010 .filter(|l| l.is_weak())
1011 .filter_map(|&l| {
1012 let name = l.link_name()?;
1013 let export_kind = match l.target() {
1014 Target::Fn => SymbolExportKind::Text,
1015 Target::Static => SymbolExportKind::Data,
1016 _ => bug!(
1017 "Don't know what the export kind is for lang item of kind {:?}",
1018 l.target()
1019 ),
1020 };
1021 lang_items::required(tcx, l).then_some((name, export_kind))
1022 })
1023 .collect();
1024
1025 #[allow(rustc::potential_query_instability)]
1028 info.linked_symbols
1029 .iter_mut()
1030 .filter(|(crate_type, _)| {
1031 !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
1032 })
1033 .for_each(|(_, linked_symbols)| {
1034 let mut symbols = missing_weak_lang_items
1035 .iter()
1036 .map(|(item, export_kind)| {
1037 (
1038 add_prefix(
1039 mangle_internal_symbol(tcx, item.as_str()),
1040 *export_kind,
1041 ),
1042 *export_kind,
1043 )
1044 })
1045 .collect::<Vec<_>>();
1046 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1047 linked_symbols.extend(symbols);
1048 });
1049 }
1050
1051 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1052 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1053 true
1056 }
1057 CrateType::ProcMacro => {
1058 false
1062 }
1063 CrateType::Staticlib | CrateType::Rlib => {
1064 false
1067 }
1068 });
1069
1070 if target.is_like_msvc && embed_visualizers {
1071 info.natvis_debugger_visualizers =
1072 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1073 }
1074
1075 info
1076 }
1077}
1078
1079pub(crate) fn provide(providers: &mut Providers) {
1080 providers.backend_optimization_level = |tcx, cratenum| {
1081 let for_speed = match tcx.sess.opts.optimize {
1082 config::OptLevel::No => return config::OptLevel::No,
1089 config::OptLevel::Less => return config::OptLevel::Less,
1091 config::OptLevel::More => return config::OptLevel::More,
1092 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1093 config::OptLevel::Size => config::OptLevel::More,
1096 config::OptLevel::SizeMin => config::OptLevel::More,
1097 };
1098
1099 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1100
1101 let any_for_speed = defids.items().any(|id| {
1102 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1103 matches!(optimize, OptimizeAttr::Speed)
1104 });
1105
1106 if any_for_speed {
1107 return for_speed;
1108 }
1109
1110 tcx.sess.opts.optimize
1111 };
1112}
1113
1114pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1115 if !tcx.dep_graph.is_fully_enabled() {
1116 return CguReuse::No;
1117 }
1118
1119 let work_product_id = &cgu.work_product_id();
1120 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1121 return CguReuse::No;
1124 }
1125
1126 let dep_node = cgu.codegen_dep_node(tcx);
1133 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(&dep_node, || {
1134 format!(
1135 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1136 cgu.name()
1137 )
1138 });
1139
1140 if tcx.try_mark_green(&dep_node) {
1141 match compute_per_cgu_lto_type(
1145 &tcx.sess.lto(),
1146 &tcx.sess.opts,
1147 tcx.crate_types(),
1148 ModuleKind::Regular,
1149 ) {
1150 ComputedLtoType::No => CguReuse::PostLto,
1151 _ => CguReuse::PreLto,
1152 }
1153 } else {
1154 CguReuse::No
1155 }
1156}