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