]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/base.rs
38ab39febe066c4c0db3adfb8f4286d1ff0289e7
[rust.git] / compiler / rustc_codegen_ssa / src / base.rs
1 use crate::back::write::{
2     compute_per_cgu_lto_type, start_async_codegen, submit_codegened_module_to_llvm,
3     submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen,
4 };
5 use crate::common::{IntPredicate, RealPredicate, TypeKind};
6 use crate::meth;
7 use crate::mir;
8 use crate::mir::operand::OperandValue;
9 use crate::mir::place::PlaceRef;
10 use crate::traits::*;
11 use crate::{CachedModuleCodegen, CrateInfo, MemFlags, ModuleCodegen, ModuleKind};
12
13 use rustc_attr as attr;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
16 use rustc_data_structures::sync::{par_iter, ParallelIterator};
17 use rustc_hir as hir;
18 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
19 use rustc_hir::lang_items::LangItem;
20 use rustc_index::vec::Idx;
21 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
22 use rustc_middle::middle::cstore::EncodedMetadata;
23 use rustc_middle::middle::cstore::{self, LinkagePreference};
24 use rustc_middle::middle::lang_items;
25 use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem};
26 use rustc_middle::ty::layout::{HasTyCtxt, TyAndLayout};
27 use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
28 use rustc_middle::ty::query::Providers;
29 use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
30 use rustc_session::cgu_reuse_tracker::CguReuse;
31 use rustc_session::config::{self, EntryFnType};
32 use rustc_session::Session;
33 use rustc_span::symbol::sym;
34 use rustc_target::abi::{Align, LayoutOf, VariantIdx};
35
36 use std::ops::{Deref, DerefMut};
37 use std::time::{Duration, Instant};
38
39 use itertools::Itertools;
40
41 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind, signed: bool) -> IntPredicate {
42     match op {
43         hir::BinOpKind::Eq => IntPredicate::IntEQ,
44         hir::BinOpKind::Ne => IntPredicate::IntNE,
45         hir::BinOpKind::Lt => {
46             if signed {
47                 IntPredicate::IntSLT
48             } else {
49                 IntPredicate::IntULT
50             }
51         }
52         hir::BinOpKind::Le => {
53             if signed {
54                 IntPredicate::IntSLE
55             } else {
56                 IntPredicate::IntULE
57             }
58         }
59         hir::BinOpKind::Gt => {
60             if signed {
61                 IntPredicate::IntSGT
62             } else {
63                 IntPredicate::IntUGT
64             }
65         }
66         hir::BinOpKind::Ge => {
67             if signed {
68                 IntPredicate::IntSGE
69             } else {
70                 IntPredicate::IntUGE
71             }
72         }
73         op => bug!(
74             "comparison_op_to_icmp_predicate: expected comparison operator, \
75              found {:?}",
76             op
77         ),
78     }
79 }
80
81 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
82     match op {
83         hir::BinOpKind::Eq => RealPredicate::RealOEQ,
84         hir::BinOpKind::Ne => RealPredicate::RealUNE,
85         hir::BinOpKind::Lt => RealPredicate::RealOLT,
86         hir::BinOpKind::Le => RealPredicate::RealOLE,
87         hir::BinOpKind::Gt => RealPredicate::RealOGT,
88         hir::BinOpKind::Ge => RealPredicate::RealOGE,
89         op => {
90             bug!(
91                 "comparison_op_to_fcmp_predicate: expected comparison operator, \
92                  found {:?}",
93                 op
94             );
95         }
96     }
97 }
98
99 pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
100     bx: &mut Bx,
101     lhs: Bx::Value,
102     rhs: Bx::Value,
103     t: Ty<'tcx>,
104     ret_ty: Bx::Type,
105     op: hir::BinOpKind,
106 ) -> Bx::Value {
107     let signed = match t.kind() {
108         ty::Float(_) => {
109             let cmp = bin_op_to_fcmp_predicate(op);
110             let cmp = bx.fcmp(cmp, lhs, rhs);
111             return bx.sext(cmp, ret_ty);
112         }
113         ty::Uint(_) => false,
114         ty::Int(_) => true,
115         _ => bug!("compare_simd_types: invalid SIMD type"),
116     };
117
118     let cmp = bin_op_to_icmp_predicate(op, signed);
119     let cmp = bx.icmp(cmp, lhs, rhs);
120     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
121     // to get the correctly sized type. This will compile to a single instruction
122     // once the IR is converted to assembly if the SIMD instruction is supported
123     // by the target architecture.
124     bx.sext(cmp, ret_ty)
125 }
126
127 /// Retrieves the information we are losing (making dynamic) in an unsizing
128 /// adjustment.
129 ///
130 /// The `old_info` argument is a bit odd. It is intended for use in an upcast,
131 /// where the new vtable for an object will be derived from the old one.
132 pub fn unsized_info<'tcx, Cx: CodegenMethods<'tcx>>(
133     cx: &Cx,
134     source: Ty<'tcx>,
135     target: Ty<'tcx>,
136     old_info: Option<Cx::Value>,
137 ) -> Cx::Value {
138     let (source, target) =
139         cx.tcx().struct_lockstep_tails_erasing_lifetimes(source, target, cx.param_env());
140     match (source.kind(), target.kind()) {
141         (&ty::Array(_, len), &ty::Slice(_)) => {
142             cx.const_usize(len.eval_usize(cx.tcx(), ty::ParamEnv::reveal_all()))
143         }
144         (&ty::Dynamic(..), &ty::Dynamic(..)) => {
145             // For now, upcasts are limited to changes in marker
146             // traits, and hence never actually require an actual
147             // change to the vtable.
148             old_info.expect("unsized_info: missing old info for trait upcast")
149         }
150         (_, &ty::Dynamic(ref data, ..)) => {
151             let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target)).field(cx, FAT_PTR_EXTRA);
152             cx.const_ptrcast(
153                 meth::get_vtable(cx, source, data.principal()),
154                 cx.backend_type(vtable_ptr),
155             )
156         }
157         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
158     }
159 }
160
161 /// Coerces `src` to `dst_ty`. `src_ty` must be a thin pointer.
162 pub fn unsize_thin_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
163     bx: &mut Bx,
164     src: Bx::Value,
165     src_ty: Ty<'tcx>,
166     dst_ty: Ty<'tcx>,
167 ) -> (Bx::Value, Bx::Value) {
168     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
169     match (src_ty.kind(), dst_ty.kind()) {
170         (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
171         | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
172             assert!(bx.cx().type_is_sized(a));
173             let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
174             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
175         }
176         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
177             assert_eq!(def_a, def_b);
178
179             let src_layout = bx.cx().layout_of(src_ty);
180             let dst_layout = bx.cx().layout_of(dst_ty);
181             let mut result = None;
182             for i in 0..src_layout.fields.count() {
183                 let src_f = src_layout.field(bx.cx(), i);
184                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
185                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
186                 if src_f.is_zst() {
187                     continue;
188                 }
189                 assert_eq!(src_layout.size, src_f.size);
190
191                 let dst_f = dst_layout.field(bx.cx(), i);
192                 assert_ne!(src_f.ty, dst_f.ty);
193                 assert_eq!(result, None);
194                 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
195             }
196             let (lldata, llextra) = result.unwrap();
197             // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
198             // FIXME(eddyb) move these out of this `match` arm, so they're always
199             // applied, uniformly, no matter the source/destination types.
200             (
201                 bx.bitcast(lldata, bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true)),
202                 bx.bitcast(llextra, bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true)),
203             )
204         }
205         _ => bug!("unsize_thin_ptr: called on bad types"),
206     }
207 }
208
209 /// Coerces `src`, which is a reference to a value of type `src_ty`,
210 /// to a value of type `dst_ty`, and stores the result in `dst`.
211 pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
212     bx: &mut Bx,
213     src: PlaceRef<'tcx, Bx::Value>,
214     dst: PlaceRef<'tcx, Bx::Value>,
215 ) {
216     let src_ty = src.layout.ty;
217     let dst_ty = dst.layout.ty;
218     match (src_ty.kind(), dst_ty.kind()) {
219         (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
220             let (base, info) = match bx.load_operand(src).val {
221                 OperandValue::Pair(base, info) => {
222                     // fat-ptr to fat-ptr unsize preserves the vtable
223                     // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
224                     // So we need to pointercast the base to ensure
225                     // the types match up.
226                     // FIXME(eddyb) use `scalar_pair_element_backend_type` here,
227                     // like `unsize_thin_ptr` does.
228                     let thin_ptr = dst.layout.field(bx.cx(), FAT_PTR_ADDR);
229                     (bx.pointercast(base, bx.cx().backend_type(thin_ptr)), info)
230                 }
231                 OperandValue::Immediate(base) => unsize_thin_ptr(bx, base, src_ty, dst_ty),
232                 OperandValue::Ref(..) => bug!(),
233             };
234             OperandValue::Pair(base, info).store(bx, dst);
235         }
236
237         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
238             assert_eq!(def_a, def_b);
239
240             for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
241                 let src_f = src.project_field(bx, i);
242                 let dst_f = dst.project_field(bx, i);
243
244                 if dst_f.layout.is_zst() {
245                     continue;
246                 }
247
248                 if src_f.layout.ty == dst_f.layout.ty {
249                     memcpy_ty(
250                         bx,
251                         dst_f.llval,
252                         dst_f.align,
253                         src_f.llval,
254                         src_f.align,
255                         src_f.layout,
256                         MemFlags::empty(),
257                     );
258                 } else {
259                     coerce_unsized_into(bx, src_f, dst_f);
260                 }
261             }
262         }
263         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
264     }
265 }
266
267 pub fn cast_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
268     bx: &mut Bx,
269     op: hir::BinOpKind,
270     lhs: Bx::Value,
271     rhs: Bx::Value,
272 ) -> Bx::Value {
273     cast_shift_rhs(bx, op, lhs, rhs)
274 }
275
276 fn cast_shift_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
277     bx: &mut Bx,
278     op: hir::BinOpKind,
279     lhs: Bx::Value,
280     rhs: Bx::Value,
281 ) -> Bx::Value {
282     // Shifts may have any size int on the rhs
283     if op.is_shift() {
284         let mut rhs_llty = bx.cx().val_ty(rhs);
285         let mut lhs_llty = bx.cx().val_ty(lhs);
286         if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
287             rhs_llty = bx.cx().element_type(rhs_llty)
288         }
289         if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
290             lhs_llty = bx.cx().element_type(lhs_llty)
291         }
292         let rhs_sz = bx.cx().int_width(rhs_llty);
293         let lhs_sz = bx.cx().int_width(lhs_llty);
294         if lhs_sz < rhs_sz {
295             bx.trunc(rhs, lhs_llty)
296         } else if lhs_sz > rhs_sz {
297             // FIXME (#1877: If in the future shifting by negative
298             // values is no longer undefined then this is wrong.
299             bx.zext(rhs, lhs_llty)
300         } else {
301             rhs
302         }
303     } else {
304         rhs
305     }
306 }
307
308 /// Returns `true` if this session's target will use SEH-based unwinding.
309 ///
310 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
311 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
312 /// 64-bit MinGW) instead of "full SEH".
313 pub fn wants_msvc_seh(sess: &Session) -> bool {
314     sess.target.is_like_msvc
315 }
316
317 pub fn memcpy_ty<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
318     bx: &mut Bx,
319     dst: Bx::Value,
320     dst_align: Align,
321     src: Bx::Value,
322     src_align: Align,
323     layout: TyAndLayout<'tcx>,
324     flags: MemFlags,
325 ) {
326     let size = layout.size.bytes();
327     if size == 0 {
328         return;
329     }
330
331     bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
332 }
333
334 pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
335     cx: &'a Bx::CodegenCx,
336     instance: Instance<'tcx>,
337 ) {
338     // this is an info! to allow collecting monomorphization statistics
339     // and to allow finding the last function before LLVM aborts from
340     // release builds.
341     info!("codegen_instance({})", instance);
342
343     mir::codegen_mir::<Bx>(cx, instance);
344 }
345
346 /// Creates the `main` function which will initialize the rust runtime and call
347 /// users main function.
348 pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
349     cx: &'a Bx::CodegenCx,
350 ) -> Option<Bx::Function> {
351     let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
352     let main_is_local = main_def_id.is_local();
353     let instance = Instance::mono(cx.tcx(), main_def_id);
354
355     if main_is_local {
356         // We want to create the wrapper in the same codegen unit as Rust's main
357         // function.
358         if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
359             return None;
360         }
361     } else if !cx.codegen_unit().is_primary() {
362         // We want to create the wrapper only when the codegen unit is the primary one
363         return None;
364     }
365
366     let main_llfn = cx.get_fn_addr(instance);
367
368     let use_start_lang_item = EntryFnType::Start != entry_type;
369     let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, use_start_lang_item);
370     return Some(entry_fn);
371
372     fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
373         cx: &'a Bx::CodegenCx,
374         rust_main: Bx::Value,
375         rust_main_def_id: DefId,
376         use_start_lang_item: bool,
377     ) -> Bx::Function {
378         // The entry function is either `int main(void)` or `int main(int argc, char **argv)`,
379         // depending on whether the target needs `argc` and `argv` to be passed in.
380         let llfty = if cx.sess().target.main_needs_argc_argv {
381             cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int())
382         } else {
383             cx.type_func(&[], cx.type_int())
384         };
385
386         let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output();
387         // Given that `main()` has no arguments,
388         // then its return type cannot have
389         // late-bound regions, since late-bound
390         // regions must appear in the argument
391         // listing.
392         let main_ret_ty = cx.tcx().erase_regions(main_ret_ty.no_bound_vars().unwrap());
393
394         let llfn = match cx.declare_c_main(llfty) {
395             Some(llfn) => llfn,
396             None => {
397                 // FIXME: We should be smart and show a better diagnostic here.
398                 let span = cx.tcx().def_span(rust_main_def_id);
399                 cx.sess()
400                     .struct_span_err(span, "entry symbol `main` declared multiple times")
401                     .help("did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead")
402                     .emit();
403                 cx.sess().abort_if_errors();
404                 bug!();
405             }
406         };
407
408         // `main` should respect same config for frame pointer elimination as rest of code
409         cx.set_frame_pointer_elimination(llfn);
410         cx.apply_target_cpu_attr(llfn);
411
412         let llbb = Bx::append_block(&cx, llfn, "top");
413         let mut bx = Bx::build(&cx, llbb);
414
415         bx.insert_reference_to_gdb_debug_scripts_section_global();
416
417         let (arg_argc, arg_argv) = get_argc_argv(cx, &mut bx);
418
419         let (start_fn, args) = if use_start_lang_item {
420             let start_def_id = cx.tcx().require_lang_item(LangItem::Start, None);
421             let start_fn = cx.get_fn_addr(
422                 ty::Instance::resolve(
423                     cx.tcx(),
424                     ty::ParamEnv::reveal_all(),
425                     start_def_id,
426                     cx.tcx().intern_substs(&[main_ret_ty.into()]),
427                 )
428                 .unwrap()
429                 .unwrap(),
430             );
431             (
432                 start_fn,
433                 vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())), arg_argc, arg_argv],
434             )
435         } else {
436             debug!("using user-defined start fn");
437             (rust_main, vec![arg_argc, arg_argv])
438         };
439
440         let result = bx.call(start_fn, &args, None);
441         let cast = bx.intcast(result, cx.type_int(), true);
442         bx.ret(cast);
443
444         llfn
445     }
446 }
447
448 /// Obtain the `argc` and `argv` values to pass to the rust start function.
449 fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
450     cx: &'a Bx::CodegenCx,
451     bx: &mut Bx,
452 ) -> (Bx::Value, Bx::Value) {
453     if cx.sess().target.main_needs_argc_argv {
454         // Params from native `main()` used as args for rust start function
455         let param_argc = bx.get_param(0);
456         let param_argv = bx.get_param(1);
457         let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
458         let arg_argv = param_argv;
459         (arg_argc, arg_argv)
460     } else {
461         // The Rust start function doesn't need `argc` and `argv`, so just pass zeros.
462         let arg_argc = bx.const_int(cx.type_int(), 0);
463         let arg_argv = bx.const_null(cx.type_ptr_to(cx.type_i8p()));
464         (arg_argc, arg_argv)
465     }
466 }
467
468 pub fn codegen_crate<B: ExtraBackendMethods>(
469     backend: B,
470     tcx: TyCtxt<'tcx>,
471     target_cpu: String,
472     metadata: EncodedMetadata,
473     need_metadata_module: bool,
474 ) -> OngoingCodegen<B> {
475     // Skip crate items and just output metadata in -Z no-codegen mode.
476     if tcx.sess.opts.debugging_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
477         let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, metadata, 1);
478
479         ongoing_codegen.codegen_finished(tcx);
480
481         ongoing_codegen.check_for_errors(tcx.sess);
482
483         return ongoing_codegen;
484     }
485
486     let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
487
488     // Run the monomorphization collector and partition the collected items into
489     // codegen units.
490     let codegen_units = tcx.collect_and_partition_mono_items(()).1;
491
492     // Force all codegen_unit queries so they are already either red or green
493     // when compile_codegen_unit accesses them. We are not able to re-execute
494     // the codegen_unit query from just the DepNode, so an unknown color would
495     // lead to having to re-execute compile_codegen_unit, possibly
496     // unnecessarily.
497     if tcx.dep_graph.is_fully_enabled() {
498         for cgu in codegen_units {
499             tcx.ensure().codegen_unit(cgu.name());
500         }
501     }
502
503     let ongoing_codegen =
504         start_async_codegen(backend.clone(), tcx, target_cpu, metadata, codegen_units.len());
505     let ongoing_codegen = AbortCodegenOnDrop::<B>(Some(ongoing_codegen));
506
507     // Codegen an allocator shim, if necessary.
508     //
509     // If the crate doesn't have an `allocator_kind` set then there's definitely
510     // no shim to generate. Otherwise we also check our dependency graph for all
511     // our output crate types. If anything there looks like its a `Dynamic`
512     // linkage, then it's already got an allocator shim and we'll be using that
513     // one instead. If nothing exists then it's our job to generate the
514     // allocator!
515     let any_dynamic_crate = tcx.dependency_formats(()).iter().any(|(_, list)| {
516         use rustc_middle::middle::dependency_format::Linkage;
517         list.iter().any(|&linkage| linkage == Linkage::Dynamic)
518     });
519     let allocator_module = if any_dynamic_crate {
520         None
521     } else if let Some(kind) = tcx.allocator_kind() {
522         let llmod_id =
523             cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
524         let mut modules = backend.new_metadata(tcx, &llmod_id);
525         tcx.sess.time("write_allocator_module", || {
526             backend.codegen_allocator(tcx, &mut modules, kind, tcx.lang_items().oom().is_some())
527         });
528
529         Some(ModuleCodegen { name: llmod_id, module_llvm: modules, kind: ModuleKind::Allocator })
530     } else {
531         None
532     };
533
534     if let Some(allocator_module) = allocator_module {
535         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
536     }
537
538     if need_metadata_module {
539         // Codegen the encoded metadata.
540         let metadata_cgu_name =
541             cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
542         let mut metadata_llvm_module = backend.new_metadata(tcx, &metadata_cgu_name);
543         tcx.sess.time("write_compressed_metadata", || {
544             backend.write_compressed_metadata(
545                 tcx,
546                 &ongoing_codegen.metadata,
547                 &mut metadata_llvm_module,
548             );
549         });
550
551         let metadata_module = ModuleCodegen {
552             name: metadata_cgu_name,
553             module_llvm: metadata_llvm_module,
554             kind: ModuleKind::Metadata,
555         };
556         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
557     }
558
559     // For better throughput during parallel processing by LLVM, we used to sort
560     // CGUs largest to smallest. This would lead to better thread utilization
561     // by, for example, preventing a large CGU from being processed last and
562     // having only one LLVM thread working while the rest remained idle.
563     //
564     // However, this strategy would lead to high memory usage, as it meant the
565     // LLVM-IR for all of the largest CGUs would be resident in memory at once.
566     //
567     // Instead, we can compromise by ordering CGUs such that the largest and
568     // smallest are first, second largest and smallest are next, etc. If there
569     // are large size variations, this can reduce memory usage significantly.
570     let codegen_units: Vec<_> = {
571         let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
572         sorted_cgus.sort_by_cached_key(|cgu| cgu.size_estimate());
573
574         let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
575         second_half.iter().rev().interleave(first_half).copied().collect()
576     };
577
578     // The non-parallel compiler can only translate codegen units to LLVM IR
579     // on a single thread, leading to a staircase effect where the N LLVM
580     // threads have to wait on the single codegen threads to generate work
581     // for them. The parallel compiler does not have this restriction, so
582     // we can pre-load the LLVM queue in parallel before handing off
583     // coordination to the OnGoingCodegen scheduler.
584     //
585     // This likely is a temporary measure. Once we don't have to support the
586     // non-parallel compiler anymore, we can compile CGUs end-to-end in
587     // parallel and get rid of the complicated scheduling logic.
588     let pre_compile_cgus = |cgu_reuse: &[CguReuse]| {
589         if cfg!(parallel_compiler) {
590             tcx.sess.time("compile_first_CGU_batch", || {
591                 // Try to find one CGU to compile per thread.
592                 let cgus: Vec<_> = cgu_reuse
593                     .iter()
594                     .enumerate()
595                     .filter(|&(_, reuse)| reuse == &CguReuse::No)
596                     .take(tcx.sess.threads())
597                     .collect();
598
599                 // Compile the found CGUs in parallel.
600                 let start_time = Instant::now();
601
602                 let pre_compiled_cgus = par_iter(cgus)
603                     .map(|(i, _)| {
604                         let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
605                         (i, module)
606                     })
607                     .collect();
608
609                 (pre_compiled_cgus, start_time.elapsed())
610             })
611         } else {
612             (FxHashMap::default(), Duration::new(0, 0))
613         }
614     };
615
616     let mut cgu_reuse = Vec::new();
617     let mut pre_compiled_cgus: Option<FxHashMap<usize, _>> = None;
618     let mut total_codegen_time = Duration::new(0, 0);
619     let start_rss = tcx.sess.time_passes().then(|| get_resident_set_size());
620
621     for (i, cgu) in codegen_units.iter().enumerate() {
622         ongoing_codegen.wait_for_signal_to_codegen_item();
623         ongoing_codegen.check_for_errors(tcx.sess);
624
625         // Do some setup work in the first iteration
626         if pre_compiled_cgus.is_none() {
627             // Calculate the CGU reuse
628             cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
629                 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, &cgu)).collect()
630             });
631             // Pre compile some CGUs
632             let (compiled_cgus, codegen_time) = pre_compile_cgus(&cgu_reuse);
633             pre_compiled_cgus = Some(compiled_cgus);
634             total_codegen_time += codegen_time;
635         }
636
637         let cgu_reuse = cgu_reuse[i];
638         tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
639
640         match cgu_reuse {
641             CguReuse::No => {
642                 let (module, cost) =
643                     if let Some(cgu) = pre_compiled_cgus.as_mut().unwrap().remove(&i) {
644                         cgu
645                     } else {
646                         let start_time = Instant::now();
647                         let module = backend.compile_codegen_unit(tcx, cgu.name());
648                         total_codegen_time += start_time.elapsed();
649                         module
650                     };
651                 // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`
652                 // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes
653                 // compilation hang on post-monomorphization errors.
654                 tcx.sess.abort_if_errors();
655
656                 submit_codegened_module_to_llvm(
657                     &backend,
658                     &ongoing_codegen.coordinator_send,
659                     module,
660                     cost,
661                 );
662                 false
663             }
664             CguReuse::PreLto => {
665                 submit_pre_lto_module_to_llvm(
666                     &backend,
667                     tcx,
668                     &ongoing_codegen.coordinator_send,
669                     CachedModuleCodegen {
670                         name: cgu.name().to_string(),
671                         source: cgu.work_product(tcx),
672                     },
673                 );
674                 true
675             }
676             CguReuse::PostLto => {
677                 submit_post_lto_module_to_llvm(
678                     &backend,
679                     &ongoing_codegen.coordinator_send,
680                     CachedModuleCodegen {
681                         name: cgu.name().to_string(),
682                         source: cgu.work_product(tcx),
683                     },
684                 );
685                 true
686             }
687         };
688     }
689
690     ongoing_codegen.codegen_finished(tcx);
691
692     // Since the main thread is sometimes blocked during codegen, we keep track
693     // -Ztime-passes output manually.
694     if tcx.sess.time_passes() {
695         let end_rss = get_resident_set_size();
696
697         print_time_passes_entry(
698             "codegen_to_LLVM_IR",
699             total_codegen_time,
700             start_rss.unwrap(),
701             end_rss,
702         );
703     }
704
705     ongoing_codegen.check_for_errors(tcx.sess);
706
707     ongoing_codegen.into_inner()
708 }
709
710 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
711 /// when it's dropped abnormally.
712 ///
713 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
714 /// stumbled upon. The segfault was never reproduced locally, but it was
715 /// suspected to be related to the fact that codegen worker threads were
716 /// sticking around by the time the main thread was exiting, causing issues.
717 ///
718 /// This structure is an attempt to fix that issue where the `codegen_aborted`
719 /// message will block until all workers have finished. This should ensure that
720 /// even if the main codegen thread panics we'll wait for pending work to
721 /// complete before returning from the main thread, hopefully avoiding
722 /// segfaults.
723 ///
724 /// If you see this comment in the code, then it means that this workaround
725 /// worked! We may yet one day track down the mysterious cause of that
726 /// segfault...
727 struct AbortCodegenOnDrop<B: ExtraBackendMethods>(Option<OngoingCodegen<B>>);
728
729 impl<B: ExtraBackendMethods> AbortCodegenOnDrop<B> {
730     fn into_inner(mut self) -> OngoingCodegen<B> {
731         self.0.take().unwrap()
732     }
733 }
734
735 impl<B: ExtraBackendMethods> Deref for AbortCodegenOnDrop<B> {
736     type Target = OngoingCodegen<B>;
737
738     fn deref(&self) -> &OngoingCodegen<B> {
739         self.0.as_ref().unwrap()
740     }
741 }
742
743 impl<B: ExtraBackendMethods> DerefMut for AbortCodegenOnDrop<B> {
744     fn deref_mut(&mut self) -> &mut OngoingCodegen<B> {
745         self.0.as_mut().unwrap()
746     }
747 }
748
749 impl<B: ExtraBackendMethods> Drop for AbortCodegenOnDrop<B> {
750     fn drop(&mut self) {
751         if let Some(codegen) = self.0.take() {
752             codegen.codegen_aborted();
753         }
754     }
755 }
756
757 impl CrateInfo {
758     pub fn new(tcx: TyCtxt<'_>) -> CrateInfo {
759         let local_crate_name = tcx.crate_name(LOCAL_CRATE);
760         let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
761         let subsystem = tcx.sess.first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
762         let windows_subsystem = subsystem.map(|subsystem| {
763             if subsystem != sym::windows && subsystem != sym::console {
764                 tcx.sess.fatal(&format!(
765                     "invalid windows subsystem `{}`, only \
766                                      `windows` and `console` are allowed",
767                     subsystem
768                 ));
769             }
770             subsystem.to_string()
771         });
772
773         let mut info = CrateInfo {
774             local_crate_name,
775             panic_runtime: None,
776             compiler_builtins: None,
777             profiler_runtime: None,
778             is_no_builtins: Default::default(),
779             native_libraries: Default::default(),
780             used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
781             crate_name: Default::default(),
782             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
783             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
784             used_crate_source: Default::default(),
785             lang_item_to_crate: Default::default(),
786             missing_lang_items: Default::default(),
787             dependency_formats: tcx.dependency_formats(()),
788             windows_subsystem,
789         };
790         let lang_items = tcx.lang_items();
791
792         let crates = tcx.crates();
793
794         let n_crates = crates.len();
795         info.native_libraries.reserve(n_crates);
796         info.crate_name.reserve(n_crates);
797         info.used_crate_source.reserve(n_crates);
798         info.missing_lang_items.reserve(n_crates);
799
800         for &cnum in crates.iter() {
801             info.native_libraries
802                 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
803             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
804             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
805             if tcx.is_panic_runtime(cnum) {
806                 info.panic_runtime = Some(cnum);
807             }
808             if tcx.is_compiler_builtins(cnum) {
809                 info.compiler_builtins = Some(cnum);
810             }
811             if tcx.is_profiler_runtime(cnum) {
812                 info.profiler_runtime = Some(cnum);
813             }
814             if tcx.is_no_builtins(cnum) {
815                 info.is_no_builtins.insert(cnum);
816             }
817             let missing = tcx.missing_lang_items(cnum);
818             for &item in missing.iter() {
819                 if let Ok(id) = lang_items.require(item) {
820                     info.lang_item_to_crate.insert(item, id.krate);
821                 }
822             }
823
824             // No need to look for lang items that don't actually need to exist.
825             let missing =
826                 missing.iter().cloned().filter(|&l| lang_items::required(tcx, l)).collect();
827             info.missing_lang_items.insert(cnum, missing);
828         }
829
830         info
831     }
832 }
833
834 pub fn provide(providers: &mut Providers) {
835     providers.backend_optimization_level = |tcx, cratenum| {
836         let for_speed = match tcx.sess.opts.optimize {
837             // If globally no optimisation is done, #[optimize] has no effect.
838             //
839             // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the
840             // pass manager and it is likely that some module-wide passes (such as inliner or
841             // cross-function constant propagation) would ignore the `optnone` annotation we put
842             // on the functions, thus necessarily involving these functions into optimisations.
843             config::OptLevel::No => return config::OptLevel::No,
844             // If globally optimise-speed is already specified, just use that level.
845             config::OptLevel::Less => return config::OptLevel::Less,
846             config::OptLevel::Default => return config::OptLevel::Default,
847             config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
848             // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)
849             // are present).
850             config::OptLevel::Size => config::OptLevel::Default,
851             config::OptLevel::SizeMin => config::OptLevel::Default,
852         };
853
854         let (defids, _) = tcx.collect_and_partition_mono_items(cratenum);
855         for id in &*defids {
856             let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
857             match optimize {
858                 attr::OptimizeAttr::None => continue,
859                 attr::OptimizeAttr::Size => continue,
860                 attr::OptimizeAttr::Speed => {
861                     return for_speed;
862                 }
863             }
864         }
865         tcx.sess.opts.optimize
866     };
867 }
868
869 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
870     if !tcx.dep_graph.is_fully_enabled() {
871         return CguReuse::No;
872     }
873
874     let work_product_id = &cgu.work_product_id();
875     if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
876         // We don't have anything cached for this CGU. This can happen
877         // if the CGU did not exist in the previous session.
878         return CguReuse::No;
879     }
880
881     // Try to mark the CGU as green. If it we can do so, it means that nothing
882     // affecting the LLVM module has changed and we can re-use a cached version.
883     // If we compile with any kind of LTO, this means we can re-use the bitcode
884     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
885     // know that later). If we are not doing LTO, there is only one optimized
886     // version of each module, so we re-use that.
887     let dep_node = cgu.codegen_dep_node(tcx);
888     assert!(
889         !tcx.dep_graph.dep_node_exists(&dep_node),
890         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
891         cgu.name()
892     );
893
894     if tcx.try_mark_green(&dep_node) {
895         // We can re-use either the pre- or the post-thinlto state. If no LTO is
896         // being performed then we can use post-LTO artifacts, otherwise we must
897         // reuse pre-LTO artifacts
898         match compute_per_cgu_lto_type(
899             &tcx.sess.lto(),
900             &tcx.sess.opts,
901             &tcx.sess.crate_types(),
902             ModuleKind::Regular,
903         ) {
904             ComputedLtoType::No => CguReuse::PostLto,
905             _ => CguReuse::PreLto,
906         }
907     } else {
908         CguReuse::No
909     }
910 }