]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/base.rs
move Instance to rustc and use it in the collector
[rust.git] / src / librustc_trans / 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 //! Translate the completed AST to the LLVM IR.
12 //!
13 //! Some functions here, such as trans_block and trans_expr, return a value --
14 //! the result of the translation to LLVM -- while others, such as trans_fn
15 //! and trans_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 trans:
19 //!
20 //!   * There's no way to find out the Ty type of a ValueRef.  Doing so
21 //!     would be "trying to get the eggs out of an omelette" (credit:
22 //!     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
23 //!     but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
24 //!     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25
26 use super::CrateTranslation;
27 use super::ModuleLlvm;
28 use super::ModuleSource;
29 use super::ModuleTranslation;
30
31 use assert_module_sources;
32 use back::link;
33 use back::linker::LinkerInfo;
34 use back::symbol_export::{self, ExportedSymbols};
35 use llvm::{Linkage, ValueRef, Vector, get_param};
36 use llvm;
37 use rustc::hir::def_id::LOCAL_CRATE;
38 use middle::lang_items::StartFnLangItem;
39 use rustc::traits;
40 use rustc::ty::{self, Ty, TyCtxt};
41 use rustc::ty::adjustment::CustomCoerceUnsized;
42 use rustc::dep_graph::{AssertDepGraphSafe, DepNode, WorkProduct};
43 use rustc::hir::map as hir_map;
44 use rustc::util::common::time;
45 use session::config::{self, NoDebugInfo};
46 use rustc_incremental::IncrementalHashesMap;
47 use session::{self, DataTypeKind, Session};
48 use abi;
49 use mir::lvalue::LvalueRef;
50 use attributes;
51 use builder::Builder;
52 use callee::{Callee};
53 use common::{C_bool, C_bytes_in_context, C_i32, C_uint};
54 use collector::{self, TransItemCollectionMode};
55 use common::{C_struct_in_context, C_u64, C_undef};
56 use common::CrateContext;
57 use common::{fulfill_obligation};
58 use common::{type_is_zero_size, val_ty};
59 use common;
60 use consts;
61 use context::{SharedCrateContext, CrateContextList};
62 use debuginfo;
63 use declare;
64 use machine;
65 use machine::llsize_of;
66 use meth;
67 use mir;
68 use monomorphize::{self, Instance};
69 use partitioning::{self, PartitioningStrategy, CodegenUnit};
70 use symbol_map::SymbolMap;
71 use symbol_names_test;
72 use trans_item::{TransItem, DefPathBasedNames};
73 use type_::Type;
74 use type_of;
75 use value::Value;
76 use util::nodemap::{NodeSet, FxHashMap, FxHashSet};
77
78 use libc::c_uint;
79 use std::ffi::{CStr, CString};
80 use std::rc::Rc;
81 use std::str;
82 use std::i32;
83 use syntax_pos::{Span, DUMMY_SP};
84 use syntax::attr;
85 use rustc::hir;
86 use rustc::ty::layout::{self, Layout};
87 use syntax::ast;
88
89 use mir::lvalue::Alignment;
90
91 pub struct StatRecorder<'a, 'tcx: 'a> {
92     ccx: &'a CrateContext<'a, 'tcx>,
93     name: Option<String>,
94     istart: usize,
95 }
96
97 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
98     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
99         let istart = ccx.stats().n_llvm_insns.get();
100         StatRecorder {
101             ccx: ccx,
102             name: Some(name),
103             istart: istart,
104         }
105     }
106 }
107
108 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
109     fn drop(&mut self) {
110         if self.ccx.sess().trans_stats() {
111             let iend = self.ccx.stats().n_llvm_insns.get();
112             self.ccx.stats().fn_stats.borrow_mut()
113                 .push((self.name.take().unwrap(), iend - self.istart));
114             self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
115             // Reset LLVM insn count to avoid compound costs.
116             self.ccx.stats().n_llvm_insns.set(self.istart);
117         }
118     }
119 }
120
121 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
122     bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
123 }
124
125 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
126     bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
127 }
128
129 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
130                                 signed: bool)
131                                 -> llvm::IntPredicate {
132     match op {
133         hir::BiEq => llvm::IntEQ,
134         hir::BiNe => llvm::IntNE,
135         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
136         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
137         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
138         hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
139         op => {
140             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
141                   found {:?}",
142                  op)
143         }
144     }
145 }
146
147 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
148     match op {
149         hir::BiEq => llvm::RealOEQ,
150         hir::BiNe => llvm::RealUNE,
151         hir::BiLt => llvm::RealOLT,
152         hir::BiLe => llvm::RealOLE,
153         hir::BiGt => llvm::RealOGT,
154         hir::BiGe => llvm::RealOGE,
155         op => {
156             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
157                   found {:?}",
158                  op);
159         }
160     }
161 }
162
163 pub fn compare_simd_types<'a, 'tcx>(
164     bcx: &Builder<'a, 'tcx>,
165     lhs: ValueRef,
166     rhs: ValueRef,
167     t: Ty<'tcx>,
168     ret_ty: Type,
169     op: hir::BinOp_
170 ) -> ValueRef {
171     let signed = match t.sty {
172         ty::TyFloat(_) => {
173             let cmp = bin_op_to_fcmp_predicate(op);
174             return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
175         },
176         ty::TyUint(_) => false,
177         ty::TyInt(_) => true,
178         _ => bug!("compare_simd_types: invalid SIMD type"),
179     };
180
181     let cmp = bin_op_to_icmp_predicate(op, signed);
182     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
183     // to get the correctly sized type. This will compile to a single instruction
184     // once the IR is converted to assembly if the SIMD instruction is supported
185     // by the target architecture.
186     bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
187 }
188
189 /// Retrieve the information we are losing (making dynamic) in an unsizing
190 /// adjustment.
191 ///
192 /// The `old_info` argument is a bit funny. It is intended for use
193 /// in an upcast, where the new vtable for an object will be drived
194 /// from the old one.
195 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
196                                 source: Ty<'tcx>,
197                                 target: Ty<'tcx>,
198                                 old_info: Option<ValueRef>)
199                                 -> ValueRef {
200     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
201     match (&source.sty, &target.sty) {
202         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
203         (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
204             // For now, upcasts are limited to changes in marker
205             // traits, and hence never actually require an actual
206             // change to the vtable.
207             old_info.expect("unsized_info: missing old info for trait upcast")
208         }
209         (_, &ty::TyDynamic(ref data, ..)) => {
210             consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
211                             Type::vtable_ptr(ccx))
212         }
213         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
214                                      source,
215                                      target),
216     }
217 }
218
219 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
220 pub fn unsize_thin_ptr<'a, 'tcx>(
221     bcx: &Builder<'a, 'tcx>,
222     src: ValueRef,
223     src_ty: Ty<'tcx>,
224     dst_ty: Ty<'tcx>
225 ) -> (ValueRef, ValueRef) {
226     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
227     match (&src_ty.sty, &dst_ty.sty) {
228         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
229          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
230         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
231          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
232         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
233          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
234             assert!(bcx.ccx.shared().type_is_sized(a));
235             let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
236             (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
237         }
238         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
239             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
240             assert!(bcx.ccx.shared().type_is_sized(a));
241             let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
242             (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
243         }
244         _ => bug!("unsize_thin_ptr: called on bad types"),
245     }
246 }
247
248 /// Coerce `src`, which is a reference to a value of type `src_ty`,
249 /// to a value of type `dst_ty` and store the result in `dst`
250 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
251                                      src: &LvalueRef<'tcx>,
252                                      dst: &LvalueRef<'tcx>) {
253     let src_ty = src.ty.to_ty(bcx.tcx());
254     let dst_ty = dst.ty.to_ty(bcx.tcx());
255     let coerce_ptr = || {
256         let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
257             // fat-ptr to fat-ptr unsize preserves the vtable
258             // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
259             // So we need to pointercast the base to ensure
260             // the types match up.
261             let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
262             let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
263             let base = bcx.pointercast(base, llcast_ty);
264             (base, info)
265         } else {
266             let base = load_ty(bcx, src.llval, src.alignment, src_ty);
267             unsize_thin_ptr(bcx, base, src_ty, dst_ty)
268         };
269         store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
270     };
271     match (&src_ty.sty, &dst_ty.sty) {
272         (&ty::TyRef(..), &ty::TyRef(..)) |
273         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
274         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
275             coerce_ptr()
276         }
277         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
278             coerce_ptr()
279         }
280
281         (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
282             assert_eq!(def_a, def_b);
283
284             let src_fields = def_a.variants[0].fields.iter().map(|f| {
285                 monomorphize::field_ty(bcx.tcx(), substs_a, f)
286             });
287             let dst_fields = def_b.variants[0].fields.iter().map(|f| {
288                 monomorphize::field_ty(bcx.tcx(), substs_b, f)
289             });
290
291             let iter = src_fields.zip(dst_fields).enumerate();
292             for (i, (src_fty, dst_fty)) in iter {
293                 if type_is_zero_size(bcx.ccx, dst_fty) {
294                     continue;
295                 }
296
297                 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
298                 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
299                 if src_fty == dst_fty {
300                     memcpy_ty(bcx, dst_f, src_f, src_fty, None);
301                 } else {
302                     coerce_unsized_into(
303                         bcx,
304                         &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
305                         &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
306                     );
307                 }
308             }
309         }
310         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
311                   src_ty,
312                   dst_ty),
313     }
314 }
315
316 pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>,
317                                              source_ty: Ty<'tcx>,
318                                              target_ty: Ty<'tcx>)
319                                              -> CustomCoerceUnsized {
320     let trait_ref = ty::Binder(ty::TraitRef {
321         def_id: scx.tcx().lang_items.coerce_unsized_trait().unwrap(),
322         substs: scx.tcx().mk_substs_trait(source_ty, &[target_ty])
323     });
324
325     match fulfill_obligation(scx, DUMMY_SP, trait_ref) {
326         traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
327             scx.tcx().custom_coerce_unsized_kind(impl_def_id)
328         }
329         vtable => {
330             bug!("invalid CoerceUnsized vtable: {:?}", vtable);
331         }
332     }
333 }
334
335 pub fn cast_shift_expr_rhs(
336     cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
337 ) -> ValueRef {
338     cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
339 }
340
341 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
342     cast_shift_rhs(op,
343                    lhs,
344                    rhs,
345                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
346                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
347 }
348
349 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
350                         lhs: ValueRef,
351                         rhs: ValueRef,
352                         trunc: F,
353                         zext: G)
354                         -> ValueRef
355     where F: FnOnce(ValueRef, Type) -> ValueRef,
356           G: FnOnce(ValueRef, Type) -> ValueRef
357 {
358     // Shifts may have any size int on the rhs
359     if op.is_shift() {
360         let mut rhs_llty = val_ty(rhs);
361         let mut lhs_llty = val_ty(lhs);
362         if rhs_llty.kind() == Vector {
363             rhs_llty = rhs_llty.element_type()
364         }
365         if lhs_llty.kind() == Vector {
366             lhs_llty = lhs_llty.element_type()
367         }
368         let rhs_sz = rhs_llty.int_width();
369         let lhs_sz = lhs_llty.int_width();
370         if lhs_sz < rhs_sz {
371             trunc(rhs, lhs_llty)
372         } else if lhs_sz > rhs_sz {
373             // FIXME (#1877: If shifting by negative
374             // values becomes not undefined then this is wrong.
375             zext(rhs, lhs_llty)
376         } else {
377             rhs
378         }
379     } else {
380         rhs
381     }
382 }
383
384 /// Returns whether this session's target will use SEH-based unwinding.
385 ///
386 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
387 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
388 /// 64-bit MinGW) instead of "full SEH".
389 pub fn wants_msvc_seh(sess: &Session) -> bool {
390     sess.target.target.options.is_like_msvc
391 }
392
393 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
394     let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
395     b.call(assume_intrinsic, &[val], None);
396 }
397
398 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
399 /// differs from the type used for SSA values. Also handles various special cases where the type
400 /// gives us better information about what we are loading.
401 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
402                          alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
403     let ccx = b.ccx;
404     if type_is_zero_size(ccx, t) {
405         return C_undef(type_of::type_of(ccx, t));
406     }
407
408     unsafe {
409         let global = llvm::LLVMIsAGlobalVariable(ptr);
410         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
411             let val = llvm::LLVMGetInitializer(global);
412             if !val.is_null() {
413                 if t.is_bool() {
414                     return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
415                 }
416                 return val;
417             }
418         }
419     }
420
421     if t.is_bool() {
422         b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
423                 Type::i1(ccx))
424     } else if t.is_char() {
425         // a char is a Unicode codepoint, and so takes values from 0
426         // to 0x10FFFF inclusive only.
427         b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
428     } else if (t.is_region_ptr() || t.is_box()) && !common::type_is_fat_ptr(ccx, t) {
429         b.load_nonnull(ptr, alignment.to_align())
430     } else {
431         b.load(ptr, alignment.to_align())
432     }
433 }
434
435 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
436 /// differs from the type used for SSA values.
437 pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
438                           dst_align: Alignment, t: Ty<'tcx>) {
439     debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
440
441     if common::type_is_fat_ptr(cx.ccx, t) {
442         let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
443         let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
444         store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
445     } else {
446         cx.store(from_immediate(cx, v), dst, dst_align.to_align());
447     }
448 }
449
450 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
451                                data: ValueRef,
452                                extra: ValueRef,
453                                dst: ValueRef,
454                                dst_align: Alignment,
455                                _ty: Ty<'tcx>) {
456     // FIXME: emit metadata
457     cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
458     cx.store(extra, get_meta(cx, dst), dst_align.to_align());
459 }
460
461 pub fn load_fat_ptr<'a, 'tcx>(
462     b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
463 ) -> (ValueRef, ValueRef) {
464     let ptr = get_dataptr(b, src);
465     let ptr = if t.is_region_ptr() || t.is_box() {
466         b.load_nonnull(ptr, alignment.to_align())
467     } else {
468         b.load(ptr, alignment.to_align())
469     };
470
471     let meta = get_meta(b, src);
472     let meta_ty = val_ty(meta);
473     // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
474     // instead
475     let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
476         b.load_nonnull(meta, None)
477     } else {
478         b.load(meta, None)
479     };
480
481     (ptr, meta)
482 }
483
484 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
485     if val_ty(val) == Type::i1(bcx.ccx) {
486         bcx.zext(val, Type::i8(bcx.ccx))
487     } else {
488         val
489     }
490 }
491
492 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
493     if ty.is_bool() {
494         bcx.trunc(val, Type::i1(bcx.ccx))
495     } else {
496         val
497     }
498 }
499
500 pub enum Lifetime { Start, End }
501
502 impl Lifetime {
503     // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
504     // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
505     // and the intrinsic for `lt` and passes them to `emit`, which is in
506     // charge of generating code to call the passed intrinsic on whatever
507     // block of generated code is targetted for the intrinsic.
508     //
509     // If LLVM lifetime intrinsic support is disabled (i.e.  optimizations
510     // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
511     pub fn call(self, b: &Builder, ptr: ValueRef) {
512         if b.ccx.sess().opts.optimize == config::OptLevel::No {
513             return;
514         }
515
516         let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
517         if size == 0 {
518             return;
519         }
520
521         let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
522             Lifetime::Start => "llvm.lifetime.start",
523             Lifetime::End => "llvm.lifetime.end"
524         });
525
526         let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
527         b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
528     }
529 }
530
531 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
532                                dst: ValueRef,
533                                src: ValueRef,
534                                n_bytes: ValueRef,
535                                align: u32) {
536     let ccx = b.ccx;
537     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
538     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
539     let memcpy = ccx.get_intrinsic(&key);
540     let src_ptr = b.pointercast(src, Type::i8p(ccx));
541     let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
542     let size = b.intcast(n_bytes, ccx.int_type(), false);
543     let align = C_i32(ccx, align as i32);
544     let volatile = C_bool(ccx, false);
545     b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
546 }
547
548 pub fn memcpy_ty<'a, 'tcx>(
549     bcx: &Builder<'a, 'tcx>,
550     dst: ValueRef,
551     src: ValueRef,
552     t: Ty<'tcx>,
553     align: Option<u32>,
554 ) {
555     let ccx = bcx.ccx;
556
557     if type_is_zero_size(ccx, t) {
558         return;
559     }
560
561     let llty = type_of::type_of(ccx, t);
562     let llsz = llsize_of(ccx, llty);
563     let llalign = align.unwrap_or_else(|| type_of::align_of(ccx, t));
564     call_memcpy(bcx, dst, src, llsz, llalign as u32);
565 }
566
567 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
568                              ptr: ValueRef,
569                              fill_byte: ValueRef,
570                              size: ValueRef,
571                              align: ValueRef,
572                              volatile: bool) -> ValueRef {
573     let ptr_width = &b.ccx.sess().target.target.target_pointer_width[..];
574     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
575     let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
576     let volatile = C_bool(b.ccx, volatile);
577     b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
578 }
579
580 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
581     let _s = if ccx.sess().trans_stats() {
582         let mut instance_name = String::new();
583         DefPathBasedNames::new(ccx.tcx(), true, true)
584             .push_def_path(instance.def_id(), &mut instance_name);
585         Some(StatRecorder::new(ccx, instance_name))
586     } else {
587         None
588     };
589
590     // this is an info! to allow collecting monomorphization statistics
591     // and to allow finding the last function before LLVM aborts from
592     // release builds.
593     info!("trans_instance({})", instance);
594
595     let fn_ty = common::instance_ty(ccx.shared(), &instance);
596     let sig = common::ty_fn_sig(ccx, fn_ty);
597     let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
598
599     let lldecl = match ccx.instances().borrow().get(&instance) {
600         Some(&val) => val,
601         None => bug!("Instance `{:?}` not already declared", instance)
602     };
603
604     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
605
606     if !ccx.sess().no_landing_pads() {
607         attributes::emit_uwtable(lldecl, true);
608     }
609
610     let mir = ccx.tcx().instance_mir(instance.def);
611     mir::trans_mir(ccx, lldecl, &mir, instance, sig);
612 }
613
614 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
615     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
616     // applicable to variable declarations and may not really make sense for
617     // Rust code in the first place but whitelist them anyway and trust that
618     // the user knows what s/he's doing. Who knows, unanticipated use cases
619     // may pop up in the future.
620     //
621     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
622     // and don't have to be, LLVM treats them as no-ops.
623     match name {
624         "appending" => Some(llvm::Linkage::AppendingLinkage),
625         "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
626         "common" => Some(llvm::Linkage::CommonLinkage),
627         "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
628         "external" => Some(llvm::Linkage::ExternalLinkage),
629         "internal" => Some(llvm::Linkage::InternalLinkage),
630         "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
631         "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
632         "private" => Some(llvm::Linkage::PrivateLinkage),
633         "weak" => Some(llvm::Linkage::WeakAnyLinkage),
634         "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
635         _ => None,
636     }
637 }
638
639 pub fn set_link_section(ccx: &CrateContext,
640                         llval: ValueRef,
641                         attrs: &[ast::Attribute]) {
642     if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
643         if contains_null(&sect.as_str()) {
644             ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
645         }
646         unsafe {
647             let buf = CString::new(sect.as_str().as_bytes()).unwrap();
648             llvm::LLVMSetSection(llval, buf.as_ptr());
649         }
650     }
651 }
652
653 /// Create the `main` function which will initialise the rust runtime and call
654 /// users main function.
655 pub fn maybe_create_entry_wrapper(ccx: &CrateContext) {
656     let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
657         Some((id, span)) => {
658             (ccx.tcx().hir.local_def_id(id), span)
659         }
660         None => return,
661     };
662
663     // check for the #[rustc_error] annotation, which forces an
664     // error in trans. This is used to write compile-fail tests
665     // that actually test that compilation succeeds without
666     // reporting an error.
667     if ccx.tcx().has_attr(main_def_id, "rustc_error") {
668         ccx.tcx().sess.span_fatal(span, "compilation successful");
669     }
670
671     let instance = Instance::mono(ccx.tcx(), main_def_id);
672
673     if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
674         // We want to create the wrapper in the same codegen unit as Rust's main
675         // function.
676         return;
677     }
678
679     let main_llfn = Callee::def(ccx, main_def_id, instance.substs).reify(ccx);
680
681     let et = ccx.sess().entry_type.get().unwrap();
682     match et {
683         config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
684         config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
685         config::EntryNone => {}    // Do nothing.
686     }
687
688     fn create_entry_fn(ccx: &CrateContext,
689                        sp: Span,
690                        rust_main: ValueRef,
691                        use_start_lang_item: bool) {
692         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
693
694         if declare::get_defined_value(ccx, "main").is_some() {
695             // FIXME: We should be smart and show a better diagnostic here.
696             ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
697                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
698                       .emit();
699             ccx.sess().abort_if_errors();
700             bug!();
701         }
702         let llfn = declare::declare_cfn(ccx, "main", llfty);
703
704         // `main` should respect same config for frame pointer elimination as rest of code
705         attributes::set_frame_pointer_elimination(ccx, llfn);
706
707         let bld = Builder::new_block(ccx, llfn, "top");
708
709         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
710
711         let (start_fn, args) = if use_start_lang_item {
712             let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
713             let empty_substs = ccx.tcx().intern_substs(&[]);
714             let start_fn = Callee::def(ccx, start_def_id, empty_substs).reify(ccx);
715             (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
716                 get_param(llfn, 1)])
717         } else {
718             debug!("using user-defined start fn");
719             (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
720         };
721
722         let result = bld.call(start_fn, &args, None);
723         bld.ret(result);
724     }
725 }
726
727 fn contains_null(s: &str) -> bool {
728     s.bytes().any(|b| b == 0)
729 }
730
731 fn write_metadata(cx: &SharedCrateContext,
732                   exported_symbols: &NodeSet) -> Vec<u8> {
733     use flate;
734
735     #[derive(PartialEq, Eq, PartialOrd, Ord)]
736     enum MetadataKind {
737         None,
738         Uncompressed,
739         Compressed
740     }
741
742     let kind = cx.sess().crate_types.borrow().iter().map(|ty| {
743         match *ty {
744             config::CrateTypeExecutable |
745             config::CrateTypeStaticlib |
746             config::CrateTypeCdylib => MetadataKind::None,
747
748             config::CrateTypeRlib => MetadataKind::Uncompressed,
749
750             config::CrateTypeDylib |
751             config::CrateTypeProcMacro => MetadataKind::Compressed,
752         }
753     }).max().unwrap();
754
755     if kind == MetadataKind::None {
756         return Vec::new();
757     }
758
759     let cstore = &cx.tcx().sess.cstore;
760     let metadata = cstore.encode_metadata(cx.tcx(),
761                                           cx.export_map(),
762                                           cx.link_meta(),
763                                           exported_symbols);
764     if kind == MetadataKind::Uncompressed {
765         return metadata;
766     }
767
768     assert!(kind == MetadataKind::Compressed);
769     let mut compressed = cstore.metadata_encoding_version().to_vec();
770     compressed.extend_from_slice(&flate::deflate_bytes(&metadata));
771
772     let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
773     let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
774     let name = cx.metadata_symbol_name();
775     let buf = CString::new(name).unwrap();
776     let llglobal = unsafe {
777         llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf.as_ptr())
778     };
779     unsafe {
780         llvm::LLVMSetInitializer(llglobal, llconst);
781         let section_name =
782             cx.tcx().sess.cstore.metadata_section_name(&cx.sess().target.target);
783         let name = CString::new(section_name).unwrap();
784         llvm::LLVMSetSection(llglobal, name.as_ptr());
785
786         // Also generate a .section directive to force no
787         // flags, at least for ELF outputs, so that the
788         // metadata doesn't get loaded into memory.
789         let directive = format!(".section {}", section_name);
790         let directive = CString::new(directive).unwrap();
791         llvm::LLVMSetModuleInlineAsm(cx.metadata_llmod(), directive.as_ptr())
792     }
793     return metadata;
794 }
795
796 /// Find any symbols that are defined in one compilation unit, but not declared
797 /// in any other compilation unit.  Give these symbols internal linkage.
798 fn internalize_symbols<'a, 'tcx>(sess: &Session,
799                                  ccxs: &CrateContextList<'a, 'tcx>,
800                                  symbol_map: &SymbolMap<'tcx>,
801                                  exported_symbols: &ExportedSymbols) {
802     let export_threshold =
803         symbol_export::crates_export_threshold(&sess.crate_types.borrow()[..]);
804
805     let exported_symbols = exported_symbols
806         .exported_symbols(LOCAL_CRATE)
807         .iter()
808         .filter(|&&(_, export_level)| {
809             symbol_export::is_below_threshold(export_level, export_threshold)
810         })
811         .map(|&(ref name, _)| &name[..])
812         .collect::<FxHashSet<&str>>();
813
814     let scx = ccxs.shared();
815     let tcx = scx.tcx();
816
817     let incr_comp = sess.opts.debugging_opts.incremental.is_some();
818
819     // 'unsafe' because we are holding on to CStr's from the LLVM module within
820     // this block.
821     unsafe {
822         let mut referenced_somewhere = FxHashSet();
823
824         // Collect all symbols that need to stay externally visible because they
825         // are referenced via a declaration in some other codegen unit. In
826         // incremental compilation, we don't need to collect. See below for more
827         // information.
828         if !incr_comp {
829             for ccx in ccxs.iter_need_trans() {
830                 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
831                     let linkage = llvm::LLVMRustGetLinkage(val);
832                     // We only care about external declarations (not definitions)
833                     // and available_externally definitions.
834                     let is_available_externally =
835                         linkage == llvm::Linkage::AvailableExternallyLinkage;
836                     let is_decl = llvm::LLVMIsDeclaration(val) == llvm::True;
837
838                     if is_decl || is_available_externally {
839                         let symbol_name = CStr::from_ptr(llvm::LLVMGetValueName(val));
840                         referenced_somewhere.insert(symbol_name);
841                     }
842                 }
843             }
844         }
845
846         // Also collect all symbols for which we cannot adjust linkage, because
847         // it is fixed by some directive in the source code.
848         let (locally_defined_symbols, linkage_fixed_explicitly) = {
849             let mut locally_defined_symbols = FxHashSet();
850             let mut linkage_fixed_explicitly = FxHashSet();
851
852             for trans_item in scx.translation_items().borrow().iter() {
853                 let symbol_name = symbol_map.get_or_compute(scx, *trans_item);
854                 if trans_item.explicit_linkage(tcx).is_some() {
855                     linkage_fixed_explicitly.insert(symbol_name.clone());
856                 }
857                 locally_defined_symbols.insert(symbol_name);
858             }
859
860             (locally_defined_symbols, linkage_fixed_explicitly)
861         };
862
863         // Examine each external definition.  If the definition is not used in
864         // any other compilation unit, and is not reachable from other crates,
865         // then give it internal linkage.
866         for ccx in ccxs.iter_need_trans() {
867             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
868                 let linkage = llvm::LLVMRustGetLinkage(val);
869
870                 let is_externally_visible = (linkage == llvm::Linkage::ExternalLinkage) ||
871                                             (linkage == llvm::Linkage::LinkOnceODRLinkage) ||
872                                             (linkage == llvm::Linkage::WeakODRLinkage);
873
874                 if !is_externally_visible {
875                     // This symbol is not visible outside of its codegen unit,
876                     // so there is nothing to do for it.
877                     continue;
878                 }
879
880                 let name_cstr = CStr::from_ptr(llvm::LLVMGetValueName(val));
881                 let name_str = name_cstr.to_str().unwrap();
882
883                 if exported_symbols.contains(&name_str) {
884                     // This symbol is explicitly exported, so we can't
885                     // mark it as internal or hidden.
886                     continue;
887                 }
888
889                 let is_declaration = llvm::LLVMIsDeclaration(val) == llvm::True;
890
891                 if is_declaration {
892                     if locally_defined_symbols.contains(name_str) {
893                         // Only mark declarations from the current crate as hidden.
894                         // Otherwise we would mark things as hidden that are
895                         // imported from other crates or native libraries.
896                         llvm::LLVMRustSetVisibility(val, llvm::Visibility::Hidden);
897                     }
898                 } else {
899                     let has_fixed_linkage = linkage_fixed_explicitly.contains(name_str);
900
901                     if !has_fixed_linkage {
902                         // In incremental compilation mode, we can't be sure that
903                         // we saw all references because we don't know what's in
904                         // cached compilation units, so we always assume that the
905                         // given item has been referenced.
906                         if incr_comp || referenced_somewhere.contains(&name_cstr) {
907                             llvm::LLVMRustSetVisibility(val, llvm::Visibility::Hidden);
908                         } else {
909                             llvm::LLVMRustSetLinkage(val, llvm::Linkage::InternalLinkage);
910                         }
911
912                         llvm::LLVMSetDLLStorageClass(val, llvm::DLLStorageClass::Default);
913                         llvm::UnsetComdat(val);
914                     }
915                 }
916             }
917         }
918     }
919 }
920
921 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
922 // This is required to satisfy `dllimport` references to static data in .rlibs
923 // when using MSVC linker.  We do this only for data, as linker can fix up
924 // code references on its own.
925 // See #26591, #27438
926 fn create_imps(cx: &CrateContextList) {
927     // The x86 ABI seems to require that leading underscores are added to symbol
928     // names, so we need an extra underscore on 32-bit. There's also a leading
929     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
930     // underscores added in front).
931     let prefix = if cx.shared().sess().target.target.target_pointer_width == "32" {
932         "\x01__imp__"
933     } else {
934         "\x01__imp_"
935     };
936     unsafe {
937         for ccx in cx.iter_need_trans() {
938             let exported: Vec<_> = iter_globals(ccx.llmod())
939                                        .filter(|&val| {
940                                            llvm::LLVMRustGetLinkage(val) ==
941                                            llvm::Linkage::ExternalLinkage &&
942                                            llvm::LLVMIsDeclaration(val) == 0
943                                        })
944                                        .collect();
945
946             let i8p_ty = Type::i8p(&ccx);
947             for val in exported {
948                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
949                 let mut imp_name = prefix.as_bytes().to_vec();
950                 imp_name.extend(name.to_bytes());
951                 let imp_name = CString::new(imp_name).unwrap();
952                 let imp = llvm::LLVMAddGlobal(ccx.llmod(),
953                                               i8p_ty.to_ref(),
954                                               imp_name.as_ptr() as *const _);
955                 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
956                 llvm::LLVMSetInitializer(imp, init);
957                 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
958             }
959         }
960     }
961 }
962
963 struct ValueIter {
964     cur: ValueRef,
965     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
966 }
967
968 impl Iterator for ValueIter {
969     type Item = ValueRef;
970
971     fn next(&mut self) -> Option<ValueRef> {
972         let old = self.cur;
973         if !old.is_null() {
974             self.cur = unsafe { (self.step)(old) };
975             Some(old)
976         } else {
977             None
978         }
979     }
980 }
981
982 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
983     unsafe {
984         ValueIter {
985             cur: llvm::LLVMGetFirstGlobal(llmod),
986             step: llvm::LLVMGetNextGlobal,
987         }
988     }
989 }
990
991 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
992     unsafe {
993         ValueIter {
994             cur: llvm::LLVMGetFirstFunction(llmod),
995             step: llvm::LLVMGetNextFunction,
996         }
997     }
998 }
999
1000 /// The context provided lists a set of reachable ids as calculated by
1001 /// middle::reachable, but this contains far more ids and symbols than we're
1002 /// actually exposing from the object file. This function will filter the set in
1003 /// the context to the set of ids which correspond to symbols that are exposed
1004 /// from the object file being generated.
1005 ///
1006 /// This list is later used by linkers to determine the set of symbols needed to
1007 /// be exposed from a dynamic library and it's also encoded into the metadata.
1008 pub fn find_exported_symbols(tcx: TyCtxt, reachable: NodeSet) -> NodeSet {
1009     reachable.into_iter().filter(|&id| {
1010         // Next, we want to ignore some FFI functions that are not exposed from
1011         // this crate. Reachable FFI functions can be lumped into two
1012         // categories:
1013         //
1014         // 1. Those that are included statically via a static library
1015         // 2. Those included otherwise (e.g. dynamically or via a framework)
1016         //
1017         // Although our LLVM module is not literally emitting code for the
1018         // statically included symbols, it's an export of our library which
1019         // needs to be passed on to the linker and encoded in the metadata.
1020         //
1021         // As a result, if this id is an FFI item (foreign item) then we only
1022         // let it through if it's included statically.
1023         match tcx.hir.get(id) {
1024             hir_map::NodeForeignItem(..) => {
1025                 let def_id = tcx.hir.local_def_id(id);
1026                 tcx.sess.cstore.is_statically_included_foreign_item(def_id)
1027             }
1028
1029             // Only consider nodes that actually have exported symbols.
1030             hir_map::NodeItem(&hir::Item {
1031                 node: hir::ItemStatic(..), .. }) |
1032             hir_map::NodeItem(&hir::Item {
1033                 node: hir::ItemFn(..), .. }) |
1034             hir_map::NodeImplItem(&hir::ImplItem {
1035                 node: hir::ImplItemKind::Method(..), .. }) => {
1036                 let def_id = tcx.hir.local_def_id(id);
1037                 let generics = tcx.item_generics(def_id);
1038                 let attributes = tcx.get_attrs(def_id);
1039                 (generics.parent_types == 0 && generics.types.is_empty()) &&
1040                 // Functions marked with #[inline] are only ever translated
1041                 // with "internal" linkage and are never exported.
1042                 !attr::requests_inline(&attributes[..])
1043             }
1044
1045             _ => false
1046         }
1047     }).collect()
1048 }
1049
1050 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1051                              analysis: ty::CrateAnalysis,
1052                              incremental_hashes_map: &IncrementalHashesMap)
1053                              -> CrateTranslation {
1054     let _task = tcx.dep_graph.in_task(DepNode::TransCrate);
1055
1056     // Be careful with this krate: obviously it gives access to the
1057     // entire contents of the krate. So if you push any subtasks of
1058     // `TransCrate`, you need to be careful to register "reads" of the
1059     // particular items that will be processed.
1060     let krate = tcx.hir.krate();
1061
1062     let ty::CrateAnalysis { export_map, reachable, name, .. } = analysis;
1063     let exported_symbols = find_exported_symbols(tcx, reachable);
1064
1065     let check_overflow = tcx.sess.overflow_checks();
1066
1067     let link_meta = link::build_link_meta(incremental_hashes_map, &name);
1068
1069     let shared_ccx = SharedCrateContext::new(tcx,
1070                                              export_map,
1071                                              link_meta.clone(),
1072                                              exported_symbols,
1073                                              check_overflow);
1074     // Translate the metadata.
1075     let metadata = time(tcx.sess.time_passes(), "write metadata", || {
1076         write_metadata(&shared_ccx, shared_ccx.exported_symbols())
1077     });
1078
1079     let metadata_module = ModuleTranslation {
1080         name: link::METADATA_MODULE_NAME.to_string(),
1081         symbol_name_hash: 0, // we always rebuild metadata, at least for now
1082         source: ModuleSource::Translated(ModuleLlvm {
1083             llcx: shared_ccx.metadata_llcx(),
1084             llmod: shared_ccx.metadata_llmod(),
1085         }),
1086     };
1087     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
1088
1089     // Skip crate items and just output metadata in -Z no-trans mode.
1090     if tcx.sess.opts.debugging_opts.no_trans ||
1091        !tcx.sess.opts.output_types.should_trans() {
1092         let empty_exported_symbols = ExportedSymbols::empty();
1093         let linker_info = LinkerInfo::new(&shared_ccx, &empty_exported_symbols);
1094         return CrateTranslation {
1095             modules: vec![],
1096             metadata_module: metadata_module,
1097             link: link_meta,
1098             metadata: metadata,
1099             exported_symbols: empty_exported_symbols,
1100             no_builtins: no_builtins,
1101             linker_info: linker_info,
1102             windows_subsystem: None,
1103         };
1104     }
1105
1106     // Run the translation item collector and partition the collected items into
1107     // codegen units.
1108     let (codegen_units, symbol_map) = collect_and_partition_translation_items(&shared_ccx);
1109
1110     let symbol_map = Rc::new(symbol_map);
1111
1112     let previous_work_products = trans_reuse_previous_work_products(&shared_ccx,
1113                                                                     &codegen_units,
1114                                                                     &symbol_map);
1115
1116     let crate_context_list = CrateContextList::new(&shared_ccx,
1117                                                    codegen_units,
1118                                                    previous_work_products,
1119                                                    symbol_map.clone());
1120     let modules: Vec<_> = crate_context_list.iter_all()
1121         .map(|ccx| {
1122             let source = match ccx.previous_work_product() {
1123                 Some(buf) => ModuleSource::Preexisting(buf.clone()),
1124                 None => ModuleSource::Translated(ModuleLlvm {
1125                     llcx: ccx.llcx(),
1126                     llmod: ccx.llmod(),
1127                 }),
1128             };
1129
1130             ModuleTranslation {
1131                 name: String::from(ccx.codegen_unit().name()),
1132                 symbol_name_hash: ccx.codegen_unit()
1133                                      .compute_symbol_name_hash(&shared_ccx,
1134                                                                &symbol_map),
1135                 source: source,
1136             }
1137         })
1138         .collect();
1139
1140     assert_module_sources::assert_module_sources(tcx, &modules);
1141
1142     // Instantiate translation items without filling out definitions yet...
1143     for ccx in crate_context_list.iter_need_trans() {
1144         let dep_node = ccx.codegen_unit().work_product_dep_node();
1145         tcx.dep_graph.with_task(dep_node,
1146                                 ccx,
1147                                 AssertDepGraphSafe(symbol_map.clone()),
1148                                 trans_decl_task);
1149
1150         fn trans_decl_task<'a, 'tcx>(ccx: CrateContext<'a, 'tcx>,
1151                                      symbol_map: AssertDepGraphSafe<Rc<SymbolMap<'tcx>>>) {
1152             // FIXME(#40304): Instead of this, the symbol-map should be an
1153             // on-demand thing that we compute.
1154             let AssertDepGraphSafe(symbol_map) = symbol_map;
1155             let cgu = ccx.codegen_unit();
1156             let trans_items = cgu.items_in_deterministic_order(ccx.tcx(), &symbol_map);
1157             for (trans_item, linkage) in trans_items {
1158                 trans_item.predefine(&ccx, linkage);
1159             }
1160         }
1161     }
1162
1163     // ... and now that we have everything pre-defined, fill out those definitions.
1164     for ccx in crate_context_list.iter_need_trans() {
1165         let dep_node = ccx.codegen_unit().work_product_dep_node();
1166         tcx.dep_graph.with_task(dep_node,
1167                                 ccx,
1168                                 AssertDepGraphSafe(symbol_map.clone()),
1169                                 trans_def_task);
1170
1171         fn trans_def_task<'a, 'tcx>(ccx: CrateContext<'a, 'tcx>,
1172                                     symbol_map: AssertDepGraphSafe<Rc<SymbolMap<'tcx>>>) {
1173             // FIXME(#40304): Instead of this, the symbol-map should be an
1174             // on-demand thing that we compute.
1175             let AssertDepGraphSafe(symbol_map) = symbol_map;
1176             let cgu = ccx.codegen_unit();
1177             let trans_items = cgu.items_in_deterministic_order(ccx.tcx(), &symbol_map);
1178             for (trans_item, _) in trans_items {
1179                 trans_item.define(&ccx);
1180             }
1181
1182             // If this codegen unit contains the main function, also create the
1183             // wrapper here
1184             maybe_create_entry_wrapper(&ccx);
1185
1186             // Run replace-all-uses-with for statics that need it
1187             for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1188                 unsafe {
1189                     let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1190                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1191                     llvm::LLVMDeleteGlobal(old_g);
1192                 }
1193             }
1194
1195             // Finalize debuginfo
1196             if ccx.sess().opts.debuginfo != NoDebugInfo {
1197                 debuginfo::finalize(&ccx);
1198             }
1199         }
1200     }
1201
1202     symbol_names_test::report_symbol_names(&shared_ccx);
1203
1204     if shared_ccx.sess().trans_stats() {
1205         let stats = shared_ccx.stats();
1206         println!("--- trans stats ---");
1207         println!("n_glues_created: {}", stats.n_glues_created.get());
1208         println!("n_null_glues: {}", stats.n_null_glues.get());
1209         println!("n_real_glues: {}", stats.n_real_glues.get());
1210
1211         println!("n_fns: {}", stats.n_fns.get());
1212         println!("n_inlines: {}", stats.n_inlines.get());
1213         println!("n_closures: {}", stats.n_closures.get());
1214         println!("fn stats:");
1215         stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1216             insns_b.cmp(&insns_a)
1217         });
1218         for tuple in stats.fn_stats.borrow().iter() {
1219             match *tuple {
1220                 (ref name, insns) => {
1221                     println!("{} insns, {}", insns, *name);
1222                 }
1223             }
1224         }
1225     }
1226
1227     if shared_ccx.sess().count_llvm_insns() {
1228         for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
1229             println!("{:7} {}", *v, *k);
1230         }
1231     }
1232
1233     let sess = shared_ccx.sess();
1234
1235     let exported_symbols = ExportedSymbols::compute_from(&shared_ccx,
1236                                                          &symbol_map);
1237
1238     // Now that we have all symbols that are exported from the CGUs of this
1239     // crate, we can run the `internalize_symbols` pass.
1240     time(shared_ccx.sess().time_passes(), "internalize symbols", || {
1241         internalize_symbols(sess,
1242                             &crate_context_list,
1243                             &symbol_map,
1244                             &exported_symbols);
1245     });
1246
1247     if tcx.sess.opts.debugging_opts.print_type_sizes {
1248         gather_type_sizes(tcx);
1249     }
1250
1251     if sess.target.target.options.is_like_msvc &&
1252        sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1253         create_imps(&crate_context_list);
1254     }
1255
1256     let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1257
1258     let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1259                                                        "windows_subsystem");
1260     let windows_subsystem = subsystem.map(|subsystem| {
1261         if subsystem != "windows" && subsystem != "console" {
1262             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1263                                      `windows` and `console` are allowed",
1264                                     subsystem));
1265         }
1266         subsystem.to_string()
1267     });
1268
1269     CrateTranslation {
1270         modules: modules,
1271         metadata_module: metadata_module,
1272         link: link_meta,
1273         metadata: metadata,
1274         exported_symbols: exported_symbols,
1275         no_builtins: no_builtins,
1276         linker_info: linker_info,
1277         windows_subsystem: windows_subsystem,
1278     }
1279 }
1280
1281 fn gather_type_sizes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1282     let layout_cache = tcx.layout_cache.borrow();
1283     for (ty, layout) in layout_cache.iter() {
1284
1285         // (delay format until we actually need it)
1286         let record = |kind, opt_discr_size, variants| {
1287             let type_desc = format!("{:?}", ty);
1288             let overall_size = layout.size(&tcx.data_layout);
1289             let align = layout.align(&tcx.data_layout);
1290             tcx.sess.code_stats.borrow_mut().record_type_size(kind,
1291                                                               type_desc,
1292                                                               align,
1293                                                               overall_size,
1294                                                               opt_discr_size,
1295                                                               variants);
1296         };
1297
1298         let (adt_def, substs) = match ty.sty {
1299             ty::TyAdt(ref adt_def, substs) => {
1300                 debug!("print-type-size t: `{:?}` process adt", ty);
1301                 (adt_def, substs)
1302             }
1303
1304             ty::TyClosure(..) => {
1305                 debug!("print-type-size t: `{:?}` record closure", ty);
1306                 record(DataTypeKind::Closure, None, vec![]);
1307                 continue;
1308             }
1309
1310             _ => {
1311                 debug!("print-type-size t: `{:?}` skip non-nominal", ty);
1312                 continue;
1313             }
1314         };
1315
1316         let adt_kind = adt_def.adt_kind();
1317
1318         let build_field_info = |(field_name, field_ty): (ast::Name, Ty), offset: &layout::Size| {
1319             match layout_cache.get(&field_ty) {
1320                 None => bug!("no layout found for field {} type: `{:?}`", field_name, field_ty),
1321                 Some(field_layout) => {
1322                     session::FieldInfo {
1323                         name: field_name.to_string(),
1324                         offset: offset.bytes(),
1325                         size: field_layout.size(&tcx.data_layout).bytes(),
1326                         align: field_layout.align(&tcx.data_layout).abi(),
1327                     }
1328                 }
1329             }
1330         };
1331
1332         let build_primitive_info = |name: ast::Name, value: &layout::Primitive| {
1333             session::VariantInfo {
1334                 name: Some(name.to_string()),
1335                 kind: session::SizeKind::Exact,
1336                 align: value.align(&tcx.data_layout).abi(),
1337                 size: value.size(&tcx.data_layout).bytes(),
1338                 fields: vec![],
1339             }
1340         };
1341
1342         enum Fields<'a> {
1343             WithDiscrim(&'a layout::Struct),
1344             NoDiscrim(&'a layout::Struct),
1345         }
1346
1347         let build_variant_info = |n: Option<ast::Name>, flds: &[(ast::Name, Ty)], layout: Fields| {
1348             let (s, field_offsets) = match layout {
1349                 Fields::WithDiscrim(s) => (s, &s.offsets[1..]),
1350                 Fields::NoDiscrim(s) => (s, &s.offsets[0..]),
1351             };
1352             let field_info: Vec<_> = flds.iter()
1353                 .zip(field_offsets.iter())
1354                 .map(|(&field_name_ty, offset)| build_field_info(field_name_ty, offset))
1355                 .collect();
1356
1357             session::VariantInfo {
1358                 name: n.map(|n|n.to_string()),
1359                 kind: if s.sized {
1360                     session::SizeKind::Exact
1361                 } else {
1362                     session::SizeKind::Min
1363                 },
1364                 align: s.align.abi(),
1365                 size: s.min_size.bytes(),
1366                 fields: field_info,
1367             }
1368         };
1369
1370         match **layout {
1371             Layout::StructWrappedNullablePointer { nonnull: ref variant_layout,
1372                                                    nndiscr,
1373                                                    discrfield: _,
1374                                                    discrfield_source: _ } => {
1375                 debug!("print-type-size t: `{:?}` adt struct-wrapped nullable nndiscr {} is {:?}",
1376                        ty, nndiscr, variant_layout);
1377                 let variant_def = &adt_def.variants[nndiscr as usize];
1378                 let fields: Vec<_> = variant_def.fields.iter()
1379                     .map(|field_def| (field_def.name, field_def.ty(tcx, substs)))
1380                     .collect();
1381                 record(adt_kind.into(),
1382                        None,
1383                        vec![build_variant_info(Some(variant_def.name),
1384                                                &fields,
1385                                                Fields::NoDiscrim(variant_layout))]);
1386             }
1387             Layout::RawNullablePointer { nndiscr, value } => {
1388                 debug!("print-type-size t: `{:?}` adt raw nullable nndiscr {} is {:?}",
1389                        ty, nndiscr, value);
1390                 let variant_def = &adt_def.variants[nndiscr as usize];
1391                 record(adt_kind.into(), None,
1392                        vec![build_primitive_info(variant_def.name, &value)]);
1393             }
1394             Layout::Univariant { variant: ref variant_layout, non_zero: _ } => {
1395                 let variant_names = || {
1396                     adt_def.variants.iter().map(|v|format!("{}", v.name)).collect::<Vec<_>>()
1397                 };
1398                 debug!("print-type-size t: `{:?}` adt univariant {:?} variants: {:?}",
1399                        ty, variant_layout, variant_names());
1400                 assert!(adt_def.variants.len() <= 1,
1401                         "univariant with variants {:?}", variant_names());
1402                 if adt_def.variants.len() == 1 {
1403                     let variant_def = &adt_def.variants[0];
1404                     let fields: Vec<_> = variant_def.fields.iter()
1405                         .map(|field_def| (field_def.name, field_def.ty(tcx, substs)))
1406                         .collect();
1407                     record(adt_kind.into(),
1408                            None,
1409                            vec![build_variant_info(Some(variant_def.name),
1410                                                    &fields,
1411                                                    Fields::NoDiscrim(variant_layout))]);
1412                 } else {
1413                     // (This case arises for *empty* enums; so give it
1414                     // zero variants.)
1415                     record(adt_kind.into(), None, vec![]);
1416                 }
1417             }
1418
1419             Layout::General { ref variants, discr, .. } => {
1420                 debug!("print-type-size t: `{:?}` adt general variants def {} layouts {} {:?}",
1421                        ty, adt_def.variants.len(), variants.len(), variants);
1422                 let variant_infos: Vec<_> = adt_def.variants.iter()
1423                     .zip(variants.iter())
1424                     .map(|(variant_def, variant_layout)| {
1425                         let fields: Vec<_> = variant_def.fields.iter()
1426                             .map(|field_def| (field_def.name, field_def.ty(tcx, substs)))
1427                             .collect();
1428                         build_variant_info(Some(variant_def.name),
1429                                            &fields,
1430                                            Fields::WithDiscrim(variant_layout))
1431                     })
1432                     .collect();
1433                 record(adt_kind.into(), Some(discr.size()), variant_infos);
1434             }
1435
1436             Layout::UntaggedUnion { ref variants } => {
1437                 debug!("print-type-size t: `{:?}` adt union variants {:?}",
1438                        ty, variants);
1439                 // layout does not currently store info about each
1440                 // variant...
1441                 record(adt_kind.into(), None, Vec::new());
1442             }
1443
1444             Layout::CEnum { discr, .. } => {
1445                 debug!("print-type-size t: `{:?}` adt c-like enum", ty);
1446                 let variant_infos: Vec<_> = adt_def.variants.iter()
1447                     .map(|variant_def| {
1448                         build_primitive_info(variant_def.name,
1449                                              &layout::Primitive::Int(discr))
1450                     })
1451                     .collect();
1452                 record(adt_kind.into(), Some(discr.size()), variant_infos);
1453             }
1454
1455             // other cases provide little interesting (i.e. adjustable
1456             // via representation tweaks) size info beyond total size.
1457             Layout::Scalar { .. } |
1458             Layout::Vector { .. } |
1459             Layout::Array { .. } |
1460             Layout::FatPointer { .. } => {
1461                 debug!("print-type-size t: `{:?}` adt other", ty);
1462                 record(adt_kind.into(), None, Vec::new())
1463             }
1464         }
1465     }
1466 }
1467
1468 /// For each CGU, identify if we can reuse an existing object file (or
1469 /// maybe other context).
1470 fn trans_reuse_previous_work_products(scx: &SharedCrateContext,
1471                                       codegen_units: &[CodegenUnit],
1472                                       symbol_map: &SymbolMap)
1473                                       -> Vec<Option<WorkProduct>> {
1474     debug!("trans_reuse_previous_work_products()");
1475     codegen_units
1476         .iter()
1477         .map(|cgu| {
1478             let id = cgu.work_product_id();
1479
1480             let hash = cgu.compute_symbol_name_hash(scx, symbol_map);
1481
1482             debug!("trans_reuse_previous_work_products: id={:?} hash={}", id, hash);
1483
1484             if let Some(work_product) = scx.dep_graph().previous_work_product(&id) {
1485                 if work_product.input_hash == hash {
1486                     debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1487                     return Some(work_product);
1488                 } else {
1489                     if scx.sess().opts.debugging_opts.incremental_info {
1490                         println!("incremental: CGU `{}` invalidated because of \
1491                                   changed partitioning hash.",
1492                                   cgu.name());
1493                     }
1494                     debug!("trans_reuse_previous_work_products: \
1495                             not reusing {:?} because hash changed to {:?}",
1496                            work_product, hash);
1497                 }
1498             }
1499
1500             None
1501         })
1502         .collect()
1503 }
1504
1505 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>)
1506                                                      -> (Vec<CodegenUnit<'tcx>>, SymbolMap<'tcx>) {
1507     let time_passes = scx.sess().time_passes();
1508
1509     let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1510         Some(ref s) => {
1511             let mode_string = s.to_lowercase();
1512             let mode_string = mode_string.trim();
1513             if mode_string == "eager" {
1514                 TransItemCollectionMode::Eager
1515             } else {
1516                 if mode_string != "lazy" {
1517                     let message = format!("Unknown codegen-item collection mode '{}'. \
1518                                            Falling back to 'lazy' mode.",
1519                                            mode_string);
1520                     scx.sess().warn(&message);
1521                 }
1522
1523                 TransItemCollectionMode::Lazy
1524             }
1525         }
1526         None => TransItemCollectionMode::Lazy
1527     };
1528
1529     let (items, inlining_map) =
1530         time(time_passes, "translation item collection", || {
1531             collector::collect_crate_translation_items(&scx, collection_mode)
1532     });
1533
1534     let symbol_map = SymbolMap::build(scx, items.iter().cloned());
1535
1536     let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1537         PartitioningStrategy::PerModule
1538     } else {
1539         PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1540     };
1541
1542     let codegen_units = time(time_passes, "codegen unit partitioning", || {
1543         partitioning::partition(scx,
1544                                 items.iter().cloned(),
1545                                 strategy,
1546                                 &inlining_map)
1547     });
1548
1549     assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1550             scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1551
1552     {
1553         let mut ccx_map = scx.translation_items().borrow_mut();
1554
1555         for trans_item in items.iter().cloned() {
1556             ccx_map.insert(trans_item);
1557         }
1558     }
1559
1560     if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1561         let mut item_to_cgus = FxHashMap();
1562
1563         for cgu in &codegen_units {
1564             for (&trans_item, &linkage) in cgu.items() {
1565                 item_to_cgus.entry(trans_item)
1566                             .or_insert(Vec::new())
1567                             .push((cgu.name().clone(), linkage));
1568             }
1569         }
1570
1571         let mut item_keys: Vec<_> = items
1572             .iter()
1573             .map(|i| {
1574                 let mut output = i.to_string(scx.tcx());
1575                 output.push_str(" @@");
1576                 let mut empty = Vec::new();
1577                 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1578                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1579                 cgus.dedup();
1580                 for &(ref cgu_name, linkage) in cgus.iter() {
1581                     output.push_str(" ");
1582                     output.push_str(&cgu_name[..]);
1583
1584                     let linkage_abbrev = match linkage {
1585                         llvm::Linkage::ExternalLinkage => "External",
1586                         llvm::Linkage::AvailableExternallyLinkage => "Available",
1587                         llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1588                         llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1589                         llvm::Linkage::WeakAnyLinkage => "WeakAny",
1590                         llvm::Linkage::WeakODRLinkage => "WeakODR",
1591                         llvm::Linkage::AppendingLinkage => "Appending",
1592                         llvm::Linkage::InternalLinkage => "Internal",
1593                         llvm::Linkage::PrivateLinkage => "Private",
1594                         llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1595                         llvm::Linkage::CommonLinkage => "Common",
1596                     };
1597
1598                     output.push_str("[");
1599                     output.push_str(linkage_abbrev);
1600                     output.push_str("]");
1601                 }
1602                 output
1603             })
1604             .collect();
1605
1606         item_keys.sort();
1607
1608         for item in item_keys {
1609             println!("TRANS_ITEM {}", item);
1610         }
1611     }
1612
1613     (codegen_units, symbol_map)
1614 }