]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/base.rs
Auto merge of #44350 - GuillaumeGomez:id-false-positive, r=QuietMisdreavus
[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::{self, Disposition};
32 use back::link;
33 use back::symbol_export;
34 use back::write::{self, OngoingCrateTranslation};
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::middle::cstore::{self, LinkMeta, LinkagePreference};
45 use rustc::hir::map as hir_map;
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::{self, IncrementalHashesMap};
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 libc::c_uint;
81 use std::any::Any;
82 use std::cell::RefCell;
83 use std::ffi::{CStr, CString};
84 use std::str;
85 use std::sync::Arc;
86 use std::time::{Instant, Duration};
87 use std::i32;
88 use std::sync::mpsc;
89 use syntax_pos::Span;
90 use syntax_pos::symbol::InternedString;
91 use syntax::attr;
92 use rustc::hir;
93 use syntax::ast;
94
95 use mir::lvalue::Alignment;
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 // check for the #[rustc_error] annotation, which forces an
663 // error in trans. This is used to write compile-fail tests
664 // that actually test that compilation succeeds without
665 // reporting an error.
666 fn check_for_rustc_errors_attr(tcx: TyCtxt) {
667     if let Some((id, span)) = *tcx.sess.entry_fn.borrow() {
668         let main_def_id = tcx.hir.local_def_id(id);
669
670         if tcx.has_attr(main_def_id, "rustc_error") {
671             tcx.sess.span_fatal(span, "compilation successful");
672         }
673     }
674 }
675
676 /// Create the `main` function which will initialize the rust runtime and call
677 /// users main function.
678 fn maybe_create_entry_wrapper(ccx: &CrateContext) {
679     let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
680         Some((id, span)) => {
681             (ccx.tcx().hir.local_def_id(id), span)
682         }
683         None => return,
684     };
685
686     let instance = Instance::mono(ccx.tcx(), main_def_id);
687
688     if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
689         // We want to create the wrapper in the same codegen unit as Rust's main
690         // function.
691         return;
692     }
693
694     let main_llfn = callee::get_fn(ccx, instance);
695
696     let et = ccx.sess().entry_type.get().unwrap();
697     match et {
698         config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
699         config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
700         config::EntryNone => {}    // Do nothing.
701     }
702
703     fn create_entry_fn(ccx: &CrateContext,
704                        sp: Span,
705                        rust_main: ValueRef,
706                        use_start_lang_item: bool) {
707         let llfty = Type::func(&[ccx.isize_ty(), Type::i8p(ccx).ptr_to()], &ccx.isize_ty());
708
709         if declare::get_defined_value(ccx, "main").is_some() {
710             // FIXME: We should be smart and show a better diagnostic here.
711             ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
712                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
713                       .emit();
714             ccx.sess().abort_if_errors();
715             bug!();
716         }
717         let llfn = declare::declare_cfn(ccx, "main", llfty);
718
719         // `main` should respect same config for frame pointer elimination as rest of code
720         attributes::set_frame_pointer_elimination(ccx, llfn);
721
722         let bld = Builder::new_block(ccx, llfn, "top");
723
724         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
725
726         let (start_fn, args) = if use_start_lang_item {
727             let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
728             let start_instance = Instance::mono(ccx.tcx(), start_def_id);
729             let start_fn = callee::get_fn(ccx, start_instance);
730             (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
731                 get_param(llfn, 1)])
732         } else {
733             debug!("using user-defined start fn");
734             (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
735         };
736
737         let result = bld.call(start_fn, &args, None);
738         bld.ret(result);
739     }
740 }
741
742 fn contains_null(s: &str) -> bool {
743     s.bytes().any(|b| b == 0)
744 }
745
746 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
747                             link_meta: &LinkMeta,
748                             exported_symbols: &NodeSet)
749                             -> (ContextRef, ModuleRef,
750                                 EncodedMetadata, EncodedMetadataHashes) {
751     use std::io::Write;
752     use flate2::Compression;
753     use flate2::write::DeflateEncoder;
754
755     let (metadata_llcx, metadata_llmod) = unsafe {
756         context::create_context_and_module(tcx.sess, "metadata")
757     };
758
759     #[derive(PartialEq, Eq, PartialOrd, Ord)]
760     enum MetadataKind {
761         None,
762         Uncompressed,
763         Compressed
764     }
765
766     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
767         match *ty {
768             config::CrateTypeExecutable |
769             config::CrateTypeStaticlib |
770             config::CrateTypeCdylib => MetadataKind::None,
771
772             config::CrateTypeRlib => MetadataKind::Uncompressed,
773
774             config::CrateTypeDylib |
775             config::CrateTypeProcMacro => MetadataKind::Compressed,
776         }
777     }).max().unwrap();
778
779     if kind == MetadataKind::None {
780         return (metadata_llcx,
781                 metadata_llmod,
782                 EncodedMetadata::new(),
783                 EncodedMetadataHashes::new());
784     }
785
786     let (metadata, hashes) = tcx.encode_metadata(link_meta, exported_symbols);
787     if kind == MetadataKind::Uncompressed {
788         return (metadata_llcx, metadata_llmod, metadata, hashes);
789     }
790
791     assert!(kind == MetadataKind::Compressed);
792     let mut compressed = tcx.metadata_encoding_version();
793     DeflateEncoder::new(&mut compressed, Compression::Fast)
794         .write_all(&metadata.raw_data).unwrap();
795
796     let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
797     let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
798     let name = symbol_export::metadata_symbol_name(tcx);
799     let buf = CString::new(name).unwrap();
800     let llglobal = unsafe {
801         llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
802     };
803     unsafe {
804         llvm::LLVMSetInitializer(llglobal, llconst);
805         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
806         let name = CString::new(section_name).unwrap();
807         llvm::LLVMSetSection(llglobal, name.as_ptr());
808
809         // Also generate a .section directive to force no
810         // flags, at least for ELF outputs, so that the
811         // metadata doesn't get loaded into memory.
812         let directive = format!(".section {}", section_name);
813         let directive = CString::new(directive).unwrap();
814         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
815     }
816     return (metadata_llcx, metadata_llmod, metadata, hashes);
817 }
818
819 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
820 // This is required to satisfy `dllimport` references to static data in .rlibs
821 // when using MSVC linker.  We do this only for data, as linker can fix up
822 // code references on its own.
823 // See #26591, #27438
824 fn create_imps(sess: &Session,
825                llvm_module: &ModuleLlvm) {
826     // The x86 ABI seems to require that leading underscores are added to symbol
827     // names, so we need an extra underscore on 32-bit. There's also a leading
828     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
829     // underscores added in front).
830     let prefix = if sess.target.target.target_pointer_width == "32" {
831         "\x01__imp__"
832     } else {
833         "\x01__imp_"
834     };
835     unsafe {
836         let exported: Vec<_> = iter_globals(llvm_module.llmod)
837                                    .filter(|&val| {
838                                        llvm::LLVMRustGetLinkage(val) ==
839                                        llvm::Linkage::ExternalLinkage &&
840                                        llvm::LLVMIsDeclaration(val) == 0
841                                    })
842                                    .collect();
843
844         let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
845         for val in exported {
846             let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
847             let mut imp_name = prefix.as_bytes().to_vec();
848             imp_name.extend(name.to_bytes());
849             let imp_name = CString::new(imp_name).unwrap();
850             let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
851                                           i8p_ty.to_ref(),
852                                           imp_name.as_ptr() as *const _);
853             llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
854             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
855         }
856     }
857 }
858
859 struct ValueIter {
860     cur: ValueRef,
861     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
862 }
863
864 impl Iterator for ValueIter {
865     type Item = ValueRef;
866
867     fn next(&mut self) -> Option<ValueRef> {
868         let old = self.cur;
869         if !old.is_null() {
870             self.cur = unsafe { (self.step)(old) };
871             Some(old)
872         } else {
873             None
874         }
875     }
876 }
877
878 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
879     unsafe {
880         ValueIter {
881             cur: llvm::LLVMGetFirstGlobal(llmod),
882             step: llvm::LLVMGetNextGlobal,
883         }
884     }
885 }
886
887 /// The context provided lists a set of reachable ids as calculated by
888 /// middle::reachable, but this contains far more ids and symbols than we're
889 /// actually exposing from the object file. This function will filter the set in
890 /// the context to the set of ids which correspond to symbols that are exposed
891 /// from the object file being generated.
892 ///
893 /// This list is later used by linkers to determine the set of symbols needed to
894 /// be exposed from a dynamic library and it's also encoded into the metadata.
895 pub fn find_exported_symbols(tcx: TyCtxt) -> NodeSet {
896     tcx.reachable_set(LOCAL_CRATE).0.iter().cloned().filter(|&id| {
897         // Next, we want to ignore some FFI functions that are not exposed from
898         // this crate. Reachable FFI functions can be lumped into two
899         // categories:
900         //
901         // 1. Those that are included statically via a static library
902         // 2. Those included otherwise (e.g. dynamically or via a framework)
903         //
904         // Although our LLVM module is not literally emitting code for the
905         // statically included symbols, it's an export of our library which
906         // needs to be passed on to the linker and encoded in the metadata.
907         //
908         // As a result, if this id is an FFI item (foreign item) then we only
909         // let it through if it's included statically.
910         match tcx.hir.get(id) {
911             hir_map::NodeForeignItem(..) => {
912                 let def_id = tcx.hir.local_def_id(id);
913                 tcx.is_statically_included_foreign_item(def_id)
914             }
915
916             // Only consider nodes that actually have exported symbols.
917             hir_map::NodeItem(&hir::Item {
918                 node: hir::ItemStatic(..), .. }) |
919             hir_map::NodeItem(&hir::Item {
920                 node: hir::ItemFn(..), .. }) |
921             hir_map::NodeImplItem(&hir::ImplItem {
922                 node: hir::ImplItemKind::Method(..), .. }) => {
923                 let def_id = tcx.hir.local_def_id(id);
924                 let generics = tcx.generics_of(def_id);
925                 let attributes = tcx.get_attrs(def_id);
926                 (generics.parent_types == 0 && generics.types.is_empty()) &&
927                 // Functions marked with #[inline] are only ever translated
928                 // with "internal" linkage and are never exported.
929                 !attr::requests_inline(&attributes)
930             }
931
932             _ => false
933         }
934     }).collect()
935 }
936
937 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
938                              incremental_hashes_map: IncrementalHashesMap,
939                              rx: mpsc::Receiver<Box<Any + Send>>)
940                              -> OngoingCrateTranslation {
941     check_for_rustc_errors_attr(tcx);
942
943     let link_meta = link::build_link_meta(&incremental_hashes_map);
944     let exported_symbol_node_ids = find_exported_symbols(tcx);
945
946     let shared_ccx = SharedCrateContext::new(tcx);
947     // Translate the metadata.
948     let (metadata_llcx, metadata_llmod, metadata, metadata_incr_hashes) =
949         time(tcx.sess.time_passes(), "write metadata", || {
950             write_metadata(tcx, &link_meta, &exported_symbol_node_ids)
951         });
952
953     let metadata_module = ModuleTranslation {
954         name: link::METADATA_MODULE_NAME.to_string(),
955         symbol_name_hash: 0, // we always rebuild metadata, at least for now
956         source: ModuleSource::Translated(ModuleLlvm {
957             llcx: metadata_llcx,
958             llmod: metadata_llmod,
959         }),
960         kind: ModuleKind::Metadata,
961     };
962
963     let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
964         Some(time_graph::TimeGraph::new())
965     } else {
966         None
967     };
968
969     // Skip crate items and just output metadata in -Z no-trans mode.
970     if tcx.sess.opts.debugging_opts.no_trans ||
971        !tcx.sess.opts.output_types.should_trans() {
972         let ongoing_translation = write::start_async_translation(
973             tcx,
974             time_graph.clone(),
975             link_meta,
976             metadata,
977             rx);
978
979         ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
980         ongoing_translation.translation_finished(tcx);
981
982         assert_and_save_dep_graph(tcx,
983                                   incremental_hashes_map,
984                                   metadata_incr_hashes,
985                                   link_meta);
986
987         ongoing_translation.check_for_errors(tcx.sess);
988
989         return ongoing_translation;
990     }
991
992     // Run the translation item collector and partition the collected items into
993     // codegen units.
994     let codegen_units =
995         shared_ccx.tcx().collect_and_partition_translation_items(LOCAL_CRATE).1;
996     let codegen_units = (*codegen_units).clone();
997
998     assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
999
1000     let ongoing_translation = write::start_async_translation(
1001         tcx,
1002         time_graph.clone(),
1003         link_meta,
1004         metadata,
1005         rx);
1006
1007     // Translate an allocator shim, if any
1008     //
1009     // If LTO is enabled and we've got some previous LLVM module we translated
1010     // above, then we can just translate directly into that LLVM module. If not,
1011     // however, we need to create a separate module and trans into that. Note
1012     // that the separate translation is critical for the standard library where
1013     // the rlib's object file doesn't have allocator functions but the dylib
1014     // links in an object file that has allocator functions. When we're
1015     // compiling a final LTO artifact, though, there's no need to worry about
1016     // this as we're not working with this dual "rlib/dylib" functionality.
1017     let allocator_module = if tcx.sess.lto() {
1018         None
1019     } else if let Some(kind) = tcx.sess.allocator_kind.get() {
1020         unsafe {
1021             let (llcx, llmod) =
1022                 context::create_context_and_module(tcx.sess, "allocator");
1023             let modules = ModuleLlvm {
1024                 llmod,
1025                 llcx,
1026             };
1027             time(tcx.sess.time_passes(), "write allocator module", || {
1028                 allocator::trans(tcx, &modules, kind)
1029             });
1030
1031             Some(ModuleTranslation {
1032                 name: link::ALLOCATOR_MODULE_NAME.to_string(),
1033                 symbol_name_hash: 0, // we always rebuild allocator shims
1034                 source: ModuleSource::Translated(modules),
1035                 kind: ModuleKind::Allocator,
1036             })
1037         }
1038     } else {
1039         None
1040     };
1041
1042     if let Some(allocator_module) = allocator_module {
1043         ongoing_translation.submit_pre_translated_module_to_llvm(tcx, allocator_module);
1044     }
1045
1046     ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
1047
1048     // We sort the codegen units by size. This way we can schedule work for LLVM
1049     // a bit more efficiently. Note that "size" is defined rather crudely at the
1050     // moment as it is just the number of TransItems in the CGU, not taking into
1051     // account the size of each TransItem.
1052     let codegen_units = {
1053         let mut codegen_units = codegen_units;
1054         codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
1055         codegen_units
1056     };
1057
1058     let mut total_trans_time = Duration::new(0, 0);
1059     let mut all_stats = Stats::default();
1060
1061     for cgu in codegen_units.into_iter() {
1062         ongoing_translation.wait_for_signal_to_translate_item();
1063         ongoing_translation.check_for_errors(tcx.sess);
1064
1065         let _timing_guard = time_graph
1066             .as_ref()
1067             .map(|time_graph| time_graph.start(write::TRANS_WORKER_TIMELINE,
1068                                                write::TRANS_WORK_PACKAGE_KIND));
1069         let start_time = Instant::now();
1070         all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
1071         total_trans_time += start_time.elapsed();
1072         ongoing_translation.check_for_errors(tcx.sess);
1073     }
1074
1075     ongoing_translation.translation_finished(tcx);
1076
1077     // Since the main thread is sometimes blocked during trans, we keep track
1078     // -Ztime-passes output manually.
1079     print_time_passes_entry(tcx.sess.time_passes(),
1080                             "translate to LLVM IR",
1081                             total_trans_time);
1082
1083     if tcx.sess.opts.incremental.is_some() {
1084         DISPOSITIONS.with(|d| {
1085             assert_module_sources::assert_module_sources(tcx, &d.borrow());
1086         });
1087     }
1088
1089     symbol_names_test::report_symbol_names(tcx);
1090
1091     if shared_ccx.sess().trans_stats() {
1092         println!("--- trans stats ---");
1093         println!("n_glues_created: {}", all_stats.n_glues_created);
1094         println!("n_null_glues: {}", all_stats.n_null_glues);
1095         println!("n_real_glues: {}", all_stats.n_real_glues);
1096
1097         println!("n_fns: {}", all_stats.n_fns);
1098         println!("n_inlines: {}", all_stats.n_inlines);
1099         println!("n_closures: {}", all_stats.n_closures);
1100         println!("fn stats:");
1101         all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
1102         for &(ref name, insns) in all_stats.fn_stats.iter() {
1103             println!("{} insns, {}", insns, *name);
1104         }
1105     }
1106
1107     if shared_ccx.sess().count_llvm_insns() {
1108         for (k, v) in all_stats.llvm_insns.iter() {
1109             println!("{:7} {}", *v, *k);
1110         }
1111     }
1112
1113     ongoing_translation.check_for_errors(tcx.sess);
1114
1115     assert_and_save_dep_graph(tcx,
1116                               incremental_hashes_map,
1117                               metadata_incr_hashes,
1118                               link_meta);
1119     ongoing_translation
1120 }
1121
1122 // FIXME(#42293) hopefully once red/green is enabled we're testing everything
1123 // via a method that doesn't require this!
1124 thread_local!(static DISPOSITIONS: RefCell<Vec<(String, Disposition)>> = Default::default());
1125
1126 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1127                                        incremental_hashes_map: IncrementalHashesMap,
1128                                        metadata_incr_hashes: EncodedMetadataHashes,
1129                                        link_meta: LinkMeta) {
1130     time(tcx.sess.time_passes(),
1131          "assert dep graph",
1132          || rustc_incremental::assert_dep_graph(tcx));
1133
1134     time(tcx.sess.time_passes(),
1135          "serialize dep graph",
1136          || rustc_incremental::save_dep_graph(tcx,
1137                                               incremental_hashes_map,
1138                                               &metadata_incr_hashes,
1139                                               link_meta.crate_hash));
1140 }
1141
1142 #[inline(never)] // give this a place in the profiler
1143 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1144     where I: Iterator<Item=&'a TransItem<'tcx>>
1145 {
1146     let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1147         (trans_item, trans_item.symbol_name(tcx))
1148     }).collect();
1149
1150     (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1151         sym1.cmp(sym2)
1152     });
1153
1154     for pair in (&symbols[..]).windows(2) {
1155         let sym1 = &pair[0].1;
1156         let sym2 = &pair[1].1;
1157
1158         if *sym1 == *sym2 {
1159             let trans_item1 = pair[0].0;
1160             let trans_item2 = pair[1].0;
1161
1162             let span1 = trans_item1.local_span(tcx);
1163             let span2 = trans_item2.local_span(tcx);
1164
1165             // Deterministically select one of the spans for error reporting
1166             let span = match (span1, span2) {
1167                 (Some(span1), Some(span2)) => {
1168                     Some(if span1.lo().0 > span2.lo().0 {
1169                         span1
1170                     } else {
1171                         span2
1172                     })
1173                 }
1174                 (Some(span), None) |
1175                 (None, Some(span)) => Some(span),
1176                 _ => None
1177             };
1178
1179             let error_message = format!("symbol `{}` is already defined", sym1);
1180
1181             if let Some(span) = span {
1182                 tcx.sess.span_fatal(span, &error_message)
1183             } else {
1184                 tcx.sess.fatal(&error_message)
1185             }
1186         }
1187     }
1188 }
1189
1190 fn collect_and_partition_translation_items<'a, 'tcx>(
1191     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1192     cnum: CrateNum,
1193 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
1194 {
1195     assert_eq!(cnum, LOCAL_CRATE);
1196     let time_passes = tcx.sess.time_passes();
1197
1198     let collection_mode = match tcx.sess.opts.debugging_opts.print_trans_items {
1199         Some(ref s) => {
1200             let mode_string = s.to_lowercase();
1201             let mode_string = mode_string.trim();
1202             if mode_string == "eager" {
1203                 TransItemCollectionMode::Eager
1204             } else {
1205                 if mode_string != "lazy" {
1206                     let message = format!("Unknown codegen-item collection mode '{}'. \
1207                                            Falling back to 'lazy' mode.",
1208                                            mode_string);
1209                     tcx.sess.warn(&message);
1210                 }
1211
1212                 TransItemCollectionMode::Lazy
1213             }
1214         }
1215         None => TransItemCollectionMode::Lazy
1216     };
1217
1218     let (items, inlining_map) =
1219         time(time_passes, "translation item collection", || {
1220             collector::collect_crate_translation_items(tcx, collection_mode)
1221     });
1222
1223     assert_symbols_are_distinct(tcx, items.iter());
1224
1225     let strategy = if tcx.sess.opts.debugging_opts.incremental.is_some() {
1226         PartitioningStrategy::PerModule
1227     } else {
1228         PartitioningStrategy::FixedUnitCount(tcx.sess.opts.cg.codegen_units)
1229     };
1230
1231     let codegen_units = time(time_passes, "codegen unit partitioning", || {
1232         partitioning::partition(tcx,
1233                                 items.iter().cloned(),
1234                                 strategy,
1235                                 &inlining_map)
1236             .into_iter()
1237             .map(Arc::new)
1238             .collect::<Vec<_>>()
1239     });
1240
1241     assert!(tcx.sess.opts.cg.codegen_units == codegen_units.len() ||
1242             tcx.sess.opts.debugging_opts.incremental.is_some());
1243
1244     let translation_items: DefIdSet = items.iter().filter_map(|trans_item| {
1245         match *trans_item {
1246             TransItem::Fn(ref instance) => Some(instance.def_id()),
1247             _ => None,
1248         }
1249     }).collect();
1250
1251     if tcx.sess.opts.debugging_opts.print_trans_items.is_some() {
1252         let mut item_to_cgus = FxHashMap();
1253
1254         for cgu in &codegen_units {
1255             for (&trans_item, &linkage) in cgu.items() {
1256                 item_to_cgus.entry(trans_item)
1257                             .or_insert(Vec::new())
1258                             .push((cgu.name().clone(), linkage));
1259             }
1260         }
1261
1262         let mut item_keys: Vec<_> = items
1263             .iter()
1264             .map(|i| {
1265                 let mut output = i.to_string(tcx);
1266                 output.push_str(" @@");
1267                 let mut empty = Vec::new();
1268                 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1269                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1270                 cgus.dedup();
1271                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1272                     output.push_str(" ");
1273                     output.push_str(&cgu_name);
1274
1275                     let linkage_abbrev = match linkage {
1276                         Linkage::External => "External",
1277                         Linkage::AvailableExternally => "Available",
1278                         Linkage::LinkOnceAny => "OnceAny",
1279                         Linkage::LinkOnceODR => "OnceODR",
1280                         Linkage::WeakAny => "WeakAny",
1281                         Linkage::WeakODR => "WeakODR",
1282                         Linkage::Appending => "Appending",
1283                         Linkage::Internal => "Internal",
1284                         Linkage::Private => "Private",
1285                         Linkage::ExternalWeak => "ExternalWeak",
1286                         Linkage::Common => "Common",
1287                     };
1288
1289                     output.push_str("[");
1290                     output.push_str(linkage_abbrev);
1291                     output.push_str("]");
1292                 }
1293                 output
1294             })
1295             .collect();
1296
1297         item_keys.sort();
1298
1299         for item in item_keys {
1300             println!("TRANS_ITEM {}", item);
1301         }
1302     }
1303
1304     (Arc::new(translation_items), Arc::new(codegen_units))
1305 }
1306
1307 impl CrateInfo {
1308     pub fn new(tcx: TyCtxt) -> CrateInfo {
1309         let mut info = CrateInfo {
1310             panic_runtime: None,
1311             compiler_builtins: None,
1312             profiler_runtime: None,
1313             sanitizer_runtime: None,
1314             is_no_builtins: FxHashSet(),
1315             native_libraries: FxHashMap(),
1316             used_libraries: tcx.native_libraries(LOCAL_CRATE),
1317             link_args: tcx.link_args(LOCAL_CRATE),
1318             crate_name: FxHashMap(),
1319             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1320             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1321             used_crate_source: FxHashMap(),
1322         };
1323
1324         for &cnum in tcx.crates().iter() {
1325             info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1326             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1327             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1328             if tcx.is_panic_runtime(cnum) {
1329                 info.panic_runtime = Some(cnum);
1330             }
1331             if tcx.is_compiler_builtins(cnum) {
1332                 info.compiler_builtins = Some(cnum);
1333             }
1334             if tcx.is_profiler_runtime(cnum) {
1335                 info.profiler_runtime = Some(cnum);
1336             }
1337             if tcx.is_sanitizer_runtime(cnum) {
1338                 info.sanitizer_runtime = Some(cnum);
1339             }
1340             if tcx.is_no_builtins(cnum) {
1341                 info.is_no_builtins.insert(cnum);
1342             }
1343         }
1344
1345
1346         return info
1347     }
1348 }
1349
1350 fn is_translated_function(tcx: TyCtxt, id: DefId) -> bool {
1351     // FIXME(#42293) needs red/green tracking to avoid failing a bunch of
1352     // existing tests
1353     tcx.dep_graph.with_ignore(|| {
1354         let (all_trans_items, _) =
1355             tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1356         all_trans_items.contains(&id)
1357     })
1358 }
1359
1360 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1361                                   cgu: InternedString) -> Stats {
1362     // FIXME(#42293) needs red/green tracking to avoid failing a bunch of
1363     // existing tests
1364     let cgu = tcx.dep_graph.with_ignore(|| {
1365         tcx.codegen_unit(cgu)
1366     });
1367
1368     let start_time = Instant::now();
1369     let dep_node = cgu.work_product_dep_node();
1370     let ((stats, module), _) =
1371         tcx.dep_graph.with_task(dep_node,
1372                                 tcx,
1373                                 cgu,
1374                                 module_translation);
1375     let time_to_translate = start_time.elapsed();
1376
1377     if tcx.sess.opts.incremental.is_some() {
1378         DISPOSITIONS.with(|d| {
1379             d.borrow_mut().push(module.disposition());
1380         });
1381     }
1382
1383     // We assume that the cost to run LLVM on a CGU is proportional to
1384     // the time we needed for translating it.
1385     let cost = time_to_translate.as_secs() * 1_000_000_000 +
1386                time_to_translate.subsec_nanos() as u64;
1387
1388     write::submit_translated_module_to_llvm(tcx,
1389                                             module,
1390                                             cost);
1391     return stats;
1392
1393     fn module_translation<'a, 'tcx>(
1394         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1395         cgu: Arc<CodegenUnit<'tcx>>)
1396         -> (Stats, ModuleTranslation)
1397     {
1398         let cgu_name = cgu.name().to_string();
1399         let cgu_id = cgu.work_product_id();
1400         let symbol_name_hash = cgu.compute_symbol_name_hash(tcx);
1401
1402         // Check whether there is a previous work-product we can
1403         // re-use.  Not only must the file exist, and the inputs not
1404         // be dirty, but the hash of the symbols we will generate must
1405         // be the same.
1406         let previous_work_product =
1407             tcx.dep_graph.previous_work_product(&cgu_id).and_then(|work_product| {
1408                 if work_product.input_hash == symbol_name_hash {
1409                     debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1410                     Some(work_product)
1411                 } else {
1412                     if tcx.sess.opts.debugging_opts.incremental_info {
1413                         eprintln!("incremental: CGU `{}` invalidated because of \
1414                                    changed partitioning hash.",
1415                                    cgu.name());
1416                     }
1417                     debug!("trans_reuse_previous_work_products: \
1418                             not reusing {:?} because hash changed to {:?}",
1419                            work_product, symbol_name_hash);
1420                     None
1421                 }
1422             });
1423
1424         if let Some(buf) = previous_work_product {
1425             // Don't need to translate this module.
1426             let module = ModuleTranslation {
1427                 name: cgu_name,
1428                 symbol_name_hash,
1429                 source: ModuleSource::Preexisting(buf.clone()),
1430                 kind: ModuleKind::Regular,
1431             };
1432             return (Stats::default(), module);
1433         }
1434
1435         // Instantiate translation items without filling out definitions yet...
1436         let scx = SharedCrateContext::new(tcx);
1437         let lcx = LocalCrateContext::new(&scx, cgu);
1438         let module = {
1439             let ccx = CrateContext::new(&scx, &lcx);
1440             let trans_items = ccx.codegen_unit()
1441                                  .items_in_deterministic_order(ccx.tcx());
1442             for &(trans_item, (linkage, visibility)) in &trans_items {
1443                 trans_item.predefine(&ccx, linkage, visibility);
1444             }
1445
1446             // ... and now that we have everything pre-defined, fill out those definitions.
1447             for &(trans_item, _) in &trans_items {
1448                 trans_item.define(&ccx);
1449             }
1450
1451             // If this codegen unit contains the main function, also create the
1452             // wrapper here
1453             maybe_create_entry_wrapper(&ccx);
1454
1455             // Run replace-all-uses-with for statics that need it
1456             for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1457                 unsafe {
1458                     let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1459                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1460                     llvm::LLVMDeleteGlobal(old_g);
1461                 }
1462             }
1463
1464             // Create the llvm.used variable
1465             // This variable has type [N x i8*] and is stored in the llvm.metadata section
1466             if !ccx.used_statics().borrow().is_empty() {
1467                 let name = CString::new("llvm.used").unwrap();
1468                 let section = CString::new("llvm.metadata").unwrap();
1469                 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1470
1471                 unsafe {
1472                     let g = llvm::LLVMAddGlobal(ccx.llmod(),
1473                                                 val_ty(array).to_ref(),
1474                                                 name.as_ptr());
1475                     llvm::LLVMSetInitializer(g, array);
1476                     llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1477                     llvm::LLVMSetSection(g, section.as_ptr());
1478                 }
1479             }
1480
1481             // Finalize debuginfo
1482             if ccx.sess().opts.debuginfo != NoDebugInfo {
1483                 debuginfo::finalize(&ccx);
1484             }
1485
1486             let llvm_module = ModuleLlvm {
1487                 llcx: ccx.llcx(),
1488                 llmod: ccx.llmod(),
1489             };
1490
1491             // In LTO mode we inject the allocator shim into the existing
1492             // module.
1493             if ccx.sess().lto() {
1494                 if let Some(kind) = ccx.sess().allocator_kind.get() {
1495                     time(ccx.sess().time_passes(), "write allocator module", || {
1496                         unsafe {
1497                             allocator::trans(ccx.tcx(), &llvm_module, kind);
1498                         }
1499                     });
1500                 }
1501             }
1502
1503             // Adjust exported symbols for MSVC dllimport
1504             if ccx.sess().target.target.options.is_like_msvc &&
1505                ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1506                 create_imps(ccx.sess(), &llvm_module);
1507             }
1508
1509             ModuleTranslation {
1510                 name: cgu_name,
1511                 symbol_name_hash,
1512                 source: ModuleSource::Translated(llvm_module),
1513                 kind: ModuleKind::Regular,
1514             }
1515         };
1516
1517         (lcx.into_stats(), module)
1518     }
1519 }
1520
1521 pub fn provide_local(providers: &mut Providers) {
1522     providers.collect_and_partition_translation_items =
1523         collect_and_partition_translation_items;
1524
1525     providers.is_translated_function = is_translated_function;
1526
1527     providers.codegen_unit = |tcx, name| {
1528         let (_, all) = tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1529         all.iter()
1530             .find(|cgu| *cgu.name() == name)
1531             .cloned()
1532             .expect(&format!("failed to find cgu with name {:?}", name))
1533     };
1534     providers.compile_codegen_unit = compile_codegen_unit;
1535 }
1536
1537 pub fn provide_extern(providers: &mut Providers) {
1538     providers.is_translated_function = is_translated_function;
1539 }
1540
1541 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1542     match linkage {
1543         Linkage::External => llvm::Linkage::ExternalLinkage,
1544         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1545         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1546         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1547         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1548         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1549         Linkage::Appending => llvm::Linkage::AppendingLinkage,
1550         Linkage::Internal => llvm::Linkage::InternalLinkage,
1551         Linkage::Private => llvm::Linkage::PrivateLinkage,
1552         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1553         Linkage::Common => llvm::Linkage::CommonLinkage,
1554     }
1555 }
1556
1557 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1558     match linkage {
1559         Visibility::Default => llvm::Visibility::Default,
1560         Visibility::Hidden => llvm::Visibility::Hidden,
1561         Visibility::Protected => llvm::Visibility::Protected,
1562     }
1563 }
1564
1565 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1566 //            the HashStable trait. Normally DepGraph::with_task() calls are
1567 //            hidden behind queries, but CGU creation is a special case in two
1568 //            ways: (1) it's not a query and (2) CGU are output nodes, so their
1569 //            Fingerprints are not actually needed. It remains to be clarified
1570 //            how exactly this case will be handled in the red/green system but
1571 //            for now we content ourselves with providing a no-op HashStable
1572 //            implementation for CGUs.
1573 mod temp_stable_hash_impls {
1574     use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1575                                                HashStable};
1576     use ModuleTranslation;
1577
1578     impl<HCX> HashStable<HCX> for ModuleTranslation {
1579         fn hash_stable<W: StableHasherResult>(&self,
1580                                               _: &mut HCX,
1581                                               _: &mut StableHasher<W>) {
1582             // do nothing
1583         }
1584     }
1585 }