]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/base.rs
Auto merge of #30641 - tsion:match-range, r=eddyb
[rust.git] / src / librustc_trans / 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 //! Translate the completed AST to the LLVM IR.
11 //!
12 //! Some functions here, such as trans_block and trans_expr, return a value --
13 //! the result of the translation to LLVM -- while others, such as trans_fn,
14 //! trans_impl, and trans_item, are called only for the side effect of adding a
15 //! particular definition to the LLVM IR output we're producing.
16 //!
17 //! Hopefully useful general knowledge about trans:
18 //!
19 //!   * There's no way to find out the Ty type of a ValueRef.  Doing so
20 //!     would be "trying to get the eggs out of an omelette" (credit:
21 //!     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
22 //!     but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
23 //!     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
24
25 #![allow(non_camel_case_types)]
26
27 pub use self::ValueOrigin::*;
28
29 use super::CrateTranslation;
30 use super::ModuleTranslation;
31
32 use back::link::mangle_exported_name;
33 use back::{link, abi};
34 use lint;
35 use llvm::{BasicBlockRef, Linkage, ValueRef, Vector, get_param};
36 use llvm;
37 use middle::cfg;
38 use middle::cstore::CrateStore;
39 use middle::def_id::DefId;
40 use middle::infer;
41 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
42 use middle::weak_lang_items;
43 use middle::pat_util::simple_name;
44 use middle::subst::Substs;
45 use middle::ty::{self, Ty, HasTypeFlags};
46 use rustc::front::map as hir_map;
47 use rustc_mir::mir_map::MirMap;
48 use session::config::{self, NoDebugInfo, FullDebugInfo};
49 use session::Session;
50 use trans::_match;
51 use trans::adt;
52 use trans::attributes;
53 use trans::build::*;
54 use trans::builder::{Builder, noname};
55 use trans::callee;
56 use trans::cleanup::{self, CleanupMethods, DropHint};
57 use trans::closure;
58 use trans::common::{Block, C_bool, C_bytes_in_context, C_i32, C_int, C_uint, C_integral};
59 use trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
60 use trans::common::{CrateContext, DropFlagHintsMap, Field, FunctionContext};
61 use trans::common::{Result, NodeIdAndSpan, VariantInfo};
62 use trans::common::{node_id_type, return_type_is_void};
63 use trans::common::{type_is_immediate, type_is_zero_size, val_ty};
64 use trans::common;
65 use trans::consts;
66 use trans::context::SharedCrateContext;
67 use trans::controlflow;
68 use trans::datum;
69 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
70 use trans::declare;
71 use trans::expr;
72 use trans::foreign;
73 use trans::glue;
74 use trans::intrinsic;
75 use trans::machine;
76 use trans::machine::{llsize_of, llsize_of_real};
77 use trans::meth;
78 use trans::mir;
79 use trans::monomorphize;
80 use trans::tvec;
81 use trans::type_::Type;
82 use trans::type_of;
83 use trans::type_of::*;
84 use trans::value::Value;
85 use util::common::indenter;
86 use util::sha2::Sha256;
87 use util::nodemap::{NodeMap, NodeSet};
88
89 use arena::TypedArena;
90 use libc::c_uint;
91 use std::ffi::{CStr, CString};
92 use std::cell::{Cell, RefCell};
93 use std::collections::{HashMap, HashSet};
94 use std::str;
95 use std::{i8, i16, i32, i64};
96 use syntax::abi::{Rust, RustCall, RustIntrinsic, PlatformIntrinsic, Abi};
97 use syntax::codemap::Span;
98 use syntax::parse::token::InternedString;
99 use syntax::attr::AttrMetaMethods;
100 use syntax::attr;
101 use rustc_front;
102 use rustc_front::intravisit::{self, Visitor};
103 use rustc_front::hir;
104 use syntax::ast;
105
106 thread_local! {
107     static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
108         RefCell::new(None)
109     }
110 }
111
112 pub fn with_insn_ctxt<F>(blk: F)
113     where F: FnOnce(&[&'static str])
114 {
115     TASK_LOCAL_INSN_KEY.with(move |slot| {
116         slot.borrow().as_ref().map(move |s| blk(s));
117     })
118 }
119
120 pub fn init_insn_ctxt() {
121     TASK_LOCAL_INSN_KEY.with(|slot| {
122         *slot.borrow_mut() = Some(Vec::new());
123     });
124 }
125
126 pub struct _InsnCtxt {
127     _cannot_construct_outside_of_this_module: (),
128 }
129
130 impl Drop for _InsnCtxt {
131     fn drop(&mut self) {
132         TASK_LOCAL_INSN_KEY.with(|slot| {
133             match slot.borrow_mut().as_mut() {
134                 Some(ctx) => {
135                     ctx.pop();
136                 }
137                 None => {}
138             }
139         })
140     }
141 }
142
143 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
144     debug!("new InsnCtxt: {}", s);
145     TASK_LOCAL_INSN_KEY.with(|slot| {
146         match slot.borrow_mut().as_mut() {
147             Some(ctx) => ctx.push(s),
148             None => {}
149         }
150     });
151     _InsnCtxt {
152         _cannot_construct_outside_of_this_module: (),
153     }
154 }
155
156 pub struct StatRecorder<'a, 'tcx: 'a> {
157     ccx: &'a CrateContext<'a, 'tcx>,
158     name: Option<String>,
159     istart: usize,
160 }
161
162 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
163     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
164         let istart = ccx.stats().n_llvm_insns.get();
165         StatRecorder {
166             ccx: ccx,
167             name: Some(name),
168             istart: istart,
169         }
170     }
171 }
172
173 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
174     fn drop(&mut self) {
175         if self.ccx.sess().trans_stats() {
176             let iend = self.ccx.stats().n_llvm_insns.get();
177             self.ccx
178                 .stats()
179                 .fn_stats
180                 .borrow_mut()
181                 .push((self.name.take().unwrap(), iend - self.istart));
182             self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
183             // Reset LLVM insn count to avoid compound costs.
184             self.ccx.stats().n_llvm_insns.set(self.istart);
185         }
186     }
187 }
188
189 fn get_extern_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
190                                 fn_ty: Ty<'tcx>,
191                                 name: &str,
192                                 did: DefId)
193                                 -> ValueRef {
194     match ccx.externs().borrow().get(name) {
195         Some(n) => return *n,
196         None => (),
197     }
198
199     let f = declare::declare_rust_fn(ccx, name, fn_ty);
200
201     let attrs = ccx.sess().cstore.item_attrs(did);
202     attributes::from_fn_attrs(ccx, &attrs[..], f);
203
204     ccx.externs().borrow_mut().insert(name.to_string(), f);
205     f
206 }
207
208 pub fn self_type_for_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
209                                        closure_id: DefId,
210                                        fn_ty: Ty<'tcx>)
211                                        -> Ty<'tcx> {
212     let closure_kind = ccx.tcx().closure_kind(closure_id);
213     match closure_kind {
214         ty::FnClosureKind => {
215             ccx.tcx().mk_imm_ref(ccx.tcx().mk_region(ty::ReStatic), fn_ty)
216         }
217         ty::FnMutClosureKind => {
218             ccx.tcx().mk_mut_ref(ccx.tcx().mk_region(ty::ReStatic), fn_ty)
219         }
220         ty::FnOnceClosureKind => fn_ty,
221     }
222 }
223
224 pub fn kind_for_closure(ccx: &CrateContext, closure_id: DefId) -> ty::ClosureKind {
225     *ccx.tcx().tables.borrow().closure_kinds.get(&closure_id).unwrap()
226 }
227
228 pub fn get_extern_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
229                                   did: DefId,
230                                   t: Ty<'tcx>)
231                                   -> ValueRef {
232     let name = ccx.sess().cstore.item_symbol(did);
233     let ty = type_of(ccx, t);
234     match ccx.externs().borrow_mut().get(&name) {
235         Some(n) => return *n,
236         None => (),
237     }
238     // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
239     // FIXME(nagisa): investigate whether it can be changed into define_global
240     let c = declare::declare_global(ccx, &name[..], ty);
241     // Thread-local statics in some other crate need to *always* be linked
242     // against in a thread-local fashion, so we need to be sure to apply the
243     // thread-local attribute locally if it was present remotely. If we
244     // don't do this then linker errors can be generated where the linker
245     // complains that one object files has a thread local version of the
246     // symbol and another one doesn't.
247     for attr in ccx.tcx().get_attrs(did).iter() {
248         if attr.check_name("thread_local") {
249             llvm::set_thread_local(c, true);
250         }
251     }
252     if ccx.use_dll_storage_attrs() {
253         llvm::SetDLLStorageClass(c, llvm::DLLImportStorageClass);
254     }
255     ccx.externs().borrow_mut().insert(name.to_string(), c);
256     return c;
257 }
258
259 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, info_ty: Ty<'tcx>, it: LangItem) -> DefId {
260     match bcx.tcx().lang_items.require(it) {
261         Ok(id) => id,
262         Err(s) => {
263             bcx.sess().fatal(&format!("allocation of `{}` {}", info_ty, s));
264         }
265     }
266 }
267
268 // The following malloc_raw_dyn* functions allocate a box to contain
269 // a given type, but with a potentially dynamic size.
270
271 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
272                                   llty_ptr: Type,
273                                   info_ty: Ty<'tcx>,
274                                   size: ValueRef,
275                                   align: ValueRef,
276                                   debug_loc: DebugLoc)
277                                   -> Result<'blk, 'tcx> {
278     let _icx = push_ctxt("malloc_raw_exchange");
279
280     // Allocate space:
281     let r = callee::trans_lang_call(bcx,
282                                     require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
283                                     &[size, align],
284                                     None,
285                                     debug_loc);
286
287     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
288 }
289
290
291 pub fn bin_op_to_icmp_predicate(ccx: &CrateContext,
292                                 op: hir::BinOp_,
293                                 signed: bool)
294                                 -> llvm::IntPredicate {
295     match op {
296         hir::BiEq => llvm::IntEQ,
297         hir::BiNe => llvm::IntNE,
298         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
299         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
300         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
301         hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
302         op => {
303             ccx.sess()
304                .bug(&format!("comparison_op_to_icmp_predicate: expected comparison operator, \
305                               found {:?}",
306                              op));
307         }
308     }
309 }
310
311 pub fn bin_op_to_fcmp_predicate(ccx: &CrateContext, op: hir::BinOp_) -> llvm::RealPredicate {
312     match op {
313         hir::BiEq => llvm::RealOEQ,
314         hir::BiNe => llvm::RealUNE,
315         hir::BiLt => llvm::RealOLT,
316         hir::BiLe => llvm::RealOLE,
317         hir::BiGt => llvm::RealOGT,
318         hir::BiGe => llvm::RealOGE,
319         op => {
320             ccx.sess()
321                .bug(&format!("comparison_op_to_fcmp_predicate: expected comparison operator, \
322                               found {:?}",
323                              op));
324         }
325     }
326 }
327
328 pub fn compare_fat_ptrs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
329                                     lhs_addr: ValueRef,
330                                     lhs_extra: ValueRef,
331                                     rhs_addr: ValueRef,
332                                     rhs_extra: ValueRef,
333                                     _t: Ty<'tcx>,
334                                     op: hir::BinOp_,
335                                     debug_loc: DebugLoc)
336                                     -> ValueRef {
337     match op {
338         hir::BiEq => {
339             let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
340             let extra_eq = ICmp(bcx, llvm::IntEQ, lhs_extra, rhs_extra, debug_loc);
341             And(bcx, addr_eq, extra_eq, debug_loc)
342         }
343         hir::BiNe => {
344             let addr_eq = ICmp(bcx, llvm::IntNE, lhs_addr, rhs_addr, debug_loc);
345             let extra_eq = ICmp(bcx, llvm::IntNE, lhs_extra, rhs_extra, debug_loc);
346             Or(bcx, addr_eq, extra_eq, debug_loc)
347         }
348         hir::BiLe | hir::BiLt | hir::BiGe | hir::BiGt => {
349             // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
350             let (op, strict_op) = match op {
351                 hir::BiLt => (llvm::IntULT, llvm::IntULT),
352                 hir::BiLe => (llvm::IntULE, llvm::IntULT),
353                 hir::BiGt => (llvm::IntUGT, llvm::IntUGT),
354                 hir::BiGe => (llvm::IntUGE, llvm::IntUGT),
355                 _ => unreachable!(),
356             };
357
358             let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
359             let extra_op = ICmp(bcx, op, lhs_extra, rhs_extra, debug_loc);
360             let addr_eq_extra_op = And(bcx, addr_eq, extra_op, debug_loc);
361
362             let addr_strict = ICmp(bcx, strict_op, lhs_addr, rhs_addr, debug_loc);
363             Or(bcx, addr_strict, addr_eq_extra_op, debug_loc)
364         }
365         _ => {
366             bcx.tcx().sess.bug("unexpected fat ptr binop");
367         }
368     }
369 }
370
371 pub fn compare_scalar_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
372                                         lhs: ValueRef,
373                                         rhs: ValueRef,
374                                         t: Ty<'tcx>,
375                                         op: hir::BinOp_,
376                                         debug_loc: DebugLoc)
377                                         -> ValueRef {
378     match t.sty {
379         ty::TyTuple(ref tys) if tys.is_empty() => {
380             // We don't need to do actual comparisons for nil.
381             // () == () holds but () < () does not.
382             match op {
383                 hir::BiEq | hir::BiLe | hir::BiGe => return C_bool(bcx.ccx(), true),
384                 hir::BiNe | hir::BiLt | hir::BiGt => return C_bool(bcx.ccx(), false),
385                 // refinements would be nice
386                 _ => bcx.sess().bug("compare_scalar_types: must be a comparison operator"),
387             }
388         }
389         ty::TyBareFn(..) | ty::TyBool | ty::TyUint(_) | ty::TyChar => {
390             ICmp(bcx,
391                  bin_op_to_icmp_predicate(bcx.ccx(), op, false),
392                  lhs,
393                  rhs,
394                  debug_loc)
395         }
396         ty::TyRawPtr(mt) if common::type_is_sized(bcx.tcx(), mt.ty) => {
397             ICmp(bcx,
398                  bin_op_to_icmp_predicate(bcx.ccx(), op, false),
399                  lhs,
400                  rhs,
401                  debug_loc)
402         }
403         ty::TyRawPtr(_) => {
404             let lhs_addr = Load(bcx, GEPi(bcx, lhs, &[0, abi::FAT_PTR_ADDR]));
405             let lhs_extra = Load(bcx, GEPi(bcx, lhs, &[0, abi::FAT_PTR_EXTRA]));
406
407             let rhs_addr = Load(bcx, GEPi(bcx, rhs, &[0, abi::FAT_PTR_ADDR]));
408             let rhs_extra = Load(bcx, GEPi(bcx, rhs, &[0, abi::FAT_PTR_EXTRA]));
409             compare_fat_ptrs(bcx,
410                              lhs_addr,
411                              lhs_extra,
412                              rhs_addr,
413                              rhs_extra,
414                              t,
415                              op,
416                              debug_loc)
417         }
418         ty::TyInt(_) => {
419             ICmp(bcx,
420                  bin_op_to_icmp_predicate(bcx.ccx(), op, true),
421                  lhs,
422                  rhs,
423                  debug_loc)
424         }
425         ty::TyFloat(_) => {
426             FCmp(bcx,
427                  bin_op_to_fcmp_predicate(bcx.ccx(), op),
428                  lhs,
429                  rhs,
430                  debug_loc)
431         }
432         // Should never get here, because t is scalar.
433         _ => bcx.sess().bug("non-scalar type passed to compare_scalar_types"),
434     }
435 }
436
437 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
438                                       lhs: ValueRef,
439                                       rhs: ValueRef,
440                                       t: Ty<'tcx>,
441                                       ret_ty: Type,
442                                       op: hir::BinOp_,
443                                       debug_loc: DebugLoc)
444                                       -> ValueRef {
445     let signed = match t.sty {
446         ty::TyFloat(_) => {
447             let cmp = bin_op_to_fcmp_predicate(bcx.ccx(), op);
448             return SExt(bcx, FCmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty);
449         },
450         ty::TyUint(_) => false,
451         ty::TyInt(_) => true,
452         _ => bcx.sess().bug("compare_simd_types: invalid SIMD type"),
453     };
454
455     let cmp = bin_op_to_icmp_predicate(bcx.ccx(), op, signed);
456     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
457     // to get the correctly sized type. This will compile to a single instruction
458     // once the IR is converted to assembly if the SIMD instruction is supported
459     // by the target architecture.
460     SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty)
461 }
462
463 // Iterates through the elements of a structural type.
464 pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
465                                          av: ValueRef,
466                                          t: Ty<'tcx>,
467                                          mut f: F)
468                                          -> Block<'blk, 'tcx>
469     where F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>
470 {
471     let _icx = push_ctxt("iter_structural_ty");
472
473     fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
474                                    repr: &adt::Repr<'tcx>,
475                                    av: adt::MaybeSizedValue,
476                                    variant: ty::VariantDef<'tcx>,
477                                    substs: &Substs<'tcx>,
478                                    f: &mut F)
479                                    -> Block<'blk, 'tcx>
480         where F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>
481     {
482         let _icx = push_ctxt("iter_variant");
483         let tcx = cx.tcx();
484         let mut cx = cx;
485
486         for (i, field) in variant.fields.iter().enumerate() {
487             let arg = monomorphize::field_ty(tcx, substs, field);
488             cx = f(cx,
489                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
490                    arg);
491         }
492         return cx;
493     }
494
495     let value = if common::type_is_sized(cx.tcx(), t) {
496         adt::MaybeSizedValue::sized(av)
497     } else {
498         let data = Load(cx, expr::get_dataptr(cx, av));
499         let info = Load(cx, expr::get_meta(cx, av));
500         adt::MaybeSizedValue::unsized_(data, info)
501     };
502
503     let mut cx = cx;
504     match t.sty {
505         ty::TyStruct(..) => {
506             let repr = adt::represent_type(cx.ccx(), t);
507             let VariantInfo { fields, discr } = VariantInfo::from_ty(cx.tcx(), t, None);
508             for (i, &Field(_, field_ty)) in fields.iter().enumerate() {
509                 let llfld_a = adt::trans_field_ptr(cx, &*repr, value, discr, i);
510
511                 let val = if common::type_is_sized(cx.tcx(), field_ty) {
512                     llfld_a
513                 } else {
514                     let scratch = datum::rvalue_scratch_datum(cx, field_ty, "__fat_ptr_iter");
515                     Store(cx, llfld_a, expr::get_dataptr(cx, scratch.val));
516                     Store(cx, value.meta, expr::get_meta(cx, scratch.val));
517                     scratch.val
518                 };
519                 cx = f(cx, val, field_ty);
520             }
521         }
522         ty::TyClosure(_, ref substs) => {
523             let repr = adt::represent_type(cx.ccx(), t);
524             for (i, upvar_ty) in substs.upvar_tys.iter().enumerate() {
525                 let llupvar = adt::trans_field_ptr(cx, &*repr, value, 0, i);
526                 cx = f(cx, llupvar, upvar_ty);
527             }
528         }
529         ty::TyArray(_, n) => {
530             let (base, len) = tvec::get_fixed_base_and_len(cx, value.value, n);
531             let unit_ty = t.sequence_element_type(cx.tcx());
532             cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
533         }
534         ty::TySlice(_) | ty::TyStr => {
535             let unit_ty = t.sequence_element_type(cx.tcx());
536             cx = tvec::iter_vec_raw(cx, value.value, unit_ty, value.meta, f);
537         }
538         ty::TyTuple(ref args) => {
539             let repr = adt::represent_type(cx.ccx(), t);
540             for (i, arg) in args.iter().enumerate() {
541                 let llfld_a = adt::trans_field_ptr(cx, &*repr, value, 0, i);
542                 cx = f(cx, llfld_a, *arg);
543             }
544         }
545         ty::TyEnum(en, substs) => {
546             let fcx = cx.fcx;
547             let ccx = fcx.ccx;
548
549             let repr = adt::represent_type(ccx, t);
550             let n_variants = en.variants.len();
551
552             // NB: we must hit the discriminant first so that structural
553             // comparison know not to proceed when the discriminants differ.
554
555             match adt::trans_switch(cx, &*repr, av) {
556                 (_match::Single, None) => {
557                     if n_variants != 0 {
558                         assert!(n_variants == 1);
559                         cx = iter_variant(cx, &*repr, adt::MaybeSizedValue::sized(av),
560                                           &en.variants[0], substs, &mut f);
561                     }
562                 }
563                 (_match::Switch, Some(lldiscrim_a)) => {
564                     cx = f(cx, lldiscrim_a, cx.tcx().types.isize);
565
566                     // Create a fall-through basic block for the "else" case of
567                     // the switch instruction we're about to generate. Note that
568                     // we do **not** use an Unreachable instruction here, even
569                     // though most of the time this basic block will never be hit.
570                     //
571                     // When an enum is dropped it's contents are currently
572                     // overwritten to DTOR_DONE, which means the discriminant
573                     // could have changed value to something not within the actual
574                     // range of the discriminant. Currently this function is only
575                     // used for drop glue so in this case we just return quickly
576                     // from the outer function, and any other use case will only
577                     // call this for an already-valid enum in which case the `ret
578                     // void` will never be hit.
579                     let ret_void_cx = fcx.new_temp_block("enum-iter-ret-void");
580                     RetVoid(ret_void_cx, DebugLoc::None);
581                     let llswitch = Switch(cx, lldiscrim_a, ret_void_cx.llbb, n_variants);
582                     let next_cx = fcx.new_temp_block("enum-iter-next");
583
584                     for variant in &en.variants {
585                         let variant_cx = fcx.new_temp_block(&format!("enum-iter-variant-{}",
586                                                                      &variant.disr_val
587                                                                              .to_string()));
588                         let case_val = adt::trans_case(cx, &*repr, variant.disr_val);
589                         AddCase(llswitch, case_val, variant_cx.llbb);
590                         let variant_cx = iter_variant(variant_cx,
591                                                       &*repr,
592                                                       value,
593                                                       variant,
594                                                       substs,
595                                                       &mut f);
596                         Br(variant_cx, next_cx.llbb, DebugLoc::None);
597                     }
598                     cx = next_cx;
599                 }
600                 _ => ccx.sess().unimpl("value from adt::trans_switch in iter_structural_ty"),
601             }
602         }
603         _ => {
604             cx.sess().unimpl(&format!("type in iter_structural_ty: {}", t))
605         }
606     }
607     return cx;
608 }
609
610
611 /// Retrieve the information we are losing (making dynamic) in an unsizing
612 /// adjustment.
613 ///
614 /// The `old_info` argument is a bit funny. It is intended for use
615 /// in an upcast, where the new vtable for an object will be drived
616 /// from the old one.
617 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
618                                 source: Ty<'tcx>,
619                                 target: Ty<'tcx>,
620                                 old_info: Option<ValueRef>,
621                                 param_substs: &'tcx Substs<'tcx>)
622                                 -> ValueRef {
623     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
624     match (&source.sty, &target.sty) {
625         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
626         (&ty::TyTrait(_), &ty::TyTrait(_)) => {
627             // For now, upcasts are limited to changes in marker
628             // traits, and hence never actually require an actual
629             // change to the vtable.
630             old_info.expect("unsized_info: missing old info for trait upcast")
631         }
632         (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
633             // Note that we preserve binding levels here:
634             let substs = principal.0.substs.with_self_ty(source).erase_regions();
635             let substs = ccx.tcx().mk_substs(substs);
636             let trait_ref = ty::Binder(ty::TraitRef {
637                 def_id: principal.def_id(),
638                 substs: substs,
639             });
640             consts::ptrcast(meth::get_vtable(ccx, trait_ref, param_substs),
641                             Type::vtable_ptr(ccx))
642         }
643         _ => ccx.sess().bug(&format!("unsized_info: invalid unsizing {:?} -> {:?}",
644                                      source,
645                                      target)),
646     }
647 }
648
649 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
650 pub fn unsize_thin_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
651                                    src: ValueRef,
652                                    src_ty: Ty<'tcx>,
653                                    dst_ty: Ty<'tcx>)
654                                    -> (ValueRef, ValueRef) {
655     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
656     match (&src_ty.sty, &dst_ty.sty) {
657         (&ty::TyBox(a), &ty::TyBox(b)) |
658         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
659          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
660         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
661          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
662         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
663          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
664             assert!(common::type_is_sized(bcx.tcx(), a));
665             let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), b).ptr_to();
666             (PointerCast(bcx, src, ptr_ty),
667              unsized_info(bcx.ccx(), a, b, None, bcx.fcx.param_substs))
668         }
669         _ => bcx.sess().bug("unsize_thin_ptr: called on bad types"),
670     }
671 }
672
673 /// Coerce `src`, which is a reference to a value of type `src_ty`,
674 /// to a value of type `dst_ty` and store the result in `dst`
675 pub fn coerce_unsized_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
676                                        src: ValueRef,
677                                        src_ty: Ty<'tcx>,
678                                        dst: ValueRef,
679                                        dst_ty: Ty<'tcx>) {
680     match (&src_ty.sty, &dst_ty.sty) {
681         (&ty::TyBox(..), &ty::TyBox(..)) |
682         (&ty::TyRef(..), &ty::TyRef(..)) |
683         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
684         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
685             let (base, info) = if common::type_is_fat_ptr(bcx.tcx(), src_ty) {
686                 // fat-ptr to fat-ptr unsize preserves the vtable
687                 load_fat_ptr(bcx, src, src_ty)
688             } else {
689                 let base = load_ty(bcx, src, src_ty);
690                 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
691             };
692             store_fat_ptr(bcx, base, info, dst, dst_ty);
693         }
694
695         // This can be extended to enums and tuples in the future.
696         // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
697         (&ty::TyStruct(def_a, _), &ty::TyStruct(def_b, _)) => {
698             assert_eq!(def_a, def_b);
699
700             let src_repr = adt::represent_type(bcx.ccx(), src_ty);
701             let src_fields = match &*src_repr {
702                 &adt::Repr::Univariant(ref s, _) => &s.fields,
703                 _ => bcx.sess().bug("struct has non-univariant repr"),
704             };
705             let dst_repr = adt::represent_type(bcx.ccx(), dst_ty);
706             let dst_fields = match &*dst_repr {
707                 &adt::Repr::Univariant(ref s, _) => &s.fields,
708                 _ => bcx.sess().bug("struct has non-univariant repr"),
709             };
710
711             let src = adt::MaybeSizedValue::sized(src);
712             let dst = adt::MaybeSizedValue::sized(dst);
713
714             let iter = src_fields.iter().zip(dst_fields).enumerate();
715             for (i, (src_fty, dst_fty)) in iter {
716                 if type_is_zero_size(bcx.ccx(), dst_fty) {
717                     continue;
718                 }
719
720                 let src_f = adt::trans_field_ptr(bcx, &src_repr, src, 0, i);
721                 let dst_f = adt::trans_field_ptr(bcx, &dst_repr, dst, 0, i);
722                 if src_fty == dst_fty {
723                     memcpy_ty(bcx, dst_f, src_f, src_fty);
724                 } else {
725                     coerce_unsized_into(bcx, src_f, src_fty, dst_f, dst_fty);
726                 }
727             }
728         }
729         _ => bcx.sess().bug(&format!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
730                                      src_ty,
731                                      dst_ty)),
732     }
733 }
734
735 pub fn cast_shift_expr_rhs(cx: Block, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
736     cast_shift_rhs(op, lhs, rhs, |a, b| Trunc(cx, a, b), |a, b| ZExt(cx, a, b))
737 }
738
739 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
740     cast_shift_rhs(op,
741                    lhs,
742                    rhs,
743                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
744                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
745 }
746
747 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
748                         lhs: ValueRef,
749                         rhs: ValueRef,
750                         trunc: F,
751                         zext: G)
752                         -> ValueRef
753     where F: FnOnce(ValueRef, Type) -> ValueRef,
754           G: FnOnce(ValueRef, Type) -> ValueRef
755 {
756     // Shifts may have any size int on the rhs
757     if rustc_front::util::is_shift_binop(op) {
758         let mut rhs_llty = val_ty(rhs);
759         let mut lhs_llty = val_ty(lhs);
760         if rhs_llty.kind() == Vector {
761             rhs_llty = rhs_llty.element_type()
762         }
763         if lhs_llty.kind() == Vector {
764             lhs_llty = lhs_llty.element_type()
765         }
766         let rhs_sz = rhs_llty.int_width();
767         let lhs_sz = lhs_llty.int_width();
768         if lhs_sz < rhs_sz {
769             trunc(rhs, lhs_llty)
770         } else if lhs_sz > rhs_sz {
771             // FIXME (#1877: If shifting by negative
772             // values becomes not undefined then this is wrong.
773             zext(rhs, lhs_llty)
774         } else {
775             rhs
776         }
777     } else {
778         rhs
779     }
780 }
781
782 pub fn llty_and_min_for_signed_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
783                                               val_t: Ty<'tcx>)
784                                               -> (Type, u64) {
785     match val_t.sty {
786         ty::TyInt(t) => {
787             let llty = Type::int_from_ty(cx.ccx(), t);
788             let min = match t {
789                 ast::TyIs if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
790                 ast::TyIs => i64::MIN as u64,
791                 ast::TyI8 => i8::MIN as u64,
792                 ast::TyI16 => i16::MIN as u64,
793                 ast::TyI32 => i32::MIN as u64,
794                 ast::TyI64 => i64::MIN as u64,
795             };
796             (llty, min)
797         }
798         _ => unreachable!(),
799     }
800 }
801
802 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
803                                              call_info: NodeIdAndSpan,
804                                              divrem: hir::BinOp,
805                                              lhs: ValueRef,
806                                              rhs: ValueRef,
807                                              rhs_t: Ty<'tcx>)
808                                              -> Block<'blk, 'tcx> {
809     let (zero_text, overflow_text) = if divrem.node == hir::BiDiv {
810         ("attempted to divide by zero",
811          "attempted to divide with overflow")
812     } else {
813         ("attempted remainder with a divisor of zero",
814          "attempted remainder with overflow")
815     };
816     let debug_loc = call_info.debug_loc();
817
818     let (is_zero, is_signed) = match rhs_t.sty {
819         ty::TyInt(t) => {
820             let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0, false);
821             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
822         }
823         ty::TyUint(t) => {
824             let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0, false);
825             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
826         }
827         ty::TyStruct(def, _) if def.is_simd() => {
828             let mut res = C_bool(cx.ccx(), false);
829             for i in 0..rhs_t.simd_size(cx.tcx()) {
830                 res = Or(cx,
831                          res,
832                          IsNull(cx, ExtractElement(cx, rhs, C_int(cx.ccx(), i as i64))),
833                          debug_loc);
834             }
835             (res, false)
836         }
837         _ => {
838             cx.sess().bug(&format!("fail-if-zero on unexpected type: {}", rhs_t));
839         }
840     };
841     let bcx = with_cond(cx, is_zero, |bcx| {
842         controlflow::trans_fail(bcx, call_info, InternedString::new(zero_text))
843     });
844
845     // To quote LLVM's documentation for the sdiv instruction:
846     //
847     //      Division by zero leads to undefined behavior. Overflow also leads
848     //      to undefined behavior; this is a rare case, but can occur, for
849     //      example, by doing a 32-bit division of -2147483648 by -1.
850     //
851     // In order to avoid undefined behavior, we perform runtime checks for
852     // signed division/remainder which would trigger overflow. For unsigned
853     // integers, no action beyond checking for zero need be taken.
854     if is_signed {
855         let (llty, min) = llty_and_min_for_signed_ty(cx, rhs_t);
856         let minus_one = ICmp(bcx,
857                              llvm::IntEQ,
858                              rhs,
859                              C_integral(llty, !0, false),
860                              debug_loc);
861         with_cond(bcx, minus_one, |bcx| {
862             let is_min = ICmp(bcx,
863                               llvm::IntEQ,
864                               lhs,
865                               C_integral(llty, min, true),
866                               debug_loc);
867             with_cond(bcx, is_min, |bcx| {
868                 controlflow::trans_fail(bcx, call_info, InternedString::new(overflow_text))
869             })
870         })
871     } else {
872         bcx
873     }
874 }
875
876 pub fn trans_external_path<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
877                                      did: DefId,
878                                      t: Ty<'tcx>)
879                                      -> ValueRef {
880     let name = ccx.sess().cstore.item_symbol(did);
881     match t.sty {
882         ty::TyBareFn(_, ref fn_ty) => {
883             match ccx.sess().target.target.adjust_abi(fn_ty.abi) {
884                 Rust | RustCall => {
885                     get_extern_rust_fn(ccx, t, &name[..], did)
886                 }
887                 RustIntrinsic | PlatformIntrinsic => {
888                     ccx.sess().bug("unexpected intrinsic in trans_external_path")
889                 }
890                 _ => {
891                     let attrs = ccx.sess().cstore.item_attrs(did);
892                     foreign::register_foreign_item_fn(ccx, fn_ty.abi, t, &name, &attrs)
893                 }
894             }
895         }
896         _ => {
897             get_extern_const(ccx, did, t)
898         }
899     }
900 }
901
902 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
903                           llfn: ValueRef,
904                           llargs: &[ValueRef],
905                           fn_ty: Ty<'tcx>,
906                           debug_loc: DebugLoc)
907                           -> (ValueRef, Block<'blk, 'tcx>) {
908     let _icx = push_ctxt("invoke_");
909     if bcx.unreachable.get() {
910         return (C_null(Type::i8(bcx.ccx())), bcx);
911     }
912
913     let attributes = attributes::from_fn_type(bcx.ccx(), fn_ty);
914
915     match bcx.opt_node_id {
916         None => {
917             debug!("invoke at ???");
918         }
919         Some(id) => {
920             debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
921         }
922     }
923
924     if need_invoke(bcx) {
925         debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
926         for &llarg in llargs {
927             debug!("arg: {}", bcx.val_to_string(llarg));
928         }
929         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
930         let landing_pad = bcx.fcx.get_landing_pad();
931
932         let llresult = Invoke(bcx,
933                               llfn,
934                               &llargs[..],
935                               normal_bcx.llbb,
936                               landing_pad,
937                               Some(attributes),
938                               debug_loc);
939         return (llresult, normal_bcx);
940     } else {
941         debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
942         for &llarg in llargs {
943             debug!("arg: {}", bcx.val_to_string(llarg));
944         }
945
946         let llresult = Call(bcx, llfn, &llargs[..], Some(attributes), debug_loc);
947         return (llresult, bcx);
948     }
949 }
950
951 /// Returns whether this session's target will use SEH-based unwinding.
952 ///
953 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
954 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
955 /// 64-bit MinGW) instead of "full SEH".
956 pub fn wants_msvc_seh(sess: &Session) -> bool {
957     sess.target.target.options.is_like_msvc && sess.target.target.arch == "x86"
958 }
959
960 pub fn need_invoke(bcx: Block) -> bool {
961     // FIXME(#25869) currently SEH-based unwinding is pretty buggy in LLVM and
962     //               is being overhauled as this is being written. Until that
963     //               time such that upstream LLVM's implementation is more solid
964     //               and we start binding it we need to skip invokes for any
965     //               target which wants SEH-based unwinding.
966     if bcx.sess().no_landing_pads() || wants_msvc_seh(bcx.sess()) {
967         return false;
968     }
969
970     // Avoid using invoke if we are already inside a landing pad.
971     if bcx.is_lpad {
972         return false;
973     }
974
975     bcx.fcx.needs_invoke()
976 }
977
978 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, t: Ty<'tcx>) -> ValueRef {
979     let _icx = push_ctxt("load_if_immediate");
980     if type_is_immediate(cx.ccx(), t) {
981         return load_ty(cx, v, t);
982     }
983     return v;
984 }
985
986 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
987 /// differs from the type used for SSA values. Also handles various special cases where the type
988 /// gives us better information about what we are loading.
989 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
990     if cx.unreachable.get() || type_is_zero_size(cx.ccx(), t) {
991         return C_undef(type_of::type_of(cx.ccx(), t));
992     }
993
994     let ptr = to_arg_ty_ptr(cx, ptr, t);
995     let align = type_of::align_of(cx.ccx(), t);
996
997     if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
998         let load = Load(cx, ptr);
999         unsafe {
1000             llvm::LLVMSetAlignment(load, align);
1001         }
1002         return load;
1003     }
1004
1005     unsafe {
1006         let global = llvm::LLVMIsAGlobalVariable(ptr);
1007         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
1008             let val = llvm::LLVMGetInitializer(global);
1009             if !val.is_null() {
1010                 return to_arg_ty(cx, val, t);
1011             }
1012         }
1013     }
1014
1015     let val = if t.is_bool() {
1016         LoadRangeAssert(cx, ptr, 0, 2, llvm::False)
1017     } else if t.is_char() {
1018         // a char is a Unicode codepoint, and so takes values from 0
1019         // to 0x10FFFF inclusive only.
1020         LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
1021     } else if (t.is_region_ptr() || t.is_unique()) && !common::type_is_fat_ptr(cx.tcx(), t) {
1022         LoadNonNull(cx, ptr)
1023     } else {
1024         Load(cx, ptr)
1025     };
1026
1027     unsafe {
1028         llvm::LLVMSetAlignment(val, align);
1029     }
1030
1031     to_arg_ty(cx, val, t)
1032 }
1033
1034 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
1035 /// differs from the type used for SSA values.
1036 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
1037     if cx.unreachable.get() {
1038         return;
1039     }
1040
1041     debug!("store_ty: {} : {:?} <- {}",
1042            cx.val_to_string(dst),
1043            t,
1044            cx.val_to_string(v));
1045
1046     if common::type_is_fat_ptr(cx.tcx(), t) {
1047         Store(cx,
1048               ExtractValue(cx, v, abi::FAT_PTR_ADDR),
1049               expr::get_dataptr(cx, dst));
1050         Store(cx,
1051               ExtractValue(cx, v, abi::FAT_PTR_EXTRA),
1052               expr::get_meta(cx, dst));
1053     } else {
1054         let store = Store(cx, from_arg_ty(cx, v, t), to_arg_ty_ptr(cx, dst, t));
1055         unsafe {
1056             llvm::LLVMSetAlignment(store, type_of::align_of(cx.ccx(), t));
1057         }
1058     }
1059 }
1060
1061 pub fn store_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
1062                                  data: ValueRef,
1063                                  extra: ValueRef,
1064                                  dst: ValueRef,
1065                                  _ty: Ty<'tcx>) {
1066     // FIXME: emit metadata
1067     Store(cx, data, expr::get_dataptr(cx, dst));
1068     Store(cx, extra, expr::get_meta(cx, dst));
1069 }
1070
1071 pub fn load_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
1072                                 src: ValueRef,
1073                                 _ty: Ty<'tcx>)
1074                                 -> (ValueRef, ValueRef) {
1075     // FIXME: emit metadata
1076     (Load(cx, expr::get_dataptr(cx, src)),
1077      Load(cx, expr::get_meta(cx, src)))
1078 }
1079
1080 pub fn from_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
1081     if ty.is_bool() {
1082         ZExt(bcx, val, Type::i8(bcx.ccx()))
1083     } else {
1084         val
1085     }
1086 }
1087
1088 pub fn to_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
1089     if ty.is_bool() {
1090         Trunc(bcx, val, Type::i1(bcx.ccx()))
1091     } else {
1092         val
1093     }
1094 }
1095
1096 pub fn to_arg_ty_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef, ty: Ty<'tcx>) -> ValueRef {
1097     if type_is_immediate(bcx.ccx(), ty) && type_of::type_of(bcx.ccx(), ty).is_aggregate() {
1098         // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
1099         // for this leads to bad optimizations, so its arg type is an appropriately sized integer
1100         // and we have to convert it
1101         BitCast(bcx, ptr, type_of::arg_type_of(bcx.ccx(), ty).ptr_to())
1102     } else {
1103         ptr
1104     }
1105 }
1106
1107 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &hir::Local) -> Block<'blk, 'tcx> {
1108     debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
1109     let _indenter = indenter();
1110     let _icx = push_ctxt("init_local");
1111     _match::store_local(bcx, local)
1112 }
1113
1114 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1115                              is_lpad: bool,
1116                              llbb: BasicBlockRef)
1117                              -> Block<'blk, 'tcx> {
1118     common::BlockS::new(llbb, is_lpad, None, fcx)
1119 }
1120
1121 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, val: ValueRef, f: F) -> Block<'blk, 'tcx>
1122     where F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>
1123 {
1124     let _icx = push_ctxt("with_cond");
1125
1126     if bcx.unreachable.get() || common::const_to_opt_uint(val) == Some(0) {
1127         return bcx;
1128     }
1129
1130     let fcx = bcx.fcx;
1131     let next_cx = fcx.new_temp_block("next");
1132     let cond_cx = fcx.new_temp_block("cond");
1133     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
1134     let after_cx = f(cond_cx);
1135     if !after_cx.terminated.get() {
1136         Br(after_cx, next_cx.llbb, DebugLoc::None);
1137     }
1138     next_cx
1139 }
1140
1141 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
1142     if cx.sess().opts.optimize == config::No {
1143         return;
1144     }
1145
1146     let _icx = push_ctxt("lifetime_start");
1147     let ccx = cx.ccx();
1148
1149     let size = machine::llsize_of_alloc(ccx, val_ty(ptr).element_type());
1150     if size == 0 {
1151         return;
1152     }
1153
1154     let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1155     let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
1156     Call(cx,
1157          lifetime_start,
1158          &[C_u64(ccx, size), ptr],
1159          None,
1160          DebugLoc::None);
1161 }
1162
1163 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
1164     if cx.sess().opts.optimize == config::No {
1165         return;
1166     }
1167
1168     let _icx = push_ctxt("lifetime_end");
1169     let ccx = cx.ccx();
1170
1171     let size = machine::llsize_of_alloc(ccx, val_ty(ptr).element_type());
1172     if size == 0 {
1173         return;
1174     }
1175
1176     let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1177     let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
1178     Call(cx,
1179          lifetime_end,
1180          &[C_u64(ccx, size), ptr],
1181          None,
1182          DebugLoc::None);
1183 }
1184
1185 // Generates code for resumption of unwind at the end of a landing pad.
1186 pub fn trans_unwind_resume(bcx: Block, lpval: ValueRef) {
1187     if !bcx.sess().target.target.options.custom_unwind_resume {
1188         Resume(bcx, lpval);
1189     } else {
1190         let exc_ptr = ExtractValue(bcx, lpval, 0);
1191         let llunwresume = bcx.fcx.eh_unwind_resume();
1192         Call(bcx, llunwresume, &[exc_ptr], None, DebugLoc::None);
1193         Unreachable(bcx);
1194     }
1195 }
1196
1197
1198 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1199     let _icx = push_ctxt("call_memcpy");
1200     let ccx = cx.ccx();
1201     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
1202     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
1203     let memcpy = ccx.get_intrinsic(&key);
1204     let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1205     let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1206     let size = IntCast(cx, n_bytes, ccx.int_type());
1207     let align = C_i32(ccx, align as i32);
1208     let volatile = C_bool(ccx, false);
1209     Call(cx,
1210          memcpy,
1211          &[dst_ptr, src_ptr, size, align, volatile],
1212          None,
1213          DebugLoc::None);
1214 }
1215
1216 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, dst: ValueRef, src: ValueRef, t: Ty<'tcx>) {
1217     let _icx = push_ctxt("memcpy_ty");
1218     let ccx = bcx.ccx();
1219
1220     if type_is_zero_size(ccx, t) {
1221         return;
1222     }
1223
1224     if t.is_structural() {
1225         let llty = type_of::type_of(ccx, t);
1226         let llsz = llsize_of(ccx, llty);
1227         let llalign = type_of::align_of(ccx, t);
1228         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1229     } else if common::type_is_fat_ptr(bcx.tcx(), t) {
1230         let (data, extra) = load_fat_ptr(bcx, src, t);
1231         store_fat_ptr(bcx, data, extra, dst, t);
1232     } else {
1233         store_ty(bcx, load_ty(bcx, src, t), dst, t);
1234     }
1235 }
1236
1237 pub fn drop_done_fill_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1238     if cx.unreachable.get() {
1239         return;
1240     }
1241     let _icx = push_ctxt("drop_done_fill_mem");
1242     let bcx = cx;
1243     memfill(&B(bcx), llptr, t, adt::DTOR_DONE);
1244 }
1245
1246 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1247     if cx.unreachable.get() {
1248         return;
1249     }
1250     let _icx = push_ctxt("init_zero_mem");
1251     let bcx = cx;
1252     memfill(&B(bcx), llptr, t, 0);
1253 }
1254
1255 // Always use this function instead of storing a constant byte to the memory
1256 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
1257 // allocation for large data structures, and the generated code will be
1258 // awful. (A telltale sign of this is large quantities of
1259 // `mov [byte ptr foo],0` in the generated code.)
1260 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
1261     let _icx = push_ctxt("memfill");
1262     let ccx = b.ccx;
1263
1264     let llty = type_of::type_of(ccx, ty);
1265     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
1266     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
1267
1268     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1269     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1270     let llzeroval = C_u8(ccx, byte);
1271     let size = machine::llsize_of(ccx, llty);
1272     let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
1273     let volatile = C_bool(ccx, false);
1274     b.call(llintrinsicfn,
1275            &[llptr, llzeroval, size, align, volatile],
1276            None);
1277 }
1278
1279 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, name: &str) -> ValueRef {
1280     let _icx = push_ctxt("alloc_ty");
1281     let ccx = bcx.ccx();
1282     let ty = type_of::type_of(ccx, t);
1283     assert!(!t.has_param_types());
1284     alloca(bcx, ty, name)
1285 }
1286
1287 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
1288     let _icx = push_ctxt("alloca");
1289     if cx.unreachable.get() {
1290         unsafe {
1291             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1292         }
1293     }
1294     debuginfo::clear_source_location(cx.fcx);
1295     Alloca(cx, ty, name)
1296 }
1297
1298 pub fn set_value_name(val: ValueRef, name: &str) {
1299     unsafe {
1300         let name = CString::new(name).unwrap();
1301         llvm::LLVMSetValueName(val, name.as_ptr());
1302     }
1303 }
1304
1305 // Creates the alloca slot which holds the pointer to the slot for the final return value
1306 pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1307                                           output_type: Ty<'tcx>)
1308                                           -> ValueRef {
1309     let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1310
1311     // We create an alloca to hold a pointer of type `output_type`
1312     // which will hold the pointer to the right alloca which has the
1313     // final ret value
1314     if fcx.needs_ret_allocas {
1315         // Let's create the stack slot
1316         let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1317
1318         // and if we're using an out pointer, then store that in our newly made slot
1319         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1320             let outptr = get_param(fcx.llfn, 0);
1321
1322             let b = fcx.ccx.builder();
1323             b.position_before(fcx.alloca_insert_pt.get().unwrap());
1324             b.store(outptr, slot);
1325         }
1326
1327         slot
1328
1329     // But if there are no nested returns, we skip the indirection and have a single
1330     // retslot
1331     } else {
1332         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1333             get_param(fcx.llfn, 0)
1334         } else {
1335             AllocaFcx(fcx, lloutputtype, "sret_slot")
1336         }
1337     }
1338 }
1339
1340 struct FindNestedReturn {
1341     found: bool,
1342 }
1343
1344 impl FindNestedReturn {
1345     fn new() -> FindNestedReturn {
1346         FindNestedReturn {
1347             found: false,
1348         }
1349     }
1350 }
1351
1352 impl<'v> Visitor<'v> for FindNestedReturn {
1353     fn visit_expr(&mut self, e: &hir::Expr) {
1354         match e.node {
1355             hir::ExprRet(..) => {
1356                 self.found = true;
1357             }
1358             _ => intravisit::walk_expr(self, e),
1359         }
1360     }
1361 }
1362
1363 fn build_cfg(tcx: &ty::ctxt, id: ast::NodeId) -> (ast::NodeId, Option<cfg::CFG>) {
1364     let blk = match tcx.map.find(id) {
1365         Some(hir_map::NodeItem(i)) => {
1366             match i.node {
1367                 hir::ItemFn(_, _, _, _, _, ref blk) => {
1368                     blk
1369                 }
1370                 _ => tcx.sess.bug("unexpected item variant in has_nested_returns"),
1371             }
1372         }
1373         Some(hir_map::NodeTraitItem(trait_item)) => {
1374             match trait_item.node {
1375                 hir::MethodTraitItem(_, Some(ref body)) => body,
1376                 _ => {
1377                     tcx.sess.bug("unexpected variant: trait item other than a provided method in \
1378                                   has_nested_returns")
1379                 }
1380             }
1381         }
1382         Some(hir_map::NodeImplItem(impl_item)) => {
1383             match impl_item.node {
1384                 hir::ImplItemKind::Method(_, ref body) => body,
1385                 _ => {
1386                     tcx.sess.bug("unexpected variant: non-method impl item in has_nested_returns")
1387                 }
1388             }
1389         }
1390         Some(hir_map::NodeExpr(e)) => {
1391             match e.node {
1392                 hir::ExprClosure(_, _, ref blk) => blk,
1393                 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns"),
1394             }
1395         }
1396         Some(hir_map::NodeVariant(..)) |
1397         Some(hir_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1398
1399         // glue, shims, etc
1400         None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1401
1402         _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
1403                                    tcx.map.path_to_string(id))),
1404     };
1405
1406     (blk.id, Some(cfg::CFG::new(tcx, blk)))
1407 }
1408
1409 // Checks for the presence of "nested returns" in a function.
1410 // Nested returns are when the inner expression of a return expression
1411 // (the 'expr' in 'return expr') contains a return expression. Only cases
1412 // where the outer return is actually reachable are considered. Implicit
1413 // returns from the end of blocks are considered as well.
1414 //
1415 // This check is needed to handle the case where the inner expression is
1416 // part of a larger expression that may have already partially-filled the
1417 // return slot alloca. This can cause errors related to clean-up due to
1418 // the clobbering of the existing value in the return slot.
1419 fn has_nested_returns(tcx: &ty::ctxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1420     for index in cfg.graph.depth_traverse(cfg.entry) {
1421         let n = cfg.graph.node_data(index);
1422         match tcx.map.find(n.id()) {
1423             Some(hir_map::NodeExpr(ex)) => {
1424                 if let hir::ExprRet(Some(ref ret_expr)) = ex.node {
1425                     let mut visitor = FindNestedReturn::new();
1426                     intravisit::walk_expr(&mut visitor, &**ret_expr);
1427                     if visitor.found {
1428                         return true;
1429                     }
1430                 }
1431             }
1432             Some(hir_map::NodeBlock(blk)) if blk.id == blk_id => {
1433                 let mut visitor = FindNestedReturn::new();
1434                 walk_list!(&mut visitor, visit_expr, &blk.expr);
1435                 if visitor.found {
1436                     return true;
1437                 }
1438             }
1439             _ => {}
1440         }
1441     }
1442
1443     return false;
1444 }
1445
1446 // NB: must keep 4 fns in sync:
1447 //
1448 //  - type_of_fn
1449 //  - create_datums_for_fn_args.
1450 //  - new_fn_ctxt
1451 //  - trans_args
1452 //
1453 // Be warned! You must call `init_function` before doing anything with the
1454 // returned function context.
1455 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1456                              llfndecl: ValueRef,
1457                              id: ast::NodeId,
1458                              has_env: bool,
1459                              output_type: ty::FnOutput<'tcx>,
1460                              param_substs: &'tcx Substs<'tcx>,
1461                              sp: Option<Span>,
1462                              block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1463                              -> FunctionContext<'a, 'tcx> {
1464     common::validate_substs(param_substs);
1465
1466     debug!("new_fn_ctxt(path={}, id={}, param_substs={:?})",
1467            if id == !0 {
1468                "".to_string()
1469            } else {
1470                ccx.tcx().map.path_to_string(id).to_string()
1471            },
1472            id,
1473            param_substs);
1474
1475     let uses_outptr = match output_type {
1476         ty::FnConverging(output_type) => {
1477             let substd_output_type = monomorphize::apply_param_substs(ccx.tcx(),
1478                                                                       param_substs,
1479                                                                       &output_type);
1480             type_of::return_uses_outptr(ccx, substd_output_type)
1481         }
1482         ty::FnDiverging => false,
1483     };
1484     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1485     let (blk_id, cfg) = build_cfg(ccx.tcx(), id);
1486     let nested_returns = if let Some(ref cfg) = cfg {
1487         has_nested_returns(ccx.tcx(), cfg, blk_id)
1488     } else {
1489         false
1490     };
1491
1492     let mir = ccx.mir_map().get(&id);
1493
1494     let mut fcx = FunctionContext {
1495         mir: mir,
1496         llfn: llfndecl,
1497         llenv: None,
1498         llretslotptr: Cell::new(None),
1499         param_env: ccx.tcx().empty_parameter_environment(),
1500         alloca_insert_pt: Cell::new(None),
1501         llreturn: Cell::new(None),
1502         needs_ret_allocas: nested_returns,
1503         personality: Cell::new(None),
1504         caller_expects_out_pointer: uses_outptr,
1505         lllocals: RefCell::new(NodeMap()),
1506         llupvars: RefCell::new(NodeMap()),
1507         lldropflag_hints: RefCell::new(DropFlagHintsMap::new()),
1508         id: id,
1509         param_substs: param_substs,
1510         span: sp,
1511         block_arena: block_arena,
1512         ccx: ccx,
1513         debug_context: debug_context,
1514         scopes: RefCell::new(Vec::new()),
1515         cfg: cfg,
1516     };
1517
1518     if has_env {
1519         fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1520     }
1521
1522     fcx
1523 }
1524
1525 /// Performs setup on a newly created function, creating the entry scope block
1526 /// and allocating space for the return pointer.
1527 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1528                                skip_retptr: bool,
1529                                output: ty::FnOutput<'tcx>)
1530                                -> Block<'a, 'tcx> {
1531     let entry_bcx = fcx.new_temp_block("entry-block");
1532
1533     // Use a dummy instruction as the insertion point for all allocas.
1534     // This is later removed in FunctionContext::cleanup.
1535     fcx.alloca_insert_pt.set(Some(unsafe {
1536         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1537         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1538     }));
1539
1540     if let ty::FnConverging(output_type) = output {
1541         // This shouldn't need to recompute the return type,
1542         // as new_fn_ctxt did it already.
1543         let substd_output_type = fcx.monomorphize(&output_type);
1544         if !return_type_is_void(fcx.ccx, substd_output_type) {
1545             // If the function returns nil/bot, there is no real return
1546             // value, so do not set `llretslotptr`.
1547             if !skip_retptr || fcx.caller_expects_out_pointer {
1548                 // Otherwise, we normally allocate the llretslotptr, unless we
1549                 // have been instructed to skip it for immediate return
1550                 // values.
1551                 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1552             }
1553         }
1554     }
1555
1556     // Create the drop-flag hints for every unfragmented path in the function.
1557     let tcx = fcx.ccx.tcx();
1558     let fn_did = tcx.map.local_def_id(fcx.id);
1559     let mut hints = fcx.lldropflag_hints.borrow_mut();
1560     let fragment_infos = tcx.fragment_infos.borrow();
1561
1562     // Intern table for drop-flag hint datums.
1563     let mut seen = HashMap::new();
1564
1565     if let Some(fragment_infos) = fragment_infos.get(&fn_did) {
1566         for &info in fragment_infos {
1567
1568             let make_datum = |id| {
1569                 let init_val = C_u8(fcx.ccx, adt::DTOR_NEEDED_HINT);
1570                 let llname = &format!("dropflag_hint_{}", id);
1571                 debug!("adding hint {}", llname);
1572                 let ty = tcx.types.u8;
1573                 let ptr = alloc_ty(entry_bcx, ty, llname);
1574                 Store(entry_bcx, init_val, ptr);
1575                 let flag = datum::Lvalue::new_dropflag_hint("base::init_function");
1576                 datum::Datum::new(ptr, ty, flag)
1577             };
1578
1579             let (var, datum) = match info {
1580                 ty::FragmentInfo::Moved { var, .. } |
1581                 ty::FragmentInfo::Assigned { var, .. } => {
1582                     let datum = seen.get(&var).cloned().unwrap_or_else(|| {
1583                         let datum = make_datum(var);
1584                         seen.insert(var, datum.clone());
1585                         datum
1586                     });
1587                     (var, datum)
1588                 }
1589             };
1590             match info {
1591                 ty::FragmentInfo::Moved { move_expr: expr_id, .. } => {
1592                     debug!("FragmentInfo::Moved insert drop hint for {}", expr_id);
1593                     hints.insert(expr_id, DropHint::new(var, datum));
1594                 }
1595                 ty::FragmentInfo::Assigned { assignee_id: expr_id, .. } => {
1596                     debug!("FragmentInfo::Assigned insert drop hint for {}", expr_id);
1597                     hints.insert(expr_id, DropHint::new(var, datum));
1598                 }
1599             }
1600         }
1601     }
1602
1603     entry_bcx
1604 }
1605
1606 // NB: must keep 4 fns in sync:
1607 //
1608 //  - type_of_fn
1609 //  - create_datums_for_fn_args.
1610 //  - new_fn_ctxt
1611 //  - trans_args
1612
1613 pub fn arg_kind<'a, 'tcx>(cx: &FunctionContext<'a, 'tcx>, t: Ty<'tcx>) -> datum::Rvalue {
1614     use trans::datum::{ByRef, ByValue};
1615
1616     datum::Rvalue {
1617         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1618     }
1619 }
1620
1621 // create_datums_for_fn_args: creates lvalue datums for each of the
1622 // incoming function arguments.
1623 pub fn create_datums_for_fn_args<'a, 'tcx>(mut bcx: Block<'a, 'tcx>,
1624                                            args: &[hir::Arg],
1625                                            arg_tys: &[Ty<'tcx>],
1626                                            has_tupled_arg: bool,
1627                                            arg_scope: cleanup::CustomScopeIndex)
1628                                            -> Block<'a, 'tcx> {
1629     let _icx = push_ctxt("create_datums_for_fn_args");
1630     let fcx = bcx.fcx;
1631     let arg_scope_id = cleanup::CustomScope(arg_scope);
1632
1633     // Return an array wrapping the ValueRefs that we get from `get_param` for
1634     // each argument into datums.
1635     //
1636     // For certain mode/type combinations, the raw llarg values are passed
1637     // by value.  However, within the fn body itself, we want to always
1638     // have all locals and arguments be by-ref so that we can cancel the
1639     // cleanup and for better interaction with LLVM's debug info.  So, if
1640     // the argument would be passed by value, we store it into an alloca.
1641     // This alloca should be optimized away by LLVM's mem-to-reg pass in
1642     // the event it's not truly needed.
1643     let mut idx = fcx.arg_offset() as c_uint;
1644     for (i, &arg_ty) in arg_tys.iter().enumerate() {
1645         let arg_datum = if !has_tupled_arg || i < arg_tys.len() - 1 {
1646             if type_of::arg_is_indirect(bcx.ccx(), arg_ty) &&
1647                bcx.sess().opts.debuginfo != FullDebugInfo {
1648                 // Don't copy an indirect argument to an alloca, the caller
1649                 // already put it in a temporary alloca and gave it up, unless
1650                 // we emit extra-debug-info, which requires local allocas :(.
1651                 let llarg = get_param(fcx.llfn, idx);
1652                 idx += 1;
1653                 bcx.fcx.schedule_lifetime_end(arg_scope_id, llarg);
1654                 bcx.fcx.schedule_drop_mem(arg_scope_id, llarg, arg_ty, None);
1655
1656                 datum::Datum::new(llarg,
1657                                   arg_ty,
1658                                   datum::Lvalue::new("create_datum_for_fn_args"))
1659             } else if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
1660                 let data = get_param(fcx.llfn, idx);
1661                 let extra = get_param(fcx.llfn, idx + 1);
1662                 idx += 2;
1663                 unpack_datum!(bcx, datum::lvalue_scratch_datum(bcx, arg_ty, "",
1664                                                         arg_scope_id, (data, extra),
1665                                                         |(data, extra), bcx, dst| {
1666                     Store(bcx, data, expr::get_dataptr(bcx, dst));
1667                     Store(bcx, extra, expr::get_meta(bcx, dst));
1668                     bcx
1669                 }))
1670             } else {
1671                 let llarg = get_param(fcx.llfn, idx);
1672                 idx += 1;
1673                 let tmp = datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty));
1674                 unpack_datum!(bcx,
1675                               datum::lvalue_scratch_datum(bcx,
1676                                                           arg_ty,
1677                                                           "",
1678                                                           arg_scope_id,
1679                                                           tmp,
1680                                                           |tmp, bcx, dst| tmp.store_to(bcx, dst)))
1681             }
1682         } else {
1683             // FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1684             match arg_ty.sty {
1685                 ty::TyTuple(ref tupled_arg_tys) => {
1686                     unpack_datum!(bcx,
1687                                   datum::lvalue_scratch_datum(bcx,
1688                                                               arg_ty,
1689                                                               "tupled_args",
1690                                                               arg_scope_id,
1691                                                               (),
1692                                                               |(),
1693                                                                mut bcx,
1694                                                                llval| {
1695                         for (j, &tupled_arg_ty) in
1696                                     tupled_arg_tys.iter().enumerate() {
1697                             let lldest = StructGEP(bcx, llval, j);
1698                             if common::type_is_fat_ptr(bcx.tcx(), tupled_arg_ty) {
1699                                 let data = get_param(bcx.fcx.llfn, idx);
1700                                 let extra = get_param(bcx.fcx.llfn, idx + 1);
1701                                 Store(bcx, data, expr::get_dataptr(bcx, lldest));
1702                                 Store(bcx, extra, expr::get_meta(bcx, lldest));
1703                                 idx += 2;
1704                             } else {
1705                                 let datum = datum::Datum::new(
1706                                     get_param(bcx.fcx.llfn, idx),
1707                                     tupled_arg_ty,
1708                                     arg_kind(bcx.fcx, tupled_arg_ty));
1709                                 idx += 1;
1710                                 bcx = datum.store_to(bcx, lldest);
1711                             };
1712                         }
1713                         bcx
1714                     }))
1715                 }
1716                 _ => {
1717                     bcx.tcx()
1718                        .sess
1719                        .bug("last argument of a function with `rust-call` ABI isn't a tuple?!")
1720                 }
1721             }
1722         };
1723
1724         let pat = &*args[i].pat;
1725         bcx = if let Some(name) = simple_name(pat) {
1726             // Generate nicer LLVM for the common case of fn a pattern
1727             // like `x: T`
1728             set_value_name(arg_datum.val, &bcx.name(name));
1729             bcx.fcx.lllocals.borrow_mut().insert(pat.id, arg_datum);
1730             bcx
1731         } else {
1732             // General path. Copy out the values that are used in the
1733             // pattern.
1734             _match::bind_irrefutable_pat(bcx, pat, arg_datum.match_input(), arg_scope_id)
1735         };
1736         debuginfo::create_argument_metadata(bcx, &args[i]);
1737     }
1738
1739     bcx
1740 }
1741
1742 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1743 // and builds the return block.
1744 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1745                              last_bcx: Block<'blk, 'tcx>,
1746                              retty: ty::FnOutput<'tcx>,
1747                              ret_debug_loc: DebugLoc) {
1748     let _icx = push_ctxt("finish_fn");
1749
1750     let ret_cx = match fcx.llreturn.get() {
1751         Some(llreturn) => {
1752             if !last_bcx.terminated.get() {
1753                 Br(last_bcx, llreturn, DebugLoc::None);
1754             }
1755             raw_block(fcx, false, llreturn)
1756         }
1757         None => last_bcx,
1758     };
1759
1760     // This shouldn't need to recompute the return type,
1761     // as new_fn_ctxt did it already.
1762     let substd_retty = fcx.monomorphize(&retty);
1763     build_return_block(fcx, ret_cx, substd_retty, ret_debug_loc);
1764
1765     debuginfo::clear_source_location(fcx);
1766     fcx.cleanup();
1767 }
1768
1769 // Builds the return block for a function.
1770 pub fn build_return_block<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1771                                       ret_cx: Block<'blk, 'tcx>,
1772                                       retty: ty::FnOutput<'tcx>,
1773                                       ret_debug_location: DebugLoc) {
1774     if fcx.llretslotptr.get().is_none() ||
1775        (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1776         return RetVoid(ret_cx, ret_debug_location);
1777     }
1778
1779     let retslot = if fcx.needs_ret_allocas {
1780         Load(ret_cx, fcx.llretslotptr.get().unwrap())
1781     } else {
1782         fcx.llretslotptr.get().unwrap()
1783     };
1784     let retptr = Value(retslot);
1785     match retptr.get_dominating_store(ret_cx) {
1786         // If there's only a single store to the ret slot, we can directly return
1787         // the value that was stored and omit the store and the alloca
1788         Some(s) => {
1789             let retval = s.get_operand(0).unwrap().get();
1790             s.erase_from_parent();
1791
1792             if retptr.has_no_uses() {
1793                 retptr.erase_from_parent();
1794             }
1795
1796             let retval = if retty == ty::FnConverging(fcx.ccx.tcx().types.bool) {
1797                 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1798             } else {
1799                 retval
1800             };
1801
1802             if fcx.caller_expects_out_pointer {
1803                 if let ty::FnConverging(retty) = retty {
1804                     store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1805                 }
1806                 RetVoid(ret_cx, ret_debug_location)
1807             } else {
1808                 Ret(ret_cx, retval, ret_debug_location)
1809             }
1810         }
1811         // Otherwise, copy the return value to the ret slot
1812         None => match retty {
1813             ty::FnConverging(retty) => {
1814                 if fcx.caller_expects_out_pointer {
1815                     memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1816                     RetVoid(ret_cx, ret_debug_location)
1817                 } else {
1818                     Ret(ret_cx, load_ty(ret_cx, retslot, retty), ret_debug_location)
1819                 }
1820             }
1821             ty::FnDiverging => {
1822                 if fcx.caller_expects_out_pointer {
1823                     RetVoid(ret_cx, ret_debug_location)
1824                 } else {
1825                     Ret(ret_cx, C_undef(Type::nil(fcx.ccx)), ret_debug_location)
1826                 }
1827             }
1828         },
1829     }
1830 }
1831
1832 /// Builds an LLVM function out of a source function.
1833 ///
1834 /// If the function closes over its environment a closure will be returned.
1835 pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1836                                    decl: &hir::FnDecl,
1837                                    body: &hir::Block,
1838                                    llfndecl: ValueRef,
1839                                    param_substs: &'tcx Substs<'tcx>,
1840                                    fn_ast_id: ast::NodeId,
1841                                    attributes: &[ast::Attribute],
1842                                    output_type: ty::FnOutput<'tcx>,
1843                                    abi: Abi,
1844                                    closure_env: closure::ClosureEnv<'b>) {
1845     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1846
1847     let _icx = push_ctxt("trans_closure");
1848     attributes::emit_uwtable(llfndecl, true);
1849
1850     debug!("trans_closure(..., param_substs={:?})", param_substs);
1851
1852     let has_env = match closure_env {
1853         closure::ClosureEnv::Closure(..) => true,
1854         closure::ClosureEnv::NotClosure => false,
1855     };
1856
1857     let (arena, fcx): (TypedArena<_>, FunctionContext);
1858     arena = TypedArena::new();
1859     fcx = new_fn_ctxt(ccx,
1860                       llfndecl,
1861                       fn_ast_id,
1862                       has_env,
1863                       output_type,
1864                       param_substs,
1865                       Some(body.span),
1866                       &arena);
1867     let mut bcx = init_function(&fcx, false, output_type);
1868
1869     if attributes.iter().any(|item| item.check_name("rustc_mir")) {
1870         mir::trans_mir(bcx);
1871         fcx.cleanup();
1872         return;
1873     }
1874
1875     // cleanup scope for the incoming arguments
1876     let fn_cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(ccx,
1877                                                                              fn_ast_id,
1878                                                                              body.span,
1879                                                                              true);
1880     let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1881
1882     let block_ty = node_id_type(bcx, body.id);
1883
1884     // Set up arguments to the function.
1885     let monomorphized_arg_types = decl.inputs
1886                                       .iter()
1887                                       .map(|arg| node_id_type(bcx, arg.id))
1888                                       .collect::<Vec<_>>();
1889     for monomorphized_arg_type in &monomorphized_arg_types {
1890         debug!("trans_closure: monomorphized_arg_type: {:?}",
1891                monomorphized_arg_type);
1892     }
1893     debug!("trans_closure: function lltype: {}",
1894            bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1895
1896     let has_tupled_arg = match closure_env {
1897         closure::ClosureEnv::NotClosure => abi == RustCall,
1898         _ => false,
1899     };
1900
1901     bcx = create_datums_for_fn_args(bcx,
1902                                     &decl.inputs,
1903                                     &monomorphized_arg_types,
1904                                     has_tupled_arg,
1905                                     arg_scope);
1906
1907     bcx = closure_env.load(bcx, cleanup::CustomScope(arg_scope));
1908
1909     // Up until here, IR instructions for this function have explicitly not been annotated with
1910     // source code location, so we don't step into call setup code. From here on, source location
1911     // emitting should be enabled.
1912     debuginfo::start_emitting_source_locations(&fcx);
1913
1914     let dest = match fcx.llretslotptr.get() {
1915         Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, ty::FnConverging(block_ty), "iret_slot")),
1916         None => {
1917             assert!(type_is_zero_size(bcx.ccx(), block_ty));
1918             expr::Ignore
1919         }
1920     };
1921
1922     // This call to trans_block is the place where we bridge between
1923     // translation calls that don't have a return value (trans_crate,
1924     // trans_mod, trans_item, et cetera) and those that do
1925     // (trans_block, trans_expr, et cetera).
1926     bcx = controlflow::trans_block(bcx, body, dest);
1927
1928     match dest {
1929         expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1930             Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1931         }
1932         _ => {}
1933     }
1934
1935     match fcx.llreturn.get() {
1936         Some(_) => {
1937             Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1938             fcx.pop_custom_cleanup_scope(arg_scope);
1939         }
1940         None => {
1941             // Microoptimization writ large: avoid creating a separate
1942             // llreturn basic block
1943             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1944         }
1945     };
1946
1947     // Put return block after all other blocks.
1948     // This somewhat improves single-stepping experience in debugger.
1949     unsafe {
1950         let llreturn = fcx.llreturn.get();
1951         if let Some(llreturn) = llreturn {
1952             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1953         }
1954     }
1955
1956     let ret_debug_loc = DebugLoc::At(fn_cleanup_debug_loc.id, fn_cleanup_debug_loc.span);
1957
1958     // Insert the mandatory first few basic blocks before lltop.
1959     finish_fn(&fcx, bcx, output_type, ret_debug_loc);
1960 }
1961
1962 /// Creates an LLVM function corresponding to a source language function.
1963 pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1964                           decl: &hir::FnDecl,
1965                           body: &hir::Block,
1966                           llfndecl: ValueRef,
1967                           param_substs: &'tcx Substs<'tcx>,
1968                           id: ast::NodeId,
1969                           attrs: &[ast::Attribute]) {
1970     let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1971     debug!("trans_fn(param_substs={:?})", param_substs);
1972     let _icx = push_ctxt("trans_fn");
1973     let fn_ty = ccx.tcx().node_id_to_type(id);
1974     let fn_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &fn_ty);
1975     let sig = fn_ty.fn_sig();
1976     let sig = ccx.tcx().erase_late_bound_regions(&sig);
1977     let sig = infer::normalize_associated_type(ccx.tcx(), &sig);
1978     let output_type = sig.output;
1979     let abi = fn_ty.fn_abi();
1980     trans_closure(ccx,
1981                   decl,
1982                   body,
1983                   llfndecl,
1984                   param_substs,
1985                   id,
1986                   attrs,
1987                   output_type,
1988                   abi,
1989                   closure::ClosureEnv::NotClosure);
1990 }
1991
1992 pub fn trans_enum_variant<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1993                                     ctor_id: ast::NodeId,
1994                                     disr: ty::Disr,
1995                                     param_substs: &'tcx Substs<'tcx>,
1996                                     llfndecl: ValueRef) {
1997     let _icx = push_ctxt("trans_enum_variant");
1998
1999     trans_enum_variant_or_tuple_like_struct(ccx, ctor_id, disr, param_substs, llfndecl);
2000 }
2001
2002 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
2003                                                  ctor_ty: Ty<'tcx>,
2004                                                  disr: ty::Disr,
2005                                                  args: callee::CallArgs,
2006                                                  dest: expr::Dest,
2007                                                  debug_loc: DebugLoc)
2008                                                  -> Result<'blk, 'tcx> {
2009
2010     let ccx = bcx.fcx.ccx;
2011
2012     let sig = ccx.tcx().erase_late_bound_regions(&ctor_ty.fn_sig());
2013     let sig = infer::normalize_associated_type(ccx.tcx(), &sig);
2014     let result_ty = sig.output.unwrap();
2015
2016     // Get location to store the result. If the user does not care about
2017     // the result, just make a stack slot
2018     let llresult = match dest {
2019         expr::SaveIn(d) => d,
2020         expr::Ignore => {
2021             if !type_is_zero_size(ccx, result_ty) {
2022                 let llresult = alloc_ty(bcx, result_ty, "constructor_result");
2023                 call_lifetime_start(bcx, llresult);
2024                 llresult
2025             } else {
2026                 C_undef(type_of::type_of(ccx, result_ty).ptr_to())
2027             }
2028         }
2029     };
2030
2031     if !type_is_zero_size(ccx, result_ty) {
2032         match args {
2033             callee::ArgExprs(exprs) => {
2034                 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
2035                 bcx = expr::trans_adt(bcx,
2036                                       result_ty,
2037                                       disr,
2038                                       &fields[..],
2039                                       None,
2040                                       expr::SaveIn(llresult),
2041                                       debug_loc);
2042             }
2043             _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor"),
2044         }
2045     } else {
2046         // Just eval all the expressions (if any). Since expressions in Rust can have arbitrary
2047         // contents, there could be side-effects we need from them.
2048         match args {
2049             callee::ArgExprs(exprs) => {
2050                 for expr in exprs {
2051                     bcx = expr::trans_into(bcx, expr, expr::Ignore);
2052                 }
2053             }
2054             _ => (),
2055         }
2056     }
2057
2058     // If the caller doesn't care about the result
2059     // drop the temporary we made
2060     let bcx = match dest {
2061         expr::SaveIn(_) => bcx,
2062         expr::Ignore => {
2063             let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
2064             if !type_is_zero_size(ccx, result_ty) {
2065                 call_lifetime_end(bcx, llresult);
2066             }
2067             bcx
2068         }
2069     };
2070
2071     Result::new(bcx, llresult)
2072 }
2073
2074 pub fn trans_tuple_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2075                                     ctor_id: ast::NodeId,
2076                                     param_substs: &'tcx Substs<'tcx>,
2077                                     llfndecl: ValueRef) {
2078     let _icx = push_ctxt("trans_tuple_struct");
2079
2080     trans_enum_variant_or_tuple_like_struct(ccx, ctor_id, 0, param_substs, llfndecl);
2081 }
2082
2083 fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2084                                                      ctor_id: ast::NodeId,
2085                                                      disr: ty::Disr,
2086                                                      param_substs: &'tcx Substs<'tcx>,
2087                                                      llfndecl: ValueRef) {
2088     let ctor_ty = ccx.tcx().node_id_to_type(ctor_id);
2089     let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
2090
2091     let sig = ccx.tcx().erase_late_bound_regions(&ctor_ty.fn_sig());
2092     let sig = infer::normalize_associated_type(ccx.tcx(), &sig);
2093     let arg_tys = sig.inputs;
2094     let result_ty = sig.output;
2095
2096     let (arena, fcx): (TypedArena<_>, FunctionContext);
2097     arena = TypedArena::new();
2098     fcx = new_fn_ctxt(ccx,
2099                       llfndecl,
2100                       ctor_id,
2101                       false,
2102                       result_ty,
2103                       param_substs,
2104                       None,
2105                       &arena);
2106     let bcx = init_function(&fcx, false, result_ty);
2107
2108     assert!(!fcx.needs_ret_allocas);
2109
2110     if !type_is_zero_size(fcx.ccx, result_ty.unwrap()) {
2111         let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
2112         let dest_val = adt::MaybeSizedValue::sized(dest); // Can return unsized value
2113         let repr = adt::represent_type(ccx, result_ty.unwrap());
2114         let mut llarg_idx = fcx.arg_offset() as c_uint;
2115         for (i, arg_ty) in arg_tys.into_iter().enumerate() {
2116             let lldestptr = adt::trans_field_ptr(bcx, &*repr, dest_val, disr, i);
2117             if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
2118                 Store(bcx,
2119                       get_param(fcx.llfn, llarg_idx),
2120                       expr::get_dataptr(bcx, lldestptr));
2121                 Store(bcx,
2122                       get_param(fcx.llfn, llarg_idx + 1),
2123                       expr::get_meta(bcx, lldestptr));
2124                 llarg_idx += 2;
2125             } else {
2126                 let arg = get_param(fcx.llfn, llarg_idx);
2127                 llarg_idx += 1;
2128
2129                 if arg_is_indirect(ccx, arg_ty) {
2130                     memcpy_ty(bcx, lldestptr, arg, arg_ty);
2131                 } else {
2132                     store_ty(bcx, arg, lldestptr, arg_ty);
2133                 }
2134             }
2135         }
2136         adt::trans_set_discr(bcx, &*repr, dest, disr);
2137     }
2138
2139     finish_fn(&fcx, bcx, result_ty, DebugLoc::None);
2140 }
2141
2142 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &hir::EnumDef, sp: Span, id: ast::NodeId) {
2143     let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
2144
2145     let print_info = ccx.sess().print_enum_sizes();
2146
2147     let levels = ccx.tcx().node_lint_levels.borrow();
2148     let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCES);
2149     let lvlsrc = levels.get(&(id, lint_id));
2150     let is_allow = lvlsrc.map_or(true, |&(lvl, _)| lvl == lint::Allow);
2151
2152     if is_allow && !print_info {
2153         // we're not interested in anything here
2154         return;
2155     }
2156
2157     let ty = ccx.tcx().node_id_to_type(id);
2158     let avar = adt::represent_type(ccx, ty);
2159     match *avar {
2160         adt::General(_, ref variants, _) => {
2161             for var in variants {
2162                 let mut size = 0;
2163                 for field in var.fields.iter().skip(1) {
2164                     // skip the discriminant
2165                     size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
2166                 }
2167                 sizes.push(size);
2168             }
2169         },
2170         _ => { /* its size is either constant or unimportant */ }
2171     }
2172
2173     let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
2174         |(l, s, li), (idx, &size)|
2175             if size > l {
2176                 (size, l, idx)
2177             } else if size > s {
2178                 (l, size, li)
2179             } else {
2180                 (l, s, li)
2181             }
2182     );
2183
2184     // FIXME(#30505) Should use logging for this.
2185     if print_info {
2186         let llty = type_of::sizing_type_of(ccx, ty);
2187
2188         let sess = &ccx.tcx().sess;
2189         sess.span_note_without_error(sp,
2190                                      &*format!("total size: {} bytes", llsize_of_real(ccx, llty)));
2191         match *avar {
2192             adt::General(..) => {
2193                 for (i, var) in enum_def.variants.iter().enumerate() {
2194                     ccx.tcx()
2195                        .sess
2196                        .span_note_without_error(var.span,
2197                                                 &*format!("variant data: {} bytes", sizes[i]));
2198                 }
2199             }
2200             _ => {}
2201         }
2202     }
2203
2204     // we only warn if the largest variant is at least thrice as large as
2205     // the second-largest.
2206     if !is_allow && largest > slargest * 3 && slargest > 0 {
2207         // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
2208         // pass for the latter already ran.
2209         lint::raw_struct_lint(&ccx.tcx().sess,
2210                               lint::builtin::VARIANT_SIZE_DIFFERENCES,
2211                               *lvlsrc.unwrap(),
2212                               Some(sp),
2213                               &format!("enum variant is more than three times larger ({} bytes) \
2214                                         than the next largest (ignoring padding)",
2215                                        largest))
2216             .span_note(enum_def.variants[largest_index].span,
2217                        "this variant is the largest")
2218             .emit();
2219     }
2220 }
2221
2222 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
2223     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2224     // applicable to variable declarations and may not really make sense for
2225     // Rust code in the first place but whitelist them anyway and trust that
2226     // the user knows what s/he's doing. Who knows, unanticipated use cases
2227     // may pop up in the future.
2228     //
2229     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2230     // and don't have to be, LLVM treats them as no-ops.
2231     match name {
2232         "appending" => Some(llvm::AppendingLinkage),
2233         "available_externally" => Some(llvm::AvailableExternallyLinkage),
2234         "common" => Some(llvm::CommonLinkage),
2235         "extern_weak" => Some(llvm::ExternalWeakLinkage),
2236         "external" => Some(llvm::ExternalLinkage),
2237         "internal" => Some(llvm::InternalLinkage),
2238         "linkonce" => Some(llvm::LinkOnceAnyLinkage),
2239         "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
2240         "private" => Some(llvm::PrivateLinkage),
2241         "weak" => Some(llvm::WeakAnyLinkage),
2242         "weak_odr" => Some(llvm::WeakODRLinkage),
2243         _ => None,
2244     }
2245 }
2246
2247
2248 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
2249 #[derive(Copy, Clone)]
2250 pub enum ValueOrigin {
2251     /// The LLVM `Value` is in this context because the corresponding item was
2252     /// assigned to the current compilation unit.
2253     OriginalTranslation,
2254     /// The `Value`'s corresponding item was assigned to some other compilation
2255     /// unit, but the `Value` was translated in this context anyway because the
2256     /// item is marked `#[inline]`.
2257     InlinedCopy,
2258 }
2259
2260 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
2261 /// If the `llval` is the direct translation of a specific Rust item, `id`
2262 /// should be set to the `NodeId` of that item.  (This mapping should be
2263 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
2264 /// `None`.)  `llval_origin` indicates whether `llval` is the translation of an
2265 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
2266 /// assigned to a different compilation unit.
2267 pub fn update_linkage(ccx: &CrateContext,
2268                       llval: ValueRef,
2269                       id: Option<ast::NodeId>,
2270                       llval_origin: ValueOrigin) {
2271     match llval_origin {
2272         InlinedCopy => {
2273             // `llval` is a translation of an item defined in a separate
2274             // compilation unit.  This only makes sense if there are at least
2275             // two compilation units.
2276             assert!(ccx.sess().opts.cg.codegen_units > 1);
2277             // `llval` is a copy of something defined elsewhere, so use
2278             // `AvailableExternallyLinkage` to avoid duplicating code in the
2279             // output.
2280             llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
2281             return;
2282         },
2283         OriginalTranslation => {},
2284     }
2285
2286     if let Some(id) = id {
2287         let item = ccx.tcx().map.get(id);
2288         if let hir_map::NodeItem(i) = item {
2289             if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
2290                 if let Some(linkage) = llvm_linkage_by_name(&name) {
2291                     llvm::SetLinkage(llval, linkage);
2292                 } else {
2293                     ccx.sess().span_fatal(i.span, "invalid linkage specified");
2294                 }
2295                 return;
2296             }
2297         }
2298     }
2299
2300     match id {
2301         Some(id) if ccx.reachable().contains(&id) => {
2302             llvm::SetLinkage(llval, llvm::ExternalLinkage);
2303         },
2304         _ => {
2305             // `id` does not refer to an item in `ccx.reachable`.
2306             if ccx.sess().opts.cg.codegen_units > 1 {
2307                 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2308             } else {
2309                 llvm::SetLinkage(llval, llvm::InternalLinkage);
2310             }
2311         },
2312     }
2313 }
2314
2315 fn set_global_section(ccx: &CrateContext, llval: ValueRef, i: &hir::Item) {
2316     match attr::first_attr_value_str_by_name(&i.attrs, "link_section") {
2317         Some(sect) => {
2318             if contains_null(&sect) {
2319                 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
2320             }
2321             unsafe {
2322                 let buf = CString::new(sect.as_bytes()).unwrap();
2323                 llvm::LLVMSetSection(llval, buf.as_ptr());
2324             }
2325         },
2326         None => ()
2327     }
2328 }
2329
2330 pub fn trans_item(ccx: &CrateContext, item: &hir::Item) {
2331     let _icx = push_ctxt("trans_item");
2332
2333     let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
2334
2335     match item.node {
2336         hir::ItemFn(ref decl, _, _, abi, ref generics, ref body) => {
2337             if !generics.is_type_parameterized() {
2338                 let trans_everywhere = attr::requests_inline(&item.attrs);
2339                 // Ignore `trans_everywhere` for cross-crate inlined items
2340                 // (`from_external`).  `trans_item` will be called once for each
2341                 // compilation unit that references the item, so it will still get
2342                 // translated everywhere it's needed.
2343                 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2344                     let llfn = get_item_val(ccx, item.id);
2345                     let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2346                     if abi != Rust {
2347                         foreign::trans_rust_fn_with_foreign_abi(ccx,
2348                                                                 &**decl,
2349                                                                 &**body,
2350                                                                 &item.attrs,
2351                                                                 llfn,
2352                                                                 empty_substs,
2353                                                                 item.id,
2354                                                                 None);
2355                     } else {
2356                         trans_fn(ccx,
2357                                  &**decl,
2358                                  &**body,
2359                                  llfn,
2360                                  empty_substs,
2361                                  item.id,
2362                                  &item.attrs);
2363                     }
2364                     set_global_section(ccx, llfn, item);
2365                     update_linkage(ccx,
2366                                    llfn,
2367                                    Some(item.id),
2368                                    if is_origin {
2369                                        OriginalTranslation
2370                                    } else {
2371                                        InlinedCopy
2372                                    });
2373
2374                     if is_entry_fn(ccx.sess(), item.id) {
2375                         create_entry_wrapper(ccx, item.span, llfn);
2376                         // check for the #[rustc_error] annotation, which forces an
2377                         // error in trans. This is used to write compile-fail tests
2378                         // that actually test that compilation succeeds without
2379                         // reporting an error.
2380                         let item_def_id = ccx.tcx().map.local_def_id(item.id);
2381                         if ccx.tcx().has_attr(item_def_id, "rustc_error") {
2382                             ccx.tcx().sess.span_fatal(item.span, "compilation successful");
2383                         }
2384                     }
2385                 }
2386             }
2387         }
2388         hir::ItemImpl(_, _, ref generics, _, _, ref impl_items) => {
2389             meth::trans_impl(ccx, item.name, impl_items, generics, item.id);
2390         }
2391         hir::ItemMod(_) => {
2392             // modules have no equivalent at runtime, they just affect
2393             // the mangled names of things contained within
2394         }
2395         hir::ItemEnum(ref enum_definition, ref gens) => {
2396             if gens.ty_params.is_empty() {
2397                 // sizes only make sense for non-generic types
2398
2399                 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2400             }
2401         }
2402         hir::ItemConst(..) => {}
2403         hir::ItemStatic(_, m, ref expr) => {
2404             let g = match consts::trans_static(ccx, m, expr, item.id, &item.attrs) {
2405                 Ok(g) => g,
2406                 Err(err) => ccx.tcx().sess.span_fatal(expr.span, &err.description()),
2407             };
2408             set_global_section(ccx, g, item);
2409             update_linkage(ccx, g, Some(item.id), OriginalTranslation);
2410         }
2411         hir::ItemForeignMod(ref foreign_mod) => {
2412             foreign::trans_foreign_mod(ccx, foreign_mod);
2413         }
2414         hir::ItemTrait(..) => {}
2415         _ => {
2416             // fall through
2417         }
2418     }
2419 }
2420
2421 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2422 pub fn register_fn_llvmty(ccx: &CrateContext,
2423                           sp: Span,
2424                           sym: String,
2425                           node_id: ast::NodeId,
2426                           cc: llvm::CallConv,
2427                           llfty: Type)
2428                           -> ValueRef {
2429     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2430
2431     let llfn = declare::define_fn(ccx, &sym[..], cc, llfty,
2432                                    ty::FnConverging(ccx.tcx().mk_nil())).unwrap_or_else(||{
2433         ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2434     });
2435     finish_register_fn(ccx, sym, node_id);
2436     llfn
2437 }
2438
2439 fn finish_register_fn(ccx: &CrateContext, sym: String, node_id: ast::NodeId) {
2440     ccx.item_symbols().borrow_mut().insert(node_id, sym);
2441 }
2442
2443 fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2444                          sp: Span,
2445                          sym: String,
2446                          node_id: ast::NodeId,
2447                          node_type: Ty<'tcx>)
2448                          -> ValueRef {
2449     if let ty::TyBareFn(_, ref f) = node_type.sty {
2450         if f.abi != Rust && f.abi != RustCall {
2451             ccx.sess().span_bug(sp,
2452                                 &format!("only the `{}` or `{}` calling conventions are valid \
2453                                           for this function; `{}` was specified",
2454                                          Rust.name(),
2455                                          RustCall.name(),
2456                                          f.abi.name()));
2457         }
2458     } else {
2459         ccx.sess().span_bug(sp, "expected bare rust function")
2460     }
2461
2462     let llfn = declare::define_rust_fn(ccx, &sym[..], node_type).unwrap_or_else(|| {
2463         ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2464     });
2465     finish_register_fn(ccx, sym, node_id);
2466     llfn
2467 }
2468
2469 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2470     match *sess.entry_fn.borrow() {
2471         Some((entry_id, _)) => node_id == entry_id,
2472         None => false,
2473     }
2474 }
2475
2476 /// Create the `main` function which will initialise the rust runtime and call users’ main
2477 /// function.
2478 pub fn create_entry_wrapper(ccx: &CrateContext, sp: Span, main_llfn: ValueRef) {
2479     let et = ccx.sess().entry_type.get().unwrap();
2480     match et {
2481         config::EntryMain => {
2482             create_entry_fn(ccx, sp, main_llfn, true);
2483         }
2484         config::EntryStart => create_entry_fn(ccx, sp, main_llfn, false),
2485         config::EntryNone => {}    // Do nothing.
2486     }
2487
2488     fn create_entry_fn(ccx: &CrateContext,
2489                        sp: Span,
2490                        rust_main: ValueRef,
2491                        use_start_lang_item: bool) {
2492         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
2493
2494         let llfn = declare::define_cfn(ccx, "main", llfty, ccx.tcx().mk_nil()).unwrap_or_else(|| {
2495             // FIXME: We should be smart and show a better diagnostic here.
2496             ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
2497                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
2498                       .emit();
2499             ccx.sess().abort_if_errors();
2500             panic!();
2501         });
2502
2503         let llbb = unsafe {
2504             llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, "top\0".as_ptr() as *const _)
2505         };
2506         let bld = ccx.raw_builder();
2507         unsafe {
2508             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2509
2510             debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2511
2512             let (start_fn, args) = if use_start_lang_item {
2513                 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2514                     Ok(id) => id,
2515                     Err(s) => {
2516                         ccx.sess().fatal(&s[..]);
2517                     }
2518                 };
2519                 let start_fn = if let Some(start_node_id) = ccx.tcx()
2520                                                                .map
2521                                                                .as_local_node_id(start_def_id) {
2522                     get_item_val(ccx, start_node_id)
2523                 } else {
2524                     let start_fn_type = ccx.tcx().lookup_item_type(start_def_id).ty;
2525                     trans_external_path(ccx, start_def_id, start_fn_type)
2526                 };
2527                 let args = {
2528                     let opaque_rust_main =
2529                         llvm::LLVMBuildPointerCast(bld,
2530                                                    rust_main,
2531                                                    Type::i8p(ccx).to_ref(),
2532                                                    "rust_main\0".as_ptr() as *const _);
2533
2534                     vec![opaque_rust_main, get_param(llfn, 0), get_param(llfn, 1)]
2535                 };
2536                 (start_fn, args)
2537             } else {
2538                 debug!("using user-defined start fn");
2539                 let args = vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)];
2540
2541                 (rust_main, args)
2542             };
2543
2544             let result = llvm::LLVMBuildCall(bld,
2545                                              start_fn,
2546                                              args.as_ptr(),
2547                                              args.len() as c_uint,
2548                                              noname());
2549
2550             llvm::LLVMBuildRet(bld, result);
2551         }
2552     }
2553 }
2554
2555 fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2556                            id: ast::NodeId,
2557                            ty: Ty<'tcx>,
2558                            attrs: &[ast::Attribute])
2559                            -> String {
2560     match ccx.external_srcs().borrow().get(&id) {
2561         Some(&did) => {
2562             let sym = ccx.sess().cstore.item_symbol(did);
2563             debug!("found item {} in other crate...", sym);
2564             return sym;
2565         }
2566         None => {}
2567     }
2568
2569     match attr::find_export_name_attr(ccx.sess().diagnostic(), attrs) {
2570         // Use provided name
2571         Some(name) => name.to_string(),
2572         _ => {
2573             let path = ccx.tcx().map.def_path_from_id(id);
2574             if attr::contains_name(attrs, "no_mangle") {
2575                 // Don't mangle
2576                 path.last().unwrap().data.to_string()
2577             } else {
2578                 match weak_lang_items::link_name(attrs) {
2579                     Some(name) => name.to_string(),
2580                     None => {
2581                         // Usual name mangling
2582                         mangle_exported_name(ccx, path, ty, id)
2583                     }
2584                 }
2585             }
2586         }
2587     }
2588 }
2589
2590 fn contains_null(s: &str) -> bool {
2591     s.bytes().any(|b| b == 0)
2592 }
2593
2594 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2595     debug!("get_item_val(id=`{}`)", id);
2596
2597     match ccx.item_vals().borrow().get(&id).cloned() {
2598         Some(v) => return v,
2599         None => {}
2600     }
2601
2602     let item = ccx.tcx().map.get(id);
2603     debug!("get_item_val: id={} item={:?}", id, item);
2604     let val = match item {
2605         hir_map::NodeItem(i) => {
2606             let ty = ccx.tcx().node_id_to_type(i.id);
2607             let sym = || exported_name(ccx, id, ty, &i.attrs);
2608
2609             let v = match i.node {
2610                 hir::ItemStatic(..) => {
2611                     // If this static came from an external crate, then
2612                     // we need to get the symbol from metadata instead of
2613                     // using the current crate's name/version
2614                     // information in the hash of the symbol
2615                     let sym = sym();
2616                     debug!("making {}", sym);
2617
2618                     // Create the global before evaluating the initializer;
2619                     // this is necessary to allow recursive statics.
2620                     let llty = type_of(ccx, ty);
2621                     let g = declare::define_global(ccx, &sym[..], llty).unwrap_or_else(|| {
2622                         ccx.sess()
2623                            .span_fatal(i.span, &format!("symbol `{}` is already defined", sym))
2624                     });
2625
2626                     ccx.item_symbols().borrow_mut().insert(i.id, sym);
2627                     g
2628                 }
2629
2630                 hir::ItemFn(_, _, _, abi, _, _) => {
2631                     let sym = sym();
2632                     let llfn = if abi == Rust {
2633                         register_fn(ccx, i.span, sym, i.id, ty)
2634                     } else {
2635                         foreign::register_rust_fn_with_foreign_abi(ccx, i.span, sym, i.id)
2636                     };
2637                     attributes::from_fn_attrs(ccx, &i.attrs, llfn);
2638                     llfn
2639                 }
2640
2641                 _ => ccx.sess().bug("get_item_val: weird result in table"),
2642             };
2643
2644             v
2645         }
2646
2647         hir_map::NodeTraitItem(trait_item) => {
2648             debug!("get_item_val(): processing a NodeTraitItem");
2649             match trait_item.node {
2650                 hir::MethodTraitItem(_, Some(_)) => {
2651                     register_method(ccx, id, &trait_item.attrs, trait_item.span)
2652                 }
2653                 _ => {
2654                     ccx.sess().span_bug(trait_item.span,
2655                                         "unexpected variant: trait item other than a provided \
2656                                          method in get_item_val()");
2657                 }
2658             }
2659         }
2660
2661         hir_map::NodeImplItem(impl_item) => {
2662             match impl_item.node {
2663                 hir::ImplItemKind::Method(..) => {
2664                     register_method(ccx, id, &impl_item.attrs, impl_item.span)
2665                 }
2666                 _ => {
2667                     ccx.sess().span_bug(impl_item.span,
2668                                         "unexpected variant: non-method impl item in \
2669                                          get_item_val()");
2670                 }
2671             }
2672         }
2673
2674         hir_map::NodeForeignItem(ni) => {
2675             match ni.node {
2676                 hir::ForeignItemFn(..) => {
2677                     let abi = ccx.tcx().map.get_foreign_abi(id);
2678                     let ty = ccx.tcx().node_id_to_type(ni.id);
2679                     let name = foreign::link_name(&*ni);
2680                     foreign::register_foreign_item_fn(ccx, abi, ty, &name, &ni.attrs)
2681                 }
2682                 hir::ForeignItemStatic(..) => {
2683                     foreign::register_static(ccx, &*ni)
2684                 }
2685             }
2686         }
2687
2688         hir_map::NodeVariant(ref v) => {
2689             let llfn;
2690             let fields = if v.node.data.is_struct() {
2691                 ccx.sess().bug("struct variant kind unexpected in get_item_val")
2692             } else {
2693                 v.node.data.fields()
2694             };
2695             assert!(!fields.is_empty());
2696             let ty = ccx.tcx().node_id_to_type(id);
2697             let parent = ccx.tcx().map.get_parent(id);
2698             let enm = ccx.tcx().map.expect_item(parent);
2699             let sym = exported_name(ccx, id, ty, &enm.attrs);
2700
2701             llfn = match enm.node {
2702                 hir::ItemEnum(_, _) => {
2703                     register_fn(ccx, (*v).span, sym, id, ty)
2704                 }
2705                 _ => ccx.sess().bug("NodeVariant, shouldn't happen"),
2706             };
2707             attributes::inline(llfn, attributes::InlineAttr::Hint);
2708             llfn
2709         }
2710
2711         hir_map::NodeStructCtor(struct_def) => {
2712             // Only register the constructor if this is a tuple-like struct.
2713             let ctor_id = if struct_def.is_struct() {
2714                 ccx.sess().bug("attempt to register a constructor of a non-tuple-like struct")
2715             } else {
2716                 struct_def.id()
2717             };
2718             let parent = ccx.tcx().map.get_parent(id);
2719             let struct_item = ccx.tcx().map.expect_item(parent);
2720             let ty = ccx.tcx().node_id_to_type(ctor_id);
2721             let sym = exported_name(ccx, id, ty, &struct_item.attrs);
2722             let llfn = register_fn(ccx, struct_item.span, sym, ctor_id, ty);
2723             attributes::inline(llfn, attributes::InlineAttr::Hint);
2724             llfn
2725         }
2726
2727         ref variant => {
2728             ccx.sess().bug(&format!("get_item_val(): unexpected variant: {:?}", variant))
2729         }
2730     };
2731
2732     // All LLVM globals and functions are initially created as external-linkage
2733     // declarations.  If `trans_item`/`trans_fn` later turns the declaration
2734     // into a definition, it adjusts the linkage then (using `update_linkage`).
2735     //
2736     // The exception is foreign items, which have their linkage set inside the
2737     // call to `foreign::register_*` above.  We don't touch the linkage after
2738     // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2739     // other item translation functions do).
2740
2741     ccx.item_vals().borrow_mut().insert(id, val);
2742     val
2743 }
2744
2745 fn register_method(ccx: &CrateContext,
2746                    id: ast::NodeId,
2747                    attrs: &[ast::Attribute],
2748                    span: Span)
2749                    -> ValueRef {
2750     let mty = ccx.tcx().node_id_to_type(id);
2751
2752     let sym = exported_name(ccx, id, mty, &attrs);
2753
2754     if let ty::TyBareFn(_, ref f) = mty.sty {
2755         let llfn = if f.abi == Rust || f.abi == RustCall {
2756             register_fn(ccx, span, sym, id, mty)
2757         } else {
2758             foreign::register_rust_fn_with_foreign_abi(ccx, span, sym, id)
2759         };
2760         attributes::from_fn_attrs(ccx, &attrs, llfn);
2761         return llfn;
2762     } else {
2763         ccx.sess().span_bug(span, "expected bare rust function");
2764     }
2765 }
2766
2767 pub fn write_metadata<'a, 'tcx>(cx: &SharedCrateContext<'a, 'tcx>,
2768                                 krate: &hir::Crate,
2769                                 reachable: &NodeSet,
2770                                 mir_map: &MirMap<'tcx>)
2771                                 -> Vec<u8> {
2772     use flate;
2773
2774     let any_library = cx.sess()
2775                         .crate_types
2776                         .borrow()
2777                         .iter()
2778                         .any(|ty| *ty != config::CrateTypeExecutable);
2779     if !any_library {
2780         return Vec::new();
2781     }
2782
2783     let cstore = &cx.tcx().sess.cstore;
2784     let metadata = cstore.encode_metadata(cx.tcx(),
2785                                           cx.export_map(),
2786                                           cx.item_symbols(),
2787                                           cx.link_meta(),
2788                                           reachable,
2789                                           mir_map,
2790                                           krate);
2791     let mut compressed = cstore.metadata_encoding_version().to_vec();
2792     compressed.extend_from_slice(&flate::deflate_bytes(&metadata));
2793
2794     let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2795     let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2796     let name = format!("rust_metadata_{}_{}",
2797                        cx.link_meta().crate_name,
2798                        cx.link_meta().crate_hash);
2799     let buf = CString::new(name).unwrap();
2800     let llglobal = unsafe {
2801         llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf.as_ptr())
2802     };
2803     unsafe {
2804         llvm::LLVMSetInitializer(llglobal, llconst);
2805         let name =
2806             cx.tcx().sess.cstore.metadata_section_name(&cx.sess().target.target);
2807         let name = CString::new(name).unwrap();
2808         llvm::LLVMSetSection(llglobal, name.as_ptr())
2809     }
2810     return metadata;
2811 }
2812
2813 /// Find any symbols that are defined in one compilation unit, but not declared
2814 /// in any other compilation unit.  Give these symbols internal linkage.
2815 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<&str>) {
2816     unsafe {
2817         let mut declared = HashSet::new();
2818
2819         // Collect all external declarations in all compilation units.
2820         for ccx in cx.iter() {
2821             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2822                 let linkage = llvm::LLVMGetLinkage(val);
2823                 // We only care about external declarations (not definitions)
2824                 // and available_externally definitions.
2825                 if !(linkage == llvm::ExternalLinkage as c_uint &&
2826                      llvm::LLVMIsDeclaration(val) != 0) &&
2827                    !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2828                     continue;
2829                 }
2830
2831                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2832                                .to_bytes()
2833                                .to_vec();
2834                 declared.insert(name);
2835             }
2836         }
2837
2838         // Examine each external definition.  If the definition is not used in
2839         // any other compilation unit, and is not reachable from other crates,
2840         // then give it internal linkage.
2841         for ccx in cx.iter() {
2842             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2843                 // We only care about external definitions.
2844                 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
2845                      llvm::LLVMIsDeclaration(val) == 0) {
2846                     continue;
2847                 }
2848
2849                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2850                                .to_bytes()
2851                                .to_vec();
2852                 if !declared.contains(&name) &&
2853                    !reachable.contains(str::from_utf8(&name).unwrap()) {
2854                     llvm::SetLinkage(val, llvm::InternalLinkage);
2855                     llvm::SetDLLStorageClass(val, llvm::DefaultStorageClass);
2856                 }
2857             }
2858         }
2859     }
2860 }
2861
2862 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2863 // This is required to satisfy `dllimport` references to static data in .rlibs
2864 // when using MSVC linker.  We do this only for data, as linker can fix up
2865 // code references on its own.
2866 // See #26591, #27438
2867 fn create_imps(cx: &SharedCrateContext) {
2868     // The x86 ABI seems to require that leading underscores are added to symbol
2869     // names, so we need an extra underscore on 32-bit. There's also a leading
2870     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2871     // underscores added in front).
2872     let prefix = if cx.sess().target.target.target_pointer_width == "32" {
2873         "\x01__imp__"
2874     } else {
2875         "\x01__imp_"
2876     };
2877     unsafe {
2878         for ccx in cx.iter() {
2879             let exported: Vec<_> = iter_globals(ccx.llmod())
2880                                        .filter(|&val| {
2881                                            llvm::LLVMGetLinkage(val) ==
2882                                            llvm::ExternalLinkage as c_uint &&
2883                                            llvm::LLVMIsDeclaration(val) == 0
2884                                        })
2885                                        .collect();
2886
2887             let i8p_ty = Type::i8p(&ccx);
2888             for val in exported {
2889                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2890                 let mut imp_name = prefix.as_bytes().to_vec();
2891                 imp_name.extend(name.to_bytes());
2892                 let imp_name = CString::new(imp_name).unwrap();
2893                 let imp = llvm::LLVMAddGlobal(ccx.llmod(),
2894                                               i8p_ty.to_ref(),
2895                                               imp_name.as_ptr() as *const _);
2896                 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
2897                 llvm::LLVMSetInitializer(imp, init);
2898                 llvm::SetLinkage(imp, llvm::ExternalLinkage);
2899             }
2900         }
2901     }
2902 }
2903
2904 struct ValueIter {
2905     cur: ValueRef,
2906     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
2907 }
2908
2909 impl Iterator for ValueIter {
2910     type Item = ValueRef;
2911
2912     fn next(&mut self) -> Option<ValueRef> {
2913         let old = self.cur;
2914         if !old.is_null() {
2915             self.cur = unsafe { (self.step)(old) };
2916             Some(old)
2917         } else {
2918             None
2919         }
2920     }
2921 }
2922
2923 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
2924     unsafe {
2925         ValueIter {
2926             cur: llvm::LLVMGetFirstGlobal(llmod),
2927             step: llvm::LLVMGetNextGlobal,
2928         }
2929     }
2930 }
2931
2932 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
2933     unsafe {
2934         ValueIter {
2935             cur: llvm::LLVMGetFirstFunction(llmod),
2936             step: llvm::LLVMGetNextFunction,
2937         }
2938     }
2939 }
2940
2941 /// The context provided lists a set of reachable ids as calculated by
2942 /// middle::reachable, but this contains far more ids and symbols than we're
2943 /// actually exposing from the object file. This function will filter the set in
2944 /// the context to the set of ids which correspond to symbols that are exposed
2945 /// from the object file being generated.
2946 ///
2947 /// This list is later used by linkers to determine the set of symbols needed to
2948 /// be exposed from a dynamic library and it's also encoded into the metadata.
2949 pub fn filter_reachable_ids(ccx: &SharedCrateContext) -> NodeSet {
2950     ccx.reachable().iter().map(|x| *x).filter(|id| {
2951         // First, only worry about nodes which have a symbol name
2952         ccx.item_symbols().borrow().contains_key(id)
2953     }).filter(|&id| {
2954         // Next, we want to ignore some FFI functions that are not exposed from
2955         // this crate. Reachable FFI functions can be lumped into two
2956         // categories:
2957         //
2958         // 1. Those that are included statically via a static library
2959         // 2. Those included otherwise (e.g. dynamically or via a framework)
2960         //
2961         // Although our LLVM module is not literally emitting code for the
2962         // statically included symbols, it's an export of our library which
2963         // needs to be passed on to the linker and encoded in the metadata.
2964         //
2965         // As a result, if this id is an FFI item (foreign item) then we only
2966         // let it through if it's included statically.
2967         match ccx.tcx().map.get(id) {
2968             hir_map::NodeForeignItem(..) => {
2969                 ccx.sess().cstore.is_statically_included_foreign_item(id)
2970             }
2971             _ => true,
2972         }
2973     }).collect()
2974 }
2975
2976 pub fn trans_crate<'tcx>(tcx: &ty::ctxt<'tcx>,
2977                          mir_map: &MirMap<'tcx>,
2978                          analysis: ty::CrateAnalysis)
2979                          -> CrateTranslation {
2980     let ty::CrateAnalysis { export_map, reachable, name, .. } = analysis;
2981     let krate = tcx.map.krate();
2982
2983     let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
2984         v
2985     } else {
2986         tcx.sess.opts.debug_assertions
2987     };
2988
2989     let check_dropflag = if let Some(v) = tcx.sess.opts.debugging_opts.force_dropflag_checks {
2990         v
2991     } else {
2992         tcx.sess.opts.debug_assertions
2993     };
2994
2995     // Before we touch LLVM, make sure that multithreading is enabled.
2996     unsafe {
2997         use std::sync::Once;
2998         static INIT: Once = Once::new();
2999         static mut POISONED: bool = false;
3000         INIT.call_once(|| {
3001             if llvm::LLVMStartMultithreaded() != 1 {
3002                 // use an extra bool to make sure that all future usage of LLVM
3003                 // cannot proceed despite the Once not running more than once.
3004                 POISONED = true;
3005             }
3006
3007             ::back::write::configure_llvm(&tcx.sess);
3008         });
3009
3010         if POISONED {
3011             tcx.sess.bug("couldn't enable multi-threaded LLVM");
3012         }
3013     }
3014
3015     let link_meta = link::build_link_meta(&tcx.sess, krate, name);
3016
3017     let codegen_units = tcx.sess.opts.cg.codegen_units;
3018     let shared_ccx = SharedCrateContext::new(&link_meta.crate_name,
3019                                              codegen_units,
3020                                              tcx,
3021                                              &mir_map,
3022                                              export_map,
3023                                              Sha256::new(),
3024                                              link_meta.clone(),
3025                                              reachable,
3026                                              check_overflow,
3027                                              check_dropflag);
3028
3029     {
3030         let ccx = shared_ccx.get_ccx(0);
3031
3032         // First, verify intrinsics.
3033         intrinsic::check_intrinsics(&ccx);
3034
3035         // Next, translate all items. See `TransModVisitor` for
3036         // details on why we walk in this particular way.
3037         {
3038             let _icx = push_ctxt("text");
3039             intravisit::walk_mod(&mut TransItemsWithinModVisitor { ccx: &ccx }, &krate.module);
3040             krate.visit_all_items(&mut TransModVisitor { ccx: &ccx });
3041         }
3042     }
3043
3044     for ccx in shared_ccx.iter() {
3045         if ccx.sess().opts.debuginfo != NoDebugInfo {
3046             debuginfo::finalize(&ccx);
3047         }
3048         for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
3049             unsafe {
3050                 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
3051                 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
3052                 llvm::LLVMDeleteGlobal(old_g);
3053             }
3054         }
3055     }
3056
3057     let reachable_symbol_ids = filter_reachable_ids(&shared_ccx);
3058
3059     // Translate the metadata.
3060     let metadata = write_metadata(&shared_ccx, krate, &reachable_symbol_ids, mir_map);
3061
3062     if shared_ccx.sess().trans_stats() {
3063         let stats = shared_ccx.stats();
3064         println!("--- trans stats ---");
3065         println!("n_glues_created: {}", stats.n_glues_created.get());
3066         println!("n_null_glues: {}", stats.n_null_glues.get());
3067         println!("n_real_glues: {}", stats.n_real_glues.get());
3068
3069         println!("n_fns: {}", stats.n_fns.get());
3070         println!("n_monos: {}", stats.n_monos.get());
3071         println!("n_inlines: {}", stats.n_inlines.get());
3072         println!("n_closures: {}", stats.n_closures.get());
3073         println!("fn stats:");
3074         stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
3075             insns_b.cmp(&insns_a)
3076         });
3077         for tuple in stats.fn_stats.borrow().iter() {
3078             match *tuple {
3079                 (ref name, insns) => {
3080                     println!("{} insns, {}", insns, *name);
3081                 }
3082             }
3083         }
3084     }
3085     if shared_ccx.sess().count_llvm_insns() {
3086         for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
3087             println!("{:7} {}", *v, *k);
3088         }
3089     }
3090
3091     let modules = shared_ccx.iter()
3092         .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
3093         .collect();
3094
3095     let sess = shared_ccx.sess();
3096     let mut reachable_symbols = reachable_symbol_ids.iter().map(|id| {
3097         shared_ccx.item_symbols().borrow()[id].to_string()
3098     }).collect::<Vec<_>>();
3099     if sess.entry_fn.borrow().is_some() {
3100         reachable_symbols.push("main".to_string());
3101     }
3102
3103     // For the purposes of LTO, we add to the reachable set all of the upstream
3104     // reachable extern fns. These functions are all part of the public ABI of
3105     // the final product, so LTO needs to preserve them.
3106     if sess.lto() {
3107         for cnum in sess.cstore.crates() {
3108             let syms = sess.cstore.reachable_ids(cnum);
3109             reachable_symbols.extend(syms.into_iter().filter(|did| {
3110                 sess.cstore.is_extern_fn(shared_ccx.tcx(), *did) ||
3111                 sess.cstore.is_static(*did)
3112             }).map(|did| {
3113                 sess.cstore.item_symbol(did)
3114             }));
3115         }
3116     }
3117
3118     if codegen_units > 1 {
3119         internalize_symbols(&shared_ccx,
3120                             &reachable_symbols.iter().map(|x| &x[..]).collect());
3121     }
3122
3123     if sess.target.target.options.is_like_msvc &&
3124        sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
3125         create_imps(&shared_ccx);
3126     }
3127
3128     let metadata_module = ModuleTranslation {
3129         llcx: shared_ccx.metadata_llcx(),
3130         llmod: shared_ccx.metadata_llmod(),
3131     };
3132     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
3133
3134     CrateTranslation {
3135         modules: modules,
3136         metadata_module: metadata_module,
3137         link: link_meta,
3138         metadata: metadata,
3139         reachable: reachable_symbols,
3140         no_builtins: no_builtins,
3141     }
3142 }
3143
3144 /// We visit all the items in the krate and translate them.  We do
3145 /// this in two walks. The first walk just finds module items. It then
3146 /// walks the full contents of those module items and translates all
3147 /// the items within. Note that this entire process is O(n). The
3148 /// reason for this two phased walk is that each module is
3149 /// (potentially) placed into a distinct codegen-unit. This walk also
3150 /// ensures that the immediate contents of each module is processed
3151 /// entirely before we proceed to find more modules, helping to ensure
3152 /// an equitable distribution amongst codegen-units.
3153 pub struct TransModVisitor<'a, 'tcx: 'a> {
3154     pub ccx: &'a CrateContext<'a, 'tcx>,
3155 }
3156
3157 impl<'a, 'tcx, 'v> Visitor<'v> for TransModVisitor<'a, 'tcx> {
3158     fn visit_item(&mut self, i: &hir::Item) {
3159         match i.node {
3160             hir::ItemMod(_) => {
3161                 let item_ccx = self.ccx.rotate();
3162                 intravisit::walk_item(&mut TransItemsWithinModVisitor { ccx: &item_ccx }, i);
3163             }
3164             _ => { }
3165         }
3166     }
3167 }
3168
3169 /// Translates all the items within a given module. Expects owner to
3170 /// invoke `walk_item` on a module item. Ignores nested modules.
3171 pub struct TransItemsWithinModVisitor<'a, 'tcx: 'a> {
3172     pub ccx: &'a CrateContext<'a, 'tcx>,
3173 }
3174
3175 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemsWithinModVisitor<'a, 'tcx> {
3176     fn visit_nested_item(&mut self, item_id: hir::ItemId) {
3177         self.visit_item(self.ccx.tcx().map.expect_item(item_id.id));
3178     }
3179
3180     fn visit_item(&mut self, i: &hir::Item) {
3181         match i.node {
3182             hir::ItemMod(..) => {
3183                 // skip modules, they will be uncovered by the TransModVisitor
3184             }
3185             _ => {
3186                 trans_item(self.ccx, i);
3187                 intravisit::walk_item(self, i);
3188             }
3189         }
3190     }
3191 }