1 use crate::back::metadata::create_compressed_metadata_file;
2 use crate::back::write::{
3 compute_per_cgu_lto_type, start_async_codegen, submit_codegened_module_to_llvm,
4 submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen,
6 use crate::common::{IntPredicate, RealPredicate, TypeKind};
9 use crate::mir::operand::OperandValue;
10 use crate::mir::place::PlaceRef;
12 use crate::{CachedModuleCodegen, CompiledModule, CrateInfo, MemFlags, ModuleCodegen, ModuleKind};
14 use rustc_attr as attr;
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16 use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
18 use rustc_data_structures::sync::par_iter;
19 #[cfg(parallel_compiler)]
20 use rustc_data_structures::sync::ParallelIterator;
22 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
23 use rustc_hir::lang_items::LangItem;
24 use rustc_hir::weak_lang_items::WEAK_ITEMS_SYMBOLS;
25 use rustc_index::vec::Idx;
26 use rustc_metadata::EncodedMetadata;
27 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
28 use rustc_middle::middle::exported_symbols;
29 use rustc_middle::middle::exported_symbols::SymbolExportKind;
30 use rustc_middle::middle::lang_items;
31 use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem};
32 use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout};
33 use rustc_middle::ty::query::Providers;
34 use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
35 use rustc_session::cgu_reuse_tracker::CguReuse;
36 use rustc_session::config::{self, CrateType, EntryFnType, OutputType};
37 use rustc_session::Session;
38 use rustc_span::symbol::sym;
39 use rustc_span::Symbol;
40 use rustc_span::{DebuggerVisualizerFile, DebuggerVisualizerType};
41 use rustc_target::abi::{Align, VariantIdx};
43 use std::collections::BTreeSet;
44 use std::convert::TryFrom;
45 use std::time::{Duration, Instant};
47 use itertools::Itertools;
49 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind, signed: bool) -> IntPredicate {
51 hir::BinOpKind::Eq => IntPredicate::IntEQ,
52 hir::BinOpKind::Ne => IntPredicate::IntNE,
53 hir::BinOpKind::Lt => {
60 hir::BinOpKind::Le => {
67 hir::BinOpKind::Gt => {
74 hir::BinOpKind::Ge => {
82 "comparison_op_to_icmp_predicate: expected comparison operator, \
89 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
91 hir::BinOpKind::Eq => RealPredicate::RealOEQ,
92 hir::BinOpKind::Ne => RealPredicate::RealUNE,
93 hir::BinOpKind::Lt => RealPredicate::RealOLT,
94 hir::BinOpKind::Le => RealPredicate::RealOLE,
95 hir::BinOpKind::Gt => RealPredicate::RealOGT,
96 hir::BinOpKind::Ge => RealPredicate::RealOGE,
99 "comparison_op_to_fcmp_predicate: expected comparison operator, \
107 pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
115 let signed = match t.kind() {
117 let cmp = bin_op_to_fcmp_predicate(op);
118 let cmp = bx.fcmp(cmp, lhs, rhs);
119 return bx.sext(cmp, ret_ty);
121 ty::Uint(_) => false,
123 _ => bug!("compare_simd_types: invalid SIMD type"),
126 let cmp = bin_op_to_icmp_predicate(op, signed);
127 let cmp = bx.icmp(cmp, lhs, rhs);
128 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
129 // to get the correctly sized type. This will compile to a single instruction
130 // once the IR is converted to assembly if the SIMD instruction is supported
131 // by the target architecture.
135 /// Retrieves the information we are losing (making dynamic) in an unsizing
138 /// The `old_info` argument is a bit odd. It is intended for use in an upcast,
139 /// where the new vtable for an object will be derived from the old one.
140 pub fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
144 old_info: Option<Bx::Value>,
147 let (source, target) =
148 cx.tcx().struct_lockstep_tails_erasing_lifetimes(source, target, bx.param_env());
149 match (source.kind(), target.kind()) {
150 (&ty::Array(_, len), &ty::Slice(_)) => {
151 cx.const_usize(len.eval_usize(cx.tcx(), ty::ParamEnv::reveal_all()))
153 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
155 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
156 if data_a.principal_def_id() == data_b.principal_def_id() {
157 // A NOP cast that doesn't actually change anything, should be allowed even with invalid vtables.
161 // trait upcasting coercion
164 cx.tcx().vtable_trait_upcasting_coercion_new_vptr_slot((source, target));
166 if let Some(entry_idx) = vptr_entry_idx {
167 let ptr_ty = cx.type_i8p();
168 let ptr_align = cx.tcx().data_layout.pointer_align.abi;
169 let llvtable = bx.pointercast(old_info, bx.type_ptr_to(ptr_ty));
170 let gep = bx.inbounds_gep(
173 &[bx.const_usize(u64::try_from(entry_idx).unwrap())],
175 let new_vptr = bx.load(ptr_ty, gep, ptr_align);
176 bx.nonnull_metadata(new_vptr);
177 // VTable loads are invariant.
178 bx.set_invariant_load(new_vptr);
184 (_, &ty::Dynamic(ref data, ..)) => {
185 let vtable_ptr_ty = cx.scalar_pair_element_backend_type(
186 cx.layout_of(cx.tcx().mk_mut_ptr(target)),
190 cx.const_ptrcast(meth::get_vtable(cx, source, data.principal()), vtable_ptr_ty)
192 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
196 /// Coerces `src` to `dst_ty`. `src_ty` must be a pointer.
197 pub fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
202 old_info: Option<Bx::Value>,
203 ) -> (Bx::Value, Bx::Value) {
204 debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
205 match (src_ty.kind(), dst_ty.kind()) {
206 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
207 | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
208 assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
209 let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
210 (bx.pointercast(src, ptr_ty), unsized_info(bx, a, b, old_info))
212 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
213 assert_eq!(def_a, def_b);
214 let src_layout = bx.cx().layout_of(src_ty);
215 let dst_layout = bx.cx().layout_of(dst_ty);
216 if src_ty == dst_ty {
217 return (src, old_info.unwrap());
219 let mut result = None;
220 for i in 0..src_layout.fields.count() {
221 let src_f = src_layout.field(bx.cx(), i);
226 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
227 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
228 assert_eq!(src_layout.size, src_f.size);
230 let dst_f = dst_layout.field(bx.cx(), i);
231 assert_ne!(src_f.ty, dst_f.ty);
232 assert_eq!(result, None);
233 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
235 let (lldata, llextra) = result.unwrap();
236 let lldata_ty = bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true);
237 let llextra_ty = bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true);
238 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
239 (bx.bitcast(lldata, lldata_ty), bx.bitcast(llextra, llextra_ty))
241 _ => bug!("unsize_ptr: called on bad types"),
245 /// Coerces `src`, which is a reference to a value of type `src_ty`,
246 /// to a value of type `dst_ty`, and stores the result in `dst`.
247 pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
249 src: PlaceRef<'tcx, Bx::Value>,
250 dst: PlaceRef<'tcx, Bx::Value>,
252 let src_ty = src.layout.ty;
253 let dst_ty = dst.layout.ty;
254 match (src_ty.kind(), dst_ty.kind()) {
255 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
256 let (base, info) = match bx.load_operand(src).val {
257 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
258 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
259 OperandValue::Ref(..) => bug!(),
261 OperandValue::Pair(base, info).store(bx, dst);
264 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
265 assert_eq!(def_a, def_b);
267 for i in 0..def_a.variant(VariantIdx::new(0)).fields.len() {
268 let src_f = src.project_field(bx, i);
269 let dst_f = dst.project_field(bx, i);
271 if dst_f.layout.is_zst() {
275 if src_f.layout.ty == dst_f.layout.ty {
286 coerce_unsized_into(bx, src_f, dst_f);
290 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
294 pub fn cast_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
300 cast_shift_rhs(bx, op, lhs, rhs)
303 fn cast_shift_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
309 // Shifts may have any size int on the rhs
311 let mut rhs_llty = bx.cx().val_ty(rhs);
312 let mut lhs_llty = bx.cx().val_ty(lhs);
313 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
314 rhs_llty = bx.cx().element_type(rhs_llty)
316 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
317 lhs_llty = bx.cx().element_type(lhs_llty)
319 let rhs_sz = bx.cx().int_width(rhs_llty);
320 let lhs_sz = bx.cx().int_width(lhs_llty);
322 bx.trunc(rhs, lhs_llty)
323 } else if lhs_sz > rhs_sz {
324 // FIXME (#1877: If in the future shifting by negative
325 // values is no longer undefined then this is wrong.
326 bx.zext(rhs, lhs_llty)
335 /// Returns `true` if this session's target will use SEH-based unwinding.
337 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
338 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
339 /// 64-bit MinGW) instead of "full SEH".
340 pub fn wants_msvc_seh(sess: &Session) -> bool {
341 sess.target.is_like_msvc
344 pub fn memcpy_ty<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
350 layout: TyAndLayout<'tcx>,
353 let size = layout.size.bytes();
358 bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
361 pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
362 cx: &'a Bx::CodegenCx,
363 instance: Instance<'tcx>,
365 // this is an info! to allow collecting monomorphization statistics
366 // and to allow finding the last function before LLVM aborts from
368 info!("codegen_instance({})", instance);
370 mir::codegen_mir::<Bx>(cx, instance);
373 /// Creates the `main` function which will initialize the rust runtime and call
374 /// users main function.
375 pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
376 cx: &'a Bx::CodegenCx,
377 ) -> Option<Bx::Function> {
378 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
379 let main_is_local = main_def_id.is_local();
380 let instance = Instance::mono(cx.tcx(), main_def_id);
383 // We want to create the wrapper in the same codegen unit as Rust's main
385 if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
388 } else if !cx.codegen_unit().is_primary() {
389 // We want to create the wrapper only when the codegen unit is the primary one
393 let main_llfn = cx.get_fn_addr(instance);
395 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
396 return Some(entry_fn);
398 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
399 cx: &'a Bx::CodegenCx,
400 rust_main: Bx::Value,
401 rust_main_def_id: DefId,
402 entry_type: EntryFnType,
404 // The entry function is either `int main(void)` or `int main(int argc, char **argv)`,
405 // depending on whether the target needs `argc` and `argv` to be passed in.
406 let llfty = if cx.sess().target.main_needs_argc_argv {
407 cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int())
409 cx.type_func(&[], cx.type_int())
412 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output();
413 // Given that `main()` has no arguments,
414 // then its return type cannot have
415 // late-bound regions, since late-bound
416 // regions must appear in the argument
418 let main_ret_ty = cx.tcx().normalize_erasing_regions(
419 ty::ParamEnv::reveal_all(),
420 main_ret_ty.no_bound_vars().unwrap(),
423 let Some(llfn) = cx.declare_c_main(llfty) else {
424 // FIXME: We should be smart and show a better diagnostic here.
425 let span = cx.tcx().def_span(rust_main_def_id);
427 .struct_span_err(span, "entry symbol `main` declared multiple times")
428 .help("did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead")
430 cx.sess().abort_if_errors();
434 // `main` should respect same config for frame pointer elimination as rest of code
435 cx.set_frame_pointer_type(llfn);
436 cx.apply_target_cpu_attr(llfn);
438 let llbb = Bx::append_block(&cx, llfn, "top");
439 let mut bx = Bx::build(&cx, llbb);
441 bx.insert_reference_to_gdb_debug_scripts_section_global();
443 let isize_ty = cx.type_isize();
444 let i8pp_ty = cx.type_ptr_to(cx.type_i8p());
445 let (arg_argc, arg_argv) = get_argc_argv(cx, &mut bx);
447 let (start_fn, start_ty, args) = if let EntryFnType::Main { sigpipe } = entry_type {
448 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, None);
449 let start_fn = cx.get_fn_addr(
450 ty::Instance::resolve(
452 ty::ParamEnv::reveal_all(),
454 cx.tcx().intern_substs(&[main_ret_ty.into()]),
460 let i8_ty = cx.type_i8();
461 let arg_sigpipe = bx.const_u8(sigpipe);
464 cx.type_func(&[cx.val_ty(rust_main), isize_ty, i8pp_ty, i8_ty], isize_ty);
465 (start_fn, start_ty, vec![rust_main, arg_argc, arg_argv, arg_sigpipe])
467 debug!("using user-defined start fn");
468 let start_ty = cx.type_func(&[isize_ty, i8pp_ty], isize_ty);
469 (rust_main, start_ty, vec![arg_argc, arg_argv])
472 let result = bx.call(start_ty, start_fn, &args, None);
473 let cast = bx.intcast(result, cx.type_int(), true);
480 /// Obtain the `argc` and `argv` values to pass to the rust start function.
481 fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
482 cx: &'a Bx::CodegenCx,
484 ) -> (Bx::Value, Bx::Value) {
485 if cx.sess().target.main_needs_argc_argv {
486 // Params from native `main()` used as args for rust start function
487 let param_argc = bx.get_param(0);
488 let param_argv = bx.get_param(1);
489 let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
490 let arg_argv = param_argv;
493 // The Rust start function doesn't need `argc` and `argv`, so just pass zeros.
494 let arg_argc = bx.const_int(cx.type_int(), 0);
495 let arg_argv = bx.const_null(cx.type_ptr_to(cx.type_i8p()));
500 /// This function returns all of the debugger visualizers specified for the
501 /// current crate as well as all upstream crates transitively that match the
502 /// `visualizer_type` specified.
503 pub fn collect_debugger_visualizers_transitive(
505 visualizer_type: DebuggerVisualizerType,
506 ) -> BTreeSet<DebuggerVisualizerFile> {
507 tcx.debugger_visualizers(LOCAL_CRATE)
513 let used_crate_source = tcx.used_crate_source(*cnum);
514 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
516 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
518 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
520 .collect::<BTreeSet<_>>()
523 pub fn codegen_crate<B: ExtraBackendMethods>(
527 metadata: EncodedMetadata,
528 need_metadata_module: bool,
529 ) -> OngoingCodegen<B> {
530 // Skip crate items and just output metadata in -Z no-codegen mode.
531 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
532 let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, metadata, None, 1);
534 ongoing_codegen.codegen_finished(tcx);
536 ongoing_codegen.check_for_errors(tcx.sess);
538 return ongoing_codegen;
541 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
543 // Run the monomorphization collector and partition the collected items into
545 let codegen_units = tcx.collect_and_partition_mono_items(()).1;
547 // Force all codegen_unit queries so they are already either red or green
548 // when compile_codegen_unit accesses them. We are not able to re-execute
549 // the codegen_unit query from just the DepNode, so an unknown color would
550 // lead to having to re-execute compile_codegen_unit, possibly
552 if tcx.dep_graph.is_fully_enabled() {
553 for cgu in codegen_units {
554 tcx.ensure().codegen_unit(cgu.name());
558 let metadata_module = if need_metadata_module {
559 // Emit compressed metadata object.
560 let metadata_cgu_name =
561 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
562 tcx.sess.time("write_compressed_metadata", || {
564 tcx.output_filenames(()).temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
565 let data = create_compressed_metadata_file(
568 &exported_symbols::metadata_symbol_name(tcx),
570 if let Err(err) = std::fs::write(&file_name, data) {
571 tcx.sess.fatal(&format!("error writing metadata object file: {}", err));
573 Some(CompiledModule {
574 name: metadata_cgu_name,
575 kind: ModuleKind::Metadata,
576 object: Some(file_name),
585 let ongoing_codegen = start_async_codegen(
594 // Codegen an allocator shim, if necessary.
596 // If the crate doesn't have an `allocator_kind` set then there's definitely
597 // no shim to generate. Otherwise we also check our dependency graph for all
598 // our output crate types. If anything there looks like its a `Dynamic`
599 // linkage, then it's already got an allocator shim and we'll be using that
600 // one instead. If nothing exists then it's our job to generate the
602 let any_dynamic_crate = tcx.dependency_formats(()).iter().any(|(_, list)| {
603 use rustc_middle::middle::dependency_format::Linkage;
604 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
606 let allocator_module = if any_dynamic_crate {
608 } else if let Some(kind) = tcx.allocator_kind(()) {
610 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
611 let module_llvm = tcx.sess.time("write_allocator_module", || {
612 backend.codegen_allocator(tcx, &llmod_id, kind, tcx.lang_items().oom().is_some())
615 Some(ModuleCodegen { name: llmod_id, module_llvm, kind: ModuleKind::Allocator })
620 if let Some(allocator_module) = allocator_module {
621 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
624 // For better throughput during parallel processing by LLVM, we used to sort
625 // CGUs largest to smallest. This would lead to better thread utilization
626 // by, for example, preventing a large CGU from being processed last and
627 // having only one LLVM thread working while the rest remained idle.
629 // However, this strategy would lead to high memory usage, as it meant the
630 // LLVM-IR for all of the largest CGUs would be resident in memory at once.
632 // Instead, we can compromise by ordering CGUs such that the largest and
633 // smallest are first, second largest and smallest are next, etc. If there
634 // are large size variations, this can reduce memory usage significantly.
635 let codegen_units: Vec<_> = {
636 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
637 sorted_cgus.sort_by_cached_key(|cgu| cgu.size_estimate());
639 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
640 second_half.iter().rev().interleave(first_half).copied().collect()
643 // Calculate the CGU reuse
644 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
645 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, &cgu)).collect::<Vec<_>>()
648 let mut total_codegen_time = Duration::new(0, 0);
649 let start_rss = tcx.sess.time_passes().then(|| get_resident_set_size());
651 // The non-parallel compiler can only translate codegen units to LLVM IR
652 // on a single thread, leading to a staircase effect where the N LLVM
653 // threads have to wait on the single codegen threads to generate work
654 // for them. The parallel compiler does not have this restriction, so
655 // we can pre-load the LLVM queue in parallel before handing off
656 // coordination to the OnGoingCodegen scheduler.
658 // This likely is a temporary measure. Once we don't have to support the
659 // non-parallel compiler anymore, we can compile CGUs end-to-end in
660 // parallel and get rid of the complicated scheduling logic.
661 let mut pre_compiled_cgus = if cfg!(parallel_compiler) {
662 tcx.sess.time("compile_first_CGU_batch", || {
663 // Try to find one CGU to compile per thread.
664 let cgus: Vec<_> = cgu_reuse
667 .filter(|&(_, reuse)| reuse == &CguReuse::No)
668 .take(tcx.sess.threads())
671 // Compile the found CGUs in parallel.
672 let start_time = Instant::now();
674 let pre_compiled_cgus = par_iter(cgus)
676 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
681 total_codegen_time += start_time.elapsed();
689 for (i, cgu) in codegen_units.iter().enumerate() {
690 ongoing_codegen.wait_for_signal_to_codegen_item();
691 ongoing_codegen.check_for_errors(tcx.sess);
693 let cgu_reuse = cgu_reuse[i];
694 tcx.sess.cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
698 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
701 let start_time = Instant::now();
702 let module = backend.compile_codegen_unit(tcx, cgu.name());
703 total_codegen_time += start_time.elapsed();
706 // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`
707 // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes
708 // compilation hang on post-monomorphization errors.
709 tcx.sess.abort_if_errors();
711 submit_codegened_module_to_llvm(
713 &ongoing_codegen.coordinator.sender,
719 CguReuse::PreLto => {
720 submit_pre_lto_module_to_llvm(
723 &ongoing_codegen.coordinator.sender,
724 CachedModuleCodegen {
725 name: cgu.name().to_string(),
726 source: cgu.previous_work_product(tcx),
731 CguReuse::PostLto => {
732 submit_post_lto_module_to_llvm(
734 &ongoing_codegen.coordinator.sender,
735 CachedModuleCodegen {
736 name: cgu.name().to_string(),
737 source: cgu.previous_work_product(tcx),
745 ongoing_codegen.codegen_finished(tcx);
747 // Since the main thread is sometimes blocked during codegen, we keep track
748 // -Ztime-passes output manually.
749 if tcx.sess.time_passes() {
750 let end_rss = get_resident_set_size();
752 print_time_passes_entry(
753 "codegen_to_LLVM_IR",
760 ongoing_codegen.check_for_errors(tcx.sess);
765 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
766 let exported_symbols = tcx
770 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
772 let linked_symbols = tcx
776 .map(|&c| (c, crate::back::linker::linked_symbols(tcx, c)))
778 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
779 let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
780 let subsystem = tcx.sess.first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
781 let windows_subsystem = subsystem.map(|subsystem| {
782 if subsystem != sym::windows && subsystem != sym::console {
783 tcx.sess.fatal(&format!(
784 "invalid windows subsystem `{}`, only \
785 `windows` and `console` are allowed",
789 subsystem.to_string()
792 // This list is used when generating the command line to pass through to
793 // system linker. The linker expects undefined symbols on the left of the
794 // command line to be defined in libraries on the right, not the other way
795 // around. For more info, see some comments in the add_used_library function
798 // In order to get this left-to-right dependency ordering, we use the reverse
799 // postorder of all crates putting the leaves at the right-most positions.
800 let used_crates = tcx
805 .filter(|&cnum| !tcx.dep_kind(cnum).macros_only())
808 let mut info = CrateInfo {
813 compiler_builtins: None,
814 profiler_runtime: None,
815 is_no_builtins: Default::default(),
816 native_libraries: Default::default(),
817 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
818 crate_name: Default::default(),
820 used_crate_source: Default::default(),
821 dependency_formats: tcx.dependency_formats(()).clone(),
823 natvis_debugger_visualizers: Default::default(),
825 let crates = tcx.crates(());
827 let n_crates = crates.len();
828 info.native_libraries.reserve(n_crates);
829 info.crate_name.reserve(n_crates);
830 info.used_crate_source.reserve(n_crates);
832 for &cnum in crates.iter() {
833 info.native_libraries
834 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
835 info.crate_name.insert(cnum, tcx.crate_name(cnum));
837 let used_crate_source = tcx.used_crate_source(cnum);
838 info.used_crate_source.insert(cnum, used_crate_source.clone());
839 if tcx.is_compiler_builtins(cnum) {
840 info.compiler_builtins = Some(cnum);
842 if tcx.is_profiler_runtime(cnum) {
843 info.profiler_runtime = Some(cnum);
845 if tcx.is_no_builtins(cnum) {
846 info.is_no_builtins.insert(cnum);
850 // Handle circular dependencies in the standard library.
851 // See comment before `add_linked_symbol_object` function for the details.
852 // With msvc-like linkers it's both unnecessary (they support circular dependencies),
853 // and causes linking issues (when weak lang item symbols are "privatized" by LTO).
854 let target = &tcx.sess.target;
855 if !target.is_like_msvc {
856 let missing_weak_lang_items: FxHashSet<&Symbol> = info
860 tcx.missing_lang_items(*cnum)
862 .filter(|l| lang_items::required(tcx, **l))
863 .filter_map(|item| WEAK_ITEMS_SYMBOLS.get(item))
866 let prefix = if target.is_like_windows && target.arch == "x86" { "_" } else { "" };
869 .filter(|(crate_type, _)| {
870 !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
872 .for_each(|(_, linked_symbols)| {
873 linked_symbols.extend(
874 missing_weak_lang_items
876 .map(|item| (format!("{prefix}{item}"), SymbolExportKind::Text)),
881 let embed_visualizers = tcx.sess.crate_types().iter().any(|&crate_type| match crate_type {
882 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib => {
883 // These are crate types for which we invoke the linker and can embed
884 // NatVis visualizers.
887 CrateType::ProcMacro => {
888 // We could embed NatVis for proc macro crates too (to improve the debugging
889 // experience for them) but it does not seem like a good default, since
890 // this is a rare use case and we don't want to slow down the common case.
893 CrateType::Staticlib | CrateType::Rlib => {
894 // We don't invoke the linker for these, so we don't need to collect the NatVis for them.
899 if target.is_like_msvc && embed_visualizers {
900 info.natvis_debugger_visualizers =
901 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
908 pub fn provide(providers: &mut Providers) {
909 providers.backend_optimization_level = |tcx, cratenum| {
910 let for_speed = match tcx.sess.opts.optimize {
911 // If globally no optimisation is done, #[optimize] has no effect.
913 // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the
914 // pass manager and it is likely that some module-wide passes (such as inliner or
915 // cross-function constant propagation) would ignore the `optnone` annotation we put
916 // on the functions, thus necessarily involving these functions into optimisations.
917 config::OptLevel::No => return config::OptLevel::No,
918 // If globally optimise-speed is already specified, just use that level.
919 config::OptLevel::Less => return config::OptLevel::Less,
920 config::OptLevel::Default => return config::OptLevel::Default,
921 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
922 // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)
924 config::OptLevel::Size => config::OptLevel::Default,
925 config::OptLevel::SizeMin => config::OptLevel::Default,
928 let (defids, _) = tcx.collect_and_partition_mono_items(cratenum);
930 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
932 attr::OptimizeAttr::None => continue,
933 attr::OptimizeAttr::Size => continue,
934 attr::OptimizeAttr::Speed => {
939 tcx.sess.opts.optimize
943 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
944 if !tcx.dep_graph.is_fully_enabled() {
948 let work_product_id = &cgu.work_product_id();
949 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
950 // We don't have anything cached for this CGU. This can happen
951 // if the CGU did not exist in the previous session.
955 // Try to mark the CGU as green. If it we can do so, it means that nothing
956 // affecting the LLVM module has changed and we can re-use a cached version.
957 // If we compile with any kind of LTO, this means we can re-use the bitcode
958 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
959 // know that later). If we are not doing LTO, there is only one optimized
960 // version of each module, so we re-use that.
961 let dep_node = cgu.codegen_dep_node(tcx);
963 !tcx.dep_graph.dep_node_exists(&dep_node),
964 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
968 if tcx.try_mark_green(&dep_node) {
969 // We can re-use either the pre- or the post-thinlto state. If no LTO is
970 // being performed then we can use post-LTO artifacts, otherwise we must
971 // reuse pre-LTO artifacts
972 match compute_per_cgu_lto_type(
975 &tcx.sess.crate_types(),
978 ComputedLtoType::No => CguReuse::PostLto,
979 _ => CguReuse::PreLto,