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