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