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