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