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