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