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