]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/base.rs
Auto merge of #103797 - Dylan-DPC:rollup-ps589fi, r=Dylan-DPC
[rust.git] / compiler / rustc_codegen_ssa / src / base.rs
1 use crate::back::link::are_upstream_rust_objects_already_included;
2 use crate::back::metadata::create_compressed_metadata_file;
3 use crate::back::write::{
4     compute_per_cgu_lto_type, start_async_codegen, submit_codegened_module_to_llvm,
5     submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen,
6 };
7 use crate::common::{IntPredicate, RealPredicate, TypeKind};
8 use crate::meth;
9 use crate::mir;
10 use crate::mir::operand::OperandValue;
11 use crate::mir::place::PlaceRef;
12 use crate::traits::*;
13 use crate::{CachedModuleCodegen, CompiledModule, CrateInfo, MemFlags, ModuleCodegen, ModuleKind};
14
15 use rustc_attr as attr;
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
18
19 use rustc_data_structures::sync::par_iter;
20 #[cfg(parallel_compiler)]
21 use rustc_data_structures::sync::ParallelIterator;
22 use rustc_hir as hir;
23 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
24 use rustc_hir::lang_items::LangItem;
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, Size, VariantIdx};
42
43 use std::collections::BTreeSet;
44 use std::convert::TryFrom;
45 use std::time::{Duration, Instant};
46
47 use itertools::Itertools;
48
49 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind, signed: bool) -> IntPredicate {
50     match op {
51         hir::BinOpKind::Eq => IntPredicate::IntEQ,
52         hir::BinOpKind::Ne => IntPredicate::IntNE,
53         hir::BinOpKind::Lt => {
54             if signed {
55                 IntPredicate::IntSLT
56             } else {
57                 IntPredicate::IntULT
58             }
59         }
60         hir::BinOpKind::Le => {
61             if signed {
62                 IntPredicate::IntSLE
63             } else {
64                 IntPredicate::IntULE
65             }
66         }
67         hir::BinOpKind::Gt => {
68             if signed {
69                 IntPredicate::IntSGT
70             } else {
71                 IntPredicate::IntUGT
72             }
73         }
74         hir::BinOpKind::Ge => {
75             if signed {
76                 IntPredicate::IntSGE
77             } else {
78                 IntPredicate::IntUGE
79             }
80         }
81         op => bug!(
82             "comparison_op_to_icmp_predicate: expected comparison operator, \
83              found {:?}",
84             op
85         ),
86     }
87 }
88
89 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
90     match op {
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,
97         op => {
98             bug!(
99                 "comparison_op_to_fcmp_predicate: expected comparison operator, \
100                  found {:?}",
101                 op
102             );
103         }
104     }
105 }
106
107 pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
108     bx: &mut Bx,
109     lhs: Bx::Value,
110     rhs: Bx::Value,
111     t: Ty<'tcx>,
112     ret_ty: Bx::Type,
113     op: hir::BinOpKind,
114 ) -> Bx::Value {
115     let signed = match t.kind() {
116         ty::Float(_) => {
117             let cmp = bin_op_to_fcmp_predicate(op);
118             let cmp = bx.fcmp(cmp, lhs, rhs);
119             return bx.sext(cmp, ret_ty);
120         }
121         ty::Uint(_) => false,
122         ty::Int(_) => true,
123         _ => bug!("compare_simd_types: invalid SIMD type"),
124     };
125
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.
132     bx.sext(cmp, ret_ty)
133 }
134
135 /// Retrieves the information we are losing (making dynamic) in an unsizing
136 /// adjustment.
137 ///
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>>(
141     bx: &mut Bx,
142     source: Ty<'tcx>,
143     target: Ty<'tcx>,
144     old_info: Option<Bx::Value>,
145 ) -> Bx::Value {
146     let cx = bx.cx();
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()))
152         }
153         (
154             &ty::Dynamic(ref data_a, _, src_dyn_kind),
155             &ty::Dynamic(ref data_b, _, target_dyn_kind),
156         ) => {
157             assert_eq!(src_dyn_kind, target_dyn_kind);
158
159             let old_info =
160                 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
161             if data_a.principal_def_id() == data_b.principal_def_id() {
162                 // A NOP cast that doesn't actually change anything, should be allowed even with invalid vtables.
163                 return old_info;
164             }
165
166             // trait upcasting coercion
167
168             let vptr_entry_idx =
169                 cx.tcx().vtable_trait_upcasting_coercion_new_vptr_slot((source, target));
170
171             if let Some(entry_idx) = vptr_entry_idx {
172                 let ptr_ty = cx.type_i8p();
173                 let ptr_align = cx.tcx().data_layout.pointer_align.abi;
174                 let vtable_ptr_ty = vtable_ptr_ty(cx, target, target_dyn_kind);
175                 let llvtable = bx.pointercast(old_info, bx.type_ptr_to(ptr_ty));
176                 let gep = bx.inbounds_gep(
177                     ptr_ty,
178                     llvtable,
179                     &[bx.const_usize(u64::try_from(entry_idx).unwrap())],
180                 );
181                 let new_vptr = bx.load(ptr_ty, gep, ptr_align);
182                 bx.nonnull_metadata(new_vptr);
183                 // VTable loads are invariant.
184                 bx.set_invariant_load(new_vptr);
185                 bx.pointercast(new_vptr, vtable_ptr_ty)
186             } else {
187                 old_info
188             }
189         }
190         (_, &ty::Dynamic(ref data, _, target_dyn_kind)) => {
191             let vtable_ptr_ty = vtable_ptr_ty(cx, target, target_dyn_kind);
192             cx.const_ptrcast(meth::get_vtable(cx, source, data.principal()), vtable_ptr_ty)
193         }
194         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
195     }
196 }
197
198 // Returns the vtable pointer type of a `dyn` or `dyn*` type
199 fn vtable_ptr_ty<'tcx, Cx: CodegenMethods<'tcx>>(
200     cx: &Cx,
201     target: Ty<'tcx>,
202     kind: ty::DynKind,
203 ) -> <Cx as BackendTypes>::Type {
204     cx.scalar_pair_element_backend_type(
205         cx.layout_of(match kind {
206             // vtable is the second field of `*mut dyn Trait`
207             ty::Dyn => cx.tcx().mk_mut_ptr(target),
208             // vtable is the second field of `dyn* Trait`
209             ty::DynStar => target,
210         }),
211         1,
212         true,
213     )
214 }
215
216 /// Coerces `src` to `dst_ty`. `src_ty` must be a pointer.
217 pub fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
218     bx: &mut Bx,
219     src: Bx::Value,
220     src_ty: Ty<'tcx>,
221     dst_ty: Ty<'tcx>,
222     old_info: Option<Bx::Value>,
223 ) -> (Bx::Value, Bx::Value) {
224     debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
225     match (src_ty.kind(), dst_ty.kind()) {
226         (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
227         | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
228             assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
229             let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
230             (bx.pointercast(src, ptr_ty), unsized_info(bx, a, b, old_info))
231         }
232         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
233             assert_eq!(def_a, def_b);
234             let src_layout = bx.cx().layout_of(src_ty);
235             let dst_layout = bx.cx().layout_of(dst_ty);
236             if src_ty == dst_ty {
237                 return (src, old_info.unwrap());
238             }
239             let mut result = None;
240             for i in 0..src_layout.fields.count() {
241                 let src_f = src_layout.field(bx.cx(), i);
242                 if src_f.is_zst() {
243                     continue;
244                 }
245
246                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
247                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
248                 assert_eq!(src_layout.size, src_f.size);
249
250                 let dst_f = dst_layout.field(bx.cx(), i);
251                 assert_ne!(src_f.ty, dst_f.ty);
252                 assert_eq!(result, None);
253                 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
254             }
255             let (lldata, llextra) = result.unwrap();
256             let lldata_ty = bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true);
257             let llextra_ty = bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true);
258             // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
259             (bx.bitcast(lldata, lldata_ty), bx.bitcast(llextra, llextra_ty))
260         }
261         _ => bug!("unsize_ptr: called on bad types"),
262     }
263 }
264
265 /// Coerces `src` to `dst_ty` which is guaranteed to be a `dyn*` type.
266 pub fn cast_to_dyn_star<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
267     bx: &mut Bx,
268     src: Bx::Value,
269     src_ty_and_layout: TyAndLayout<'tcx>,
270     dst_ty: Ty<'tcx>,
271     old_info: Option<Bx::Value>,
272 ) -> (Bx::Value, Bx::Value) {
273     debug!("cast_to_dyn_star: {:?} => {:?}", src_ty_and_layout.ty, dst_ty);
274     assert!(
275         matches!(dst_ty.kind(), ty::Dynamic(_, _, ty::DynStar)),
276         "destination type must be a dyn*"
277     );
278     // FIXME(dyn-star): this is probably not the best way to check if this is
279     // a pointer, and really we should ensure that the value is a suitable
280     // pointer earlier in the compilation process.
281     let src = match src_ty_and_layout.pointee_info_at(bx.cx(), Size::ZERO) {
282         Some(_) => bx.ptrtoint(src, bx.cx().type_isize()),
283         None => bx.bitcast(src, bx.type_isize()),
284     };
285     (src, unsized_info(bx, src_ty_and_layout.ty, dst_ty, old_info))
286 }
287
288 /// Coerces `src`, which is a reference to a value of type `src_ty`,
289 /// to a value of type `dst_ty`, and stores the result in `dst`.
290 pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
291     bx: &mut Bx,
292     src: PlaceRef<'tcx, Bx::Value>,
293     dst: PlaceRef<'tcx, Bx::Value>,
294 ) {
295     let src_ty = src.layout.ty;
296     let dst_ty = dst.layout.ty;
297     match (src_ty.kind(), dst_ty.kind()) {
298         (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
299             let (base, info) = match bx.load_operand(src).val {
300                 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
301                 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
302                 OperandValue::Ref(..) => bug!(),
303             };
304             OperandValue::Pair(base, info).store(bx, dst);
305         }
306
307         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
308             assert_eq!(def_a, def_b);
309
310             for i in 0..def_a.variant(VariantIdx::new(0)).fields.len() {
311                 let src_f = src.project_field(bx, i);
312                 let dst_f = dst.project_field(bx, i);
313
314                 if dst_f.layout.is_zst() {
315                     continue;
316                 }
317
318                 if src_f.layout.ty == dst_f.layout.ty {
319                     memcpy_ty(
320                         bx,
321                         dst_f.llval,
322                         dst_f.align,
323                         src_f.llval,
324                         src_f.align,
325                         src_f.layout,
326                         MemFlags::empty(),
327                     );
328                 } else {
329                     coerce_unsized_into(bx, src_f, dst_f);
330                 }
331             }
332         }
333         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
334     }
335 }
336
337 pub fn cast_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
338     bx: &mut Bx,
339     lhs: Bx::Value,
340     rhs: Bx::Value,
341 ) -> Bx::Value {
342     // Shifts may have any size int on the rhs
343     let mut rhs_llty = bx.cx().val_ty(rhs);
344     let mut lhs_llty = bx.cx().val_ty(lhs);
345     if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
346         rhs_llty = bx.cx().element_type(rhs_llty)
347     }
348     if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
349         lhs_llty = bx.cx().element_type(lhs_llty)
350     }
351     let rhs_sz = bx.cx().int_width(rhs_llty);
352     let lhs_sz = bx.cx().int_width(lhs_llty);
353     if lhs_sz < rhs_sz {
354         bx.trunc(rhs, lhs_llty)
355     } else if lhs_sz > rhs_sz {
356         // FIXME (#1877: If in the future shifting by negative
357         // values is no longer undefined then this is wrong.
358         bx.zext(rhs, lhs_llty)
359     } else {
360         rhs
361     }
362 }
363
364 /// Returns `true` if this session's target will use SEH-based unwinding.
365 ///
366 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
367 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
368 /// 64-bit MinGW) instead of "full SEH".
369 pub fn wants_msvc_seh(sess: &Session) -> bool {
370     sess.target.is_like_msvc
371 }
372
373 pub fn memcpy_ty<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
374     bx: &mut Bx,
375     dst: Bx::Value,
376     dst_align: Align,
377     src: Bx::Value,
378     src_align: Align,
379     layout: TyAndLayout<'tcx>,
380     flags: MemFlags,
381 ) {
382     let size = layout.size.bytes();
383     if size == 0 {
384         return;
385     }
386
387     bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
388 }
389
390 pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
391     cx: &'a Bx::CodegenCx,
392     instance: Instance<'tcx>,
393 ) {
394     // this is an info! to allow collecting monomorphization statistics
395     // and to allow finding the last function before LLVM aborts from
396     // release builds.
397     info!("codegen_instance({})", instance);
398
399     mir::codegen_mir::<Bx>(cx, instance);
400 }
401
402 /// Creates the `main` function which will initialize the rust runtime and call
403 /// users main function.
404 pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
405     cx: &'a Bx::CodegenCx,
406 ) -> Option<Bx::Function> {
407     let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
408     let main_is_local = main_def_id.is_local();
409     let instance = Instance::mono(cx.tcx(), main_def_id);
410
411     if main_is_local {
412         // We want to create the wrapper in the same codegen unit as Rust's main
413         // function.
414         if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
415             return None;
416         }
417     } else if !cx.codegen_unit().is_primary() {
418         // We want to create the wrapper only when the codegen unit is the primary one
419         return None;
420     }
421
422     let main_llfn = cx.get_fn_addr(instance);
423
424     let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
425     return Some(entry_fn);
426
427     fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
428         cx: &'a Bx::CodegenCx,
429         rust_main: Bx::Value,
430         rust_main_def_id: DefId,
431         entry_type: EntryFnType,
432     ) -> Bx::Function {
433         // The entry function is either `int main(void)` or `int main(int argc, char **argv)`,
434         // depending on whether the target needs `argc` and `argv` to be passed in.
435         let llfty = if cx.sess().target.main_needs_argc_argv {
436             cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int())
437         } else {
438             cx.type_func(&[], cx.type_int())
439         };
440
441         let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output();
442         // Given that `main()` has no arguments,
443         // then its return type cannot have
444         // late-bound regions, since late-bound
445         // regions must appear in the argument
446         // listing.
447         let main_ret_ty = cx.tcx().normalize_erasing_regions(
448             ty::ParamEnv::reveal_all(),
449             main_ret_ty.no_bound_vars().unwrap(),
450         );
451
452         let Some(llfn) = cx.declare_c_main(llfty) else {
453             // FIXME: We should be smart and show a better diagnostic here.
454             let span = cx.tcx().def_span(rust_main_def_id);
455             cx.sess()
456                 .struct_span_err(span, "entry symbol `main` declared multiple times")
457                 .help("did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead")
458                 .emit();
459             cx.sess().abort_if_errors();
460             bug!();
461         };
462
463         // `main` should respect same config for frame pointer elimination as rest of code
464         cx.set_frame_pointer_type(llfn);
465         cx.apply_target_cpu_attr(llfn);
466
467         let llbb = Bx::append_block(&cx, llfn, "top");
468         let mut bx = Bx::build(&cx, llbb);
469
470         bx.insert_reference_to_gdb_debug_scripts_section_global();
471
472         let isize_ty = cx.type_isize();
473         let i8pp_ty = cx.type_ptr_to(cx.type_i8p());
474         let (arg_argc, arg_argv) = get_argc_argv(cx, &mut bx);
475
476         let (start_fn, start_ty, args) = if let EntryFnType::Main { sigpipe } = entry_type {
477             let start_def_id = cx.tcx().require_lang_item(LangItem::Start, None);
478             let start_fn = cx.get_fn_addr(
479                 ty::Instance::resolve(
480                     cx.tcx(),
481                     ty::ParamEnv::reveal_all(),
482                     start_def_id,
483                     cx.tcx().intern_substs(&[main_ret_ty.into()]),
484                 )
485                 .unwrap()
486                 .unwrap(),
487             );
488
489             let i8_ty = cx.type_i8();
490             let arg_sigpipe = bx.const_u8(sigpipe);
491
492             let start_ty =
493                 cx.type_func(&[cx.val_ty(rust_main), isize_ty, i8pp_ty, i8_ty], isize_ty);
494             (start_fn, start_ty, vec![rust_main, arg_argc, arg_argv, arg_sigpipe])
495         } else {
496             debug!("using user-defined start fn");
497             let start_ty = cx.type_func(&[isize_ty, i8pp_ty], isize_ty);
498             (rust_main, start_ty, vec![arg_argc, arg_argv])
499         };
500
501         let result = bx.call(start_ty, None, start_fn, &args, None);
502         let cast = bx.intcast(result, cx.type_int(), true);
503         bx.ret(cast);
504
505         llfn
506     }
507 }
508
509 /// Obtain the `argc` and `argv` values to pass to the rust start function.
510 fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
511     cx: &'a Bx::CodegenCx,
512     bx: &mut Bx,
513 ) -> (Bx::Value, Bx::Value) {
514     if cx.sess().target.main_needs_argc_argv {
515         // Params from native `main()` used as args for rust start function
516         let param_argc = bx.get_param(0);
517         let param_argv = bx.get_param(1);
518         let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
519         let arg_argv = param_argv;
520         (arg_argc, arg_argv)
521     } else {
522         // The Rust start function doesn't need `argc` and `argv`, so just pass zeros.
523         let arg_argc = bx.const_int(cx.type_int(), 0);
524         let arg_argv = bx.const_null(cx.type_ptr_to(cx.type_i8p()));
525         (arg_argc, arg_argv)
526     }
527 }
528
529 /// This function returns all of the debugger visualizers specified for the
530 /// current crate as well as all upstream crates transitively that match the
531 /// `visualizer_type` specified.
532 pub fn collect_debugger_visualizers_transitive(
533     tcx: TyCtxt<'_>,
534     visualizer_type: DebuggerVisualizerType,
535 ) -> BTreeSet<DebuggerVisualizerFile> {
536     tcx.debugger_visualizers(LOCAL_CRATE)
537         .iter()
538         .chain(
539             tcx.crates(())
540                 .iter()
541                 .filter(|&cnum| {
542                     let used_crate_source = tcx.used_crate_source(*cnum);
543                     used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
544                 })
545                 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
546         )
547         .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
548         .cloned()
549         .collect::<BTreeSet<_>>()
550 }
551
552 pub fn codegen_crate<B: ExtraBackendMethods>(
553     backend: B,
554     tcx: TyCtxt<'_>,
555     target_cpu: String,
556     metadata: EncodedMetadata,
557     need_metadata_module: bool,
558 ) -> OngoingCodegen<B> {
559     // Skip crate items and just output metadata in -Z no-codegen mode.
560     if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
561         let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, metadata, None, 1);
562
563         ongoing_codegen.codegen_finished(tcx);
564
565         ongoing_codegen.check_for_errors(tcx.sess);
566
567         return ongoing_codegen;
568     }
569
570     let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
571
572     // Run the monomorphization collector and partition the collected items into
573     // codegen units.
574     let codegen_units = tcx.collect_and_partition_mono_items(()).1;
575
576     // Force all codegen_unit queries so they are already either red or green
577     // when compile_codegen_unit accesses them. We are not able to re-execute
578     // the codegen_unit query from just the DepNode, so an unknown color would
579     // lead to having to re-execute compile_codegen_unit, possibly
580     // unnecessarily.
581     if tcx.dep_graph.is_fully_enabled() {
582         for cgu in codegen_units {
583             tcx.ensure().codegen_unit(cgu.name());
584         }
585     }
586
587     let metadata_module = if need_metadata_module {
588         // Emit compressed metadata object.
589         let metadata_cgu_name =
590             cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
591         tcx.sess.time("write_compressed_metadata", || {
592             let file_name =
593                 tcx.output_filenames(()).temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
594             let data = create_compressed_metadata_file(
595                 tcx.sess,
596                 &metadata,
597                 &exported_symbols::metadata_symbol_name(tcx),
598             );
599             if let Err(err) = std::fs::write(&file_name, data) {
600                 tcx.sess.fatal(&format!("error writing metadata object file: {}", err));
601             }
602             Some(CompiledModule {
603                 name: metadata_cgu_name,
604                 kind: ModuleKind::Metadata,
605                 object: Some(file_name),
606                 dwarf_object: None,
607                 bytecode: None,
608             })
609         })
610     } else {
611         None
612     };
613
614     let ongoing_codegen = start_async_codegen(
615         backend.clone(),
616         tcx,
617         target_cpu,
618         metadata,
619         metadata_module,
620         codegen_units.len(),
621     );
622
623     // Codegen an allocator shim, if necessary.
624     //
625     // If the crate doesn't have an `allocator_kind` set then there's definitely
626     // no shim to generate. Otherwise we also check our dependency graph for all
627     // our output crate types. If anything there looks like its a `Dynamic`
628     // linkage, then it's already got an allocator shim and we'll be using that
629     // one instead. If nothing exists then it's our job to generate the
630     // allocator!
631     let any_dynamic_crate = tcx.dependency_formats(()).iter().any(|(_, list)| {
632         use rustc_middle::middle::dependency_format::Linkage;
633         list.iter().any(|&linkage| linkage == Linkage::Dynamic)
634     });
635     let allocator_module = if any_dynamic_crate {
636         None
637     } else if let Some(kind) = tcx.allocator_kind(()) {
638         let llmod_id =
639             cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
640         let module_llvm = tcx.sess.time("write_allocator_module", || {
641             backend.codegen_allocator(tcx, &llmod_id, kind, tcx.lang_items().oom().is_some())
642         });
643
644         Some(ModuleCodegen { name: llmod_id, module_llvm, kind: ModuleKind::Allocator })
645     } else {
646         None
647     };
648
649     if let Some(allocator_module) = allocator_module {
650         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
651     }
652
653     // For better throughput during parallel processing by LLVM, we used to sort
654     // CGUs largest to smallest. This would lead to better thread utilization
655     // by, for example, preventing a large CGU from being processed last and
656     // having only one LLVM thread working while the rest remained idle.
657     //
658     // However, this strategy would lead to high memory usage, as it meant the
659     // LLVM-IR for all of the largest CGUs would be resident in memory at once.
660     //
661     // Instead, we can compromise by ordering CGUs such that the largest and
662     // smallest are first, second largest and smallest are next, etc. If there
663     // are large size variations, this can reduce memory usage significantly.
664     let codegen_units: Vec<_> = {
665         let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
666         sorted_cgus.sort_by_cached_key(|cgu| cgu.size_estimate());
667
668         let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
669         second_half.iter().rev().interleave(first_half).copied().collect()
670     };
671
672     // Calculate the CGU reuse
673     let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
674         codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, &cgu)).collect::<Vec<_>>()
675     });
676
677     let mut total_codegen_time = Duration::new(0, 0);
678     let start_rss = tcx.sess.time_passes().then(|| get_resident_set_size());
679
680     // The non-parallel compiler can only translate codegen units to LLVM IR
681     // on a single thread, leading to a staircase effect where the N LLVM
682     // threads have to wait on the single codegen threads to generate work
683     // for them. The parallel compiler does not have this restriction, so
684     // we can pre-load the LLVM queue in parallel before handing off
685     // coordination to the OnGoingCodegen scheduler.
686     //
687     // This likely is a temporary measure. Once we don't have to support the
688     // non-parallel compiler anymore, we can compile CGUs end-to-end in
689     // parallel and get rid of the complicated scheduling logic.
690     let mut pre_compiled_cgus = if cfg!(parallel_compiler) {
691         tcx.sess.time("compile_first_CGU_batch", || {
692             // Try to find one CGU to compile per thread.
693             let cgus: Vec<_> = cgu_reuse
694                 .iter()
695                 .enumerate()
696                 .filter(|&(_, reuse)| reuse == &CguReuse::No)
697                 .take(tcx.sess.threads())
698                 .collect();
699
700             // Compile the found CGUs in parallel.
701             let start_time = Instant::now();
702
703             let pre_compiled_cgus = par_iter(cgus)
704                 .map(|(i, _)| {
705                     let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
706                     (i, module)
707                 })
708                 .collect();
709
710             total_codegen_time += start_time.elapsed();
711
712             pre_compiled_cgus
713         })
714     } else {
715         FxHashMap::default()
716     };
717
718     for (i, cgu) in codegen_units.iter().enumerate() {
719         ongoing_codegen.wait_for_signal_to_codegen_item();
720         ongoing_codegen.check_for_errors(tcx.sess);
721
722         let cgu_reuse = cgu_reuse[i];
723         tcx.sess.cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
724
725         match cgu_reuse {
726             CguReuse::No => {
727                 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
728                     cgu
729                 } else {
730                     let start_time = Instant::now();
731                     let module = backend.compile_codegen_unit(tcx, cgu.name());
732                     total_codegen_time += start_time.elapsed();
733                     module
734                 };
735                 // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`
736                 // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes
737                 // compilation hang on post-monomorphization errors.
738                 tcx.sess.abort_if_errors();
739
740                 submit_codegened_module_to_llvm(
741                     &backend,
742                     &ongoing_codegen.coordinator.sender,
743                     module,
744                     cost,
745                 );
746                 false
747             }
748             CguReuse::PreLto => {
749                 submit_pre_lto_module_to_llvm(
750                     &backend,
751                     tcx,
752                     &ongoing_codegen.coordinator.sender,
753                     CachedModuleCodegen {
754                         name: cgu.name().to_string(),
755                         source: cgu.previous_work_product(tcx),
756                     },
757                 );
758                 true
759             }
760             CguReuse::PostLto => {
761                 submit_post_lto_module_to_llvm(
762                     &backend,
763                     &ongoing_codegen.coordinator.sender,
764                     CachedModuleCodegen {
765                         name: cgu.name().to_string(),
766                         source: cgu.previous_work_product(tcx),
767                     },
768                 );
769                 true
770             }
771         };
772     }
773
774     ongoing_codegen.codegen_finished(tcx);
775
776     // Since the main thread is sometimes blocked during codegen, we keep track
777     // -Ztime-passes output manually.
778     if tcx.sess.time_passes() {
779         let end_rss = get_resident_set_size();
780
781         print_time_passes_entry(
782             "codegen_to_LLVM_IR",
783             total_codegen_time,
784             start_rss.unwrap(),
785             end_rss,
786         );
787     }
788
789     ongoing_codegen.check_for_errors(tcx.sess);
790     ongoing_codegen
791 }
792
793 impl CrateInfo {
794     pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
795         let exported_symbols = tcx
796             .sess
797             .crate_types()
798             .iter()
799             .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
800             .collect();
801         let linked_symbols = tcx
802             .sess
803             .crate_types()
804             .iter()
805             .map(|&c| (c, crate::back::linker::linked_symbols(tcx, c)))
806             .collect();
807         let local_crate_name = tcx.crate_name(LOCAL_CRATE);
808         let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
809         let subsystem = tcx.sess.first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
810         let windows_subsystem = subsystem.map(|subsystem| {
811             if subsystem != sym::windows && subsystem != sym::console {
812                 tcx.sess.fatal(&format!(
813                     "invalid windows subsystem `{}`, only \
814                                      `windows` and `console` are allowed",
815                     subsystem
816                 ));
817             }
818             subsystem.to_string()
819         });
820
821         // This list is used when generating the command line to pass through to
822         // system linker. The linker expects undefined symbols on the left of the
823         // command line to be defined in libraries on the right, not the other way
824         // around. For more info, see some comments in the add_used_library function
825         // below.
826         //
827         // In order to get this left-to-right dependency ordering, we use the reverse
828         // postorder of all crates putting the leaves at the right-most positions.
829         let used_crates = tcx
830             .postorder_cnums(())
831             .iter()
832             .rev()
833             .copied()
834             .filter(|&cnum| !tcx.dep_kind(cnum).macros_only())
835             .collect();
836
837         let mut info = CrateInfo {
838             target_cpu,
839             exported_symbols,
840             linked_symbols,
841             local_crate_name,
842             compiler_builtins: None,
843             profiler_runtime: None,
844             is_no_builtins: Default::default(),
845             native_libraries: Default::default(),
846             used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
847             crate_name: Default::default(),
848             used_crates,
849             used_crate_source: Default::default(),
850             dependency_formats: tcx.dependency_formats(()).clone(),
851             windows_subsystem,
852             natvis_debugger_visualizers: Default::default(),
853         };
854         let crates = tcx.crates(());
855
856         let n_crates = crates.len();
857         info.native_libraries.reserve(n_crates);
858         info.crate_name.reserve(n_crates);
859         info.used_crate_source.reserve(n_crates);
860
861         for &cnum in crates.iter() {
862             info.native_libraries
863                 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
864             info.crate_name.insert(cnum, tcx.crate_name(cnum));
865
866             let used_crate_source = tcx.used_crate_source(cnum);
867             info.used_crate_source.insert(cnum, used_crate_source.clone());
868             if tcx.is_compiler_builtins(cnum) {
869                 info.compiler_builtins = Some(cnum);
870             }
871             if tcx.is_profiler_runtime(cnum) {
872                 info.profiler_runtime = Some(cnum);
873             }
874             if tcx.is_no_builtins(cnum) {
875                 info.is_no_builtins.insert(cnum);
876             }
877         }
878
879         // Handle circular dependencies in the standard library.
880         // See comment before `add_linked_symbol_object` function for the details.
881         // If global LTO is enabled then almost everything (*) is glued into a single object file,
882         // so this logic is not necessary and can cause issues on some targets (due to weak lang
883         // item symbols being "privatized" to that object file), so we disable it.
884         // (*) Native libs, and `#[compiler_builtins]` and `#[no_builtins]` crates are not glued,
885         // and we assume that they cannot define weak lang items. This is not currently enforced
886         // by the compiler, but that's ok because all this stuff is unstable anyway.
887         let target = &tcx.sess.target;
888         if !are_upstream_rust_objects_already_included(tcx.sess) {
889             let missing_weak_lang_items: FxHashSet<Symbol> = info
890                 .used_crates
891                 .iter()
892                 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
893                 .filter(|l| l.is_weak())
894                 .filter_map(|&l| {
895                     let name = l.link_name()?;
896                     lang_items::required(tcx, l).then_some(name)
897                 })
898                 .collect();
899             let prefix = if target.is_like_windows && target.arch == "x86" { "_" } else { "" };
900             info.linked_symbols
901                 .iter_mut()
902                 .filter(|(crate_type, _)| {
903                     !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
904                 })
905                 .for_each(|(_, linked_symbols)| {
906                     linked_symbols.extend(
907                         missing_weak_lang_items
908                             .iter()
909                             .map(|item| (format!("{prefix}{item}"), SymbolExportKind::Text)),
910                     )
911                 });
912         }
913
914         let embed_visualizers = tcx.sess.crate_types().iter().any(|&crate_type| match crate_type {
915             CrateType::Executable | CrateType::Dylib | CrateType::Cdylib => {
916                 // These are crate types for which we invoke the linker and can embed
917                 // NatVis visualizers.
918                 true
919             }
920             CrateType::ProcMacro => {
921                 // We could embed NatVis for proc macro crates too (to improve the debugging
922                 // experience for them) but it does not seem like a good default, since
923                 // this is a rare use case and we don't want to slow down the common case.
924                 false
925             }
926             CrateType::Staticlib | CrateType::Rlib => {
927                 // We don't invoke the linker for these, so we don't need to collect the NatVis for them.
928                 false
929             }
930         });
931
932         if target.is_like_msvc && embed_visualizers {
933             info.natvis_debugger_visualizers =
934                 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
935         }
936
937         info
938     }
939 }
940
941 pub fn provide(providers: &mut Providers) {
942     providers.backend_optimization_level = |tcx, cratenum| {
943         let for_speed = match tcx.sess.opts.optimize {
944             // If globally no optimisation is done, #[optimize] has no effect.
945             //
946             // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the
947             // pass manager and it is likely that some module-wide passes (such as inliner or
948             // cross-function constant propagation) would ignore the `optnone` annotation we put
949             // on the functions, thus necessarily involving these functions into optimisations.
950             config::OptLevel::No => return config::OptLevel::No,
951             // If globally optimise-speed is already specified, just use that level.
952             config::OptLevel::Less => return config::OptLevel::Less,
953             config::OptLevel::Default => return config::OptLevel::Default,
954             config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
955             // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)
956             // are present).
957             config::OptLevel::Size => config::OptLevel::Default,
958             config::OptLevel::SizeMin => config::OptLevel::Default,
959         };
960
961         let (defids, _) = tcx.collect_and_partition_mono_items(cratenum);
962         for id in &*defids {
963             let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
964             match optimize {
965                 attr::OptimizeAttr::None => continue,
966                 attr::OptimizeAttr::Size => continue,
967                 attr::OptimizeAttr::Speed => {
968                     return for_speed;
969                 }
970             }
971         }
972         tcx.sess.opts.optimize
973     };
974 }
975
976 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
977     if !tcx.dep_graph.is_fully_enabled() {
978         return CguReuse::No;
979     }
980
981     let work_product_id = &cgu.work_product_id();
982     if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
983         // We don't have anything cached for this CGU. This can happen
984         // if the CGU did not exist in the previous session.
985         return CguReuse::No;
986     }
987
988     // Try to mark the CGU as green. If it we can do so, it means that nothing
989     // affecting the LLVM module has changed and we can re-use a cached version.
990     // If we compile with any kind of LTO, this means we can re-use the bitcode
991     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
992     // know that later). If we are not doing LTO, there is only one optimized
993     // version of each module, so we re-use that.
994     let dep_node = cgu.codegen_dep_node(tcx);
995     assert!(
996         !tcx.dep_graph.dep_node_exists(&dep_node),
997         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
998         cgu.name()
999     );
1000
1001     if tcx.try_mark_green(&dep_node) {
1002         // We can re-use either the pre- or the post-thinlto state. If no LTO is
1003         // being performed then we can use post-LTO artifacts, otherwise we must
1004         // reuse pre-LTO artifacts
1005         match compute_per_cgu_lto_type(
1006             &tcx.sess.lto(),
1007             &tcx.sess.opts,
1008             &tcx.sess.crate_types(),
1009             ModuleKind::Regular,
1010         ) {
1011             ComputedLtoType::No => CguReuse::PostLto,
1012             _ => CguReuse::PreLto,
1013         }
1014     } else {
1015         CguReuse::No
1016     }
1017 }