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