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