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