]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/base.rs
4879975dde695c265bd7505b3e1127a0bccebf5c
[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 metadata::{csearch, encoder, loader};
38 use middle::astencode;
39 use middle::cfg;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::weak_lang_items;
42 use middle::subst::Substs;
43 use middle::ty::{self, Ty, ClosureTyper, type_is_simd, simd_size};
44 use session::config::{self, NoDebugInfo};
45 use session::Session;
46 use trans::_match;
47 use trans::adt;
48 use trans::attributes;
49 use trans::build::*;
50 use trans::builder::{Builder, noname};
51 use trans::callee;
52 use trans::cleanup::CleanupMethods;
53 use trans::cleanup;
54 use trans::closure;
55 use trans::common::{Block, C_bool, C_bytes_in_context, C_i32, C_int, C_integral};
56 use trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
57 use trans::common::{CrateContext, FunctionContext};
58 use trans::common::{Result, NodeIdAndSpan};
59 use trans::common::{node_id_type, return_type_is_void};
60 use trans::common::{type_is_immediate, type_is_zero_size, val_ty};
61 use trans::common;
62 use trans::consts;
63 use trans::context::SharedCrateContext;
64 use trans::controlflow;
65 use trans::datum;
66 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
67 use trans::declare;
68 use trans::expr;
69 use trans::foreign;
70 use trans::glue;
71 use trans::intrinsic;
72 use trans::machine;
73 use trans::machine::{llsize_of, llsize_of_real};
74 use trans::meth;
75 use trans::monomorphize;
76 use trans::tvec;
77 use trans::type_::Type;
78 use trans::type_of;
79 use trans::type_of::*;
80 use trans::value::Value;
81 use util::common::indenter;
82 use util::ppaux::{Repr, ty_to_string};
83 use util::sha2::Sha256;
84 use util::nodemap::NodeMap;
85
86 use arena::TypedArena;
87 use libc::c_uint;
88 use std::ffi::{CStr, CString};
89 use std::cell::{Cell, RefCell};
90 use std::collections::HashSet;
91 use std::mem;
92 use std::str;
93 use std::{i8, i16, i32, i64};
94 use syntax::abi::{Rust, RustCall, RustIntrinsic, Abi};
95 use syntax::ast_util::local_def;
96 use syntax::attr::AttrMetaMethods;
97 use syntax::attr;
98 use syntax::codemap::Span;
99 use syntax::parse::token::InternedString;
100 use syntax::visit::Visitor;
101 use syntax::visit;
102 use syntax::{ast, ast_util, ast_map};
103
104 thread_local! {
105     static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
106         RefCell::new(None)
107     }
108 }
109
110 pub fn with_insn_ctxt<F>(blk: F) where
111     F: FnOnce(&[&'static str]),
112 {
113     TASK_LOCAL_INSN_KEY.with(move |slot| {
114         slot.borrow().as_ref().map(move |s| blk(s));
115     })
116 }
117
118 pub fn init_insn_ctxt() {
119     TASK_LOCAL_INSN_KEY.with(|slot| {
120         *slot.borrow_mut() = Some(Vec::new());
121     });
122 }
123
124 pub struct _InsnCtxt {
125     _cannot_construct_outside_of_this_module: ()
126 }
127
128 impl Drop for _InsnCtxt {
129     fn drop(&mut self) {
130         TASK_LOCAL_INSN_KEY.with(|slot| {
131             match slot.borrow_mut().as_mut() {
132                 Some(ctx) => { ctx.pop(); }
133                 None => {}
134             }
135         })
136     }
137 }
138
139 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
140     debug!("new InsnCtxt: {}", s);
141     TASK_LOCAL_INSN_KEY.with(|slot| {
142         match slot.borrow_mut().as_mut() {
143             Some(ctx) => ctx.push(s),
144             None => {}
145         }
146     });
147     _InsnCtxt { _cannot_construct_outside_of_this_module: () }
148 }
149
150 pub struct StatRecorder<'a, 'tcx: 'a> {
151     ccx: &'a CrateContext<'a, 'tcx>,
152     name: Option<String>,
153     istart: usize,
154 }
155
156 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
157     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String)
158                -> StatRecorder<'a, 'tcx> {
159         let istart = ccx.stats().n_llvm_insns.get();
160         StatRecorder {
161             ccx: ccx,
162             name: Some(name),
163             istart: istart,
164         }
165     }
166 }
167
168 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
169     fn drop(&mut self) {
170         if self.ccx.sess().trans_stats() {
171             let iend = self.ccx.stats().n_llvm_insns.get();
172             self.ccx.stats().fn_stats.borrow_mut().push((self.name.take().unwrap(),
173                                                        iend - self.istart));
174             self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
175             // Reset LLVM insn count to avoid compound costs.
176             self.ccx.stats().n_llvm_insns.set(self.istart);
177         }
178     }
179 }
180
181 fn get_extern_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<'tcx>,
182                                 name: &str, did: ast::DefId) -> ValueRef {
183     match ccx.externs().borrow().get(name) {
184         Some(n) => return *n,
185         None => ()
186     }
187
188     let f = declare::declare_rust_fn(ccx, name, fn_ty);
189
190     let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
191     attributes::from_fn_attrs(ccx, &attrs[..], f);
192
193     ccx.externs().borrow_mut().insert(name.to_string(), f);
194     f
195 }
196
197 pub fn self_type_for_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
198                                        closure_id: ast::DefId,
199                                        fn_ty: Ty<'tcx>)
200                                        -> Ty<'tcx>
201 {
202     let closure_kind = ccx.tcx().closure_kind(closure_id);
203     match closure_kind {
204         ty::FnClosureKind => {
205             ty::mk_imm_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
206         }
207         ty::FnMutClosureKind => {
208             ty::mk_mut_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
209         }
210         ty::FnOnceClosureKind => fn_ty
211     }
212 }
213
214 pub fn kind_for_closure(ccx: &CrateContext, closure_id: ast::DefId) -> ty::ClosureKind {
215     *ccx.tcx().closure_kinds.borrow().get(&closure_id).unwrap()
216 }
217
218 pub fn get_extern_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
219                                   t: Ty<'tcx>) -> ValueRef {
220     let name = csearch::get_symbol(&ccx.sess().cstore, did);
221     let ty = type_of(ccx, t);
222     match ccx.externs().borrow_mut().get(&name) {
223         Some(n) => return *n,
224         None => ()
225     }
226     // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
227     // FIXME(nagisa): investigate whether it can be changed into define_global
228     let c = declare::declare_global(ccx, &name[..], ty);
229     // Thread-local statics in some other crate need to *always* be linked
230     // against in a thread-local fashion, so we need to be sure to apply the
231     // thread-local attribute locally if it was present remotely. If we
232     // don't do this then linker errors can be generated where the linker
233     // complains that one object files has a thread local version of the
234     // symbol and another one doesn't.
235     for attr in &*ty::get_attrs(ccx.tcx(), did) {
236         if attr.check_name("thread_local") {
237             llvm::set_thread_local(c, true);
238         }
239     }
240     ccx.externs().borrow_mut().insert(name.to_string(), c);
241     return c;
242 }
243
244 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
245                                 info_ty: Ty<'tcx>, it: LangItem) -> ast::DefId {
246     match bcx.tcx().lang_items.require(it) {
247         Ok(id) => id,
248         Err(s) => {
249             bcx.sess().fatal(&format!("allocation of `{}` {}",
250                                      bcx.ty_to_string(info_ty),
251                                      s));
252         }
253     }
254 }
255
256 // The following malloc_raw_dyn* functions allocate a box to contain
257 // a given type, but with a potentially dynamic size.
258
259 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
260                                   llty_ptr: Type,
261                                   info_ty: Ty<'tcx>,
262                                   size: ValueRef,
263                                   align: ValueRef,
264                                   debug_loc: DebugLoc)
265                                   -> Result<'blk, 'tcx> {
266     let _icx = push_ctxt("malloc_raw_exchange");
267
268     // Allocate space:
269     let r = callee::trans_lang_call(bcx,
270         require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
271         &[size, align],
272         None,
273         debug_loc);
274
275     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
276 }
277
278
279 pub fn bin_op_to_icmp_predicate(ccx: &CrateContext, op: ast::BinOp_, signed: bool)
280                                 -> llvm::IntPredicate {
281     match op {
282         ast::BiEq => llvm::IntEQ,
283         ast::BiNe => llvm::IntNE,
284         ast::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
285         ast::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
286         ast::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
287         ast::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
288         op => {
289             ccx.sess().bug(&format!("comparison_op_to_icmp_predicate: expected \
290                                      comparison operator, found {:?}", op));
291         }
292     }
293 }
294
295 pub fn bin_op_to_fcmp_predicate(ccx: &CrateContext, op: ast::BinOp_)
296                                 -> llvm::RealPredicate {
297     match op {
298         ast::BiEq => llvm::RealOEQ,
299         ast::BiNe => llvm::RealUNE,
300         ast::BiLt => llvm::RealOLT,
301         ast::BiLe => llvm::RealOLE,
302         ast::BiGt => llvm::RealOGT,
303         ast::BiGe => llvm::RealOGE,
304         op => {
305             ccx.sess().bug(&format!("comparison_op_to_fcmp_predicate: expected \
306                                      comparison operator, found {:?}", op));
307         }
308     }
309 }
310
311 pub fn compare_scalar_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
312                                         lhs: ValueRef,
313                                         rhs: ValueRef,
314                                         t: Ty<'tcx>,
315                                         op: ast::BinOp_,
316                                         debug_loc: DebugLoc)
317                                         -> ValueRef {
318     match t.sty {
319         ty::ty_tup(ref tys) if tys.is_empty() => {
320             // We don't need to do actual comparisons for nil.
321             // () == () holds but () < () does not.
322             match op {
323                 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(bcx.ccx(), true),
324                 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(bcx.ccx(), false),
325                 // refinements would be nice
326                 _ => bcx.sess().bug("compare_scalar_types: must be a comparison operator")
327             }
328         }
329         ty::ty_bare_fn(..) | ty::ty_bool | ty::ty_uint(_) | ty::ty_char => {
330             ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
331         }
332         ty::ty_ptr(mt) if common::type_is_sized(bcx.tcx(), mt.ty) => {
333             ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
334         }
335         ty::ty_int(_) => {
336             ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, true), lhs, rhs, debug_loc)
337         }
338         ty::ty_float(_) => {
339             FCmp(bcx, bin_op_to_fcmp_predicate(bcx.ccx(), op), lhs, rhs, debug_loc)
340         }
341         // Should never get here, because t is scalar.
342         _ => bcx.sess().bug("non-scalar type passed to compare_scalar_types")
343     }
344 }
345
346 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
347                                       lhs: ValueRef,
348                                       rhs: ValueRef,
349                                       t: Ty<'tcx>,
350                                       op: ast::BinOp_,
351                                       debug_loc: DebugLoc)
352                                       -> ValueRef {
353     let signed = match t.sty {
354         ty::ty_float(_) => {
355             // The comparison operators for floating point vectors are challenging.
356             // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
357             // then bitcast to a floating point vector, the result will be `-NaN`
358             // for each truth value. Because of this they are unsupported.
359             bcx.sess().bug("compare_simd_types: comparison operators \
360                             not supported for floating point SIMD types")
361         },
362         ty::ty_uint(_) => false,
363         ty::ty_int(_) => true,
364         _ => bcx.sess().bug("compare_simd_types: invalid SIMD type"),
365     };
366
367     let cmp = bin_op_to_icmp_predicate(bcx.ccx(), op, signed);
368     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
369     // to get the correctly sized type. This will compile to a single instruction
370     // once the IR is converted to assembly if the SIMD instruction is supported
371     // by the target architecture.
372     SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), val_ty(lhs))
373 }
374
375 // Iterates through the elements of a structural type.
376 pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
377                                          av: ValueRef,
378                                          t: Ty<'tcx>,
379                                          mut f: F)
380                                          -> Block<'blk, 'tcx> where
381     F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
382 {
383     let _icx = push_ctxt("iter_structural_ty");
384
385     fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
386                                    repr: &adt::Repr<'tcx>,
387                                    av: ValueRef,
388                                    variant: &ty::VariantInfo<'tcx>,
389                                    substs: &Substs<'tcx>,
390                                    f: &mut F)
391                                    -> Block<'blk, 'tcx> where
392         F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
393     {
394         let _icx = push_ctxt("iter_variant");
395         let tcx = cx.tcx();
396         let mut cx = cx;
397
398         for (i, &arg) in variant.args.iter().enumerate() {
399             let arg = monomorphize::apply_param_substs(tcx, substs, &arg);
400             cx = f(cx, adt::trans_field_ptr(cx, repr, av, variant.disr_val, i), arg);
401         }
402         return cx;
403     }
404
405     let (data_ptr, info) = if common::type_is_sized(cx.tcx(), t) {
406         (av, None)
407     } else {
408         let data = GEPi(cx, av, &[0, abi::FAT_PTR_ADDR]);
409         let info = GEPi(cx, av, &[0, abi::FAT_PTR_EXTRA]);
410         (Load(cx, data), Some(Load(cx, info)))
411     };
412
413     let mut cx = cx;
414     match t.sty {
415       ty::ty_struct(..) => {
416           let repr = adt::represent_type(cx.ccx(), t);
417           expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
418               for (i, field_ty) in field_tys.iter().enumerate() {
419                   let field_ty = field_ty.mt.ty;
420                   let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, discr, i);
421
422                   let val = if common::type_is_sized(cx.tcx(), field_ty) {
423                       llfld_a
424                   } else {
425                       let scratch = datum::rvalue_scratch_datum(cx, field_ty, "__fat_ptr_iter");
426                       Store(cx, llfld_a, GEPi(cx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
427                       Store(cx, info.unwrap(), GEPi(cx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
428                       scratch.val
429                   };
430                   cx = f(cx, val, field_ty);
431               }
432           })
433       }
434       ty::ty_closure(def_id, substs) => {
435           let repr = adt::represent_type(cx.ccx(), t);
436           let typer = common::NormalizingClosureTyper::new(cx.tcx());
437           let upvars = typer.closure_upvars(def_id, substs).unwrap();
438           for (i, upvar) in upvars.iter().enumerate() {
439               let llupvar = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
440               cx = f(cx, llupvar, upvar.ty);
441           }
442       }
443       ty::ty_vec(_, Some(n)) => {
444         let (base, len) = tvec::get_fixed_base_and_len(cx, data_ptr, n);
445         let unit_ty = ty::sequence_element_type(cx.tcx(), t);
446         cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
447       }
448       ty::ty_vec(_, None) | ty::ty_str => {
449         let unit_ty = ty::sequence_element_type(cx.tcx(), t);
450         cx = tvec::iter_vec_raw(cx, data_ptr, unit_ty, info.unwrap(), f);
451       }
452       ty::ty_tup(ref args) => {
453           let repr = adt::represent_type(cx.ccx(), t);
454           for (i, arg) in args.iter().enumerate() {
455               let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
456               cx = f(cx, llfld_a, *arg);
457           }
458       }
459       ty::ty_enum(tid, substs) => {
460           let fcx = cx.fcx;
461           let ccx = fcx.ccx;
462
463           let repr = adt::represent_type(ccx, t);
464           let variants = ty::enum_variants(ccx.tcx(), tid);
465           let n_variants = (*variants).len();
466
467           // NB: we must hit the discriminant first so that structural
468           // comparison know not to proceed when the discriminants differ.
469
470           match adt::trans_switch(cx, &*repr, av) {
471               (_match::Single, None) => {
472                   if n_variants != 0 {
473                       assert!(n_variants == 1);
474                       cx = iter_variant(cx, &*repr, av, &*(*variants)[0],
475                                         substs, &mut f);
476                   }
477               }
478               (_match::Switch, Some(lldiscrim_a)) => {
479                   cx = f(cx, lldiscrim_a, cx.tcx().types.isize);
480                   let unr_cx = fcx.new_temp_block("enum-iter-unr");
481                   Unreachable(unr_cx);
482                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
483                                         n_variants);
484                   let next_cx = fcx.new_temp_block("enum-iter-next");
485
486                   for variant in &(*variants) {
487                       let variant_cx =
488                           fcx.new_temp_block(
489                               &format!("enum-iter-variant-{}",
490                                       &variant.disr_val.to_string())
491                               );
492                       match adt::trans_case(cx, &*repr, variant.disr_val) {
493                           _match::SingleResult(r) => {
494                               AddCase(llswitch, r.val, variant_cx.llbb)
495                           }
496                           _ => ccx.sess().unimpl("value from adt::trans_case \
497                                                   in iter_structural_ty")
498                       }
499                       let variant_cx =
500                           iter_variant(variant_cx,
501                                        &*repr,
502                                        data_ptr,
503                                        &**variant,
504                                        substs,
505                                        &mut f);
506                       Br(variant_cx, next_cx.llbb, DebugLoc::None);
507                   }
508                   cx = next_cx;
509               }
510               _ => ccx.sess().unimpl("value from adt::trans_switch \
511                                       in iter_structural_ty")
512           }
513       }
514       _ => {
515           cx.sess().unimpl(&format!("type in iter_structural_ty: {}",
516                                    ty_to_string(cx.tcx(), t)))
517       }
518     }
519     return cx;
520 }
521
522 pub fn cast_shift_expr_rhs(cx: Block,
523                            op: ast::BinOp_,
524                            lhs: ValueRef,
525                            rhs: ValueRef)
526                            -> ValueRef {
527     cast_shift_rhs(op, lhs, rhs,
528                    |a,b| Trunc(cx, a, b),
529                    |a,b| ZExt(cx, a, b))
530 }
531
532 pub fn cast_shift_const_rhs(op: ast::BinOp_,
533                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
534     cast_shift_rhs(op, lhs, rhs,
535                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
536                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
537 }
538
539 fn cast_shift_rhs<F, G>(op: ast::BinOp_,
540                         lhs: ValueRef,
541                         rhs: ValueRef,
542                         trunc: F,
543                         zext: G)
544                         -> ValueRef where
545     F: FnOnce(ValueRef, Type) -> ValueRef,
546     G: FnOnce(ValueRef, Type) -> ValueRef,
547 {
548     // Shifts may have any size int on the rhs
549     if ast_util::is_shift_binop(op) {
550         let mut rhs_llty = val_ty(rhs);
551         let mut lhs_llty = val_ty(lhs);
552         if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
553         if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
554         let rhs_sz = rhs_llty.int_width();
555         let lhs_sz = lhs_llty.int_width();
556         if lhs_sz < rhs_sz {
557             trunc(rhs, lhs_llty)
558         } else if lhs_sz > rhs_sz {
559             // FIXME (#1877: If shifting by negative
560             // values becomes not undefined then this is wrong.
561             zext(rhs, lhs_llty)
562         } else {
563             rhs
564         }
565     } else {
566         rhs
567     }
568 }
569
570 pub fn llty_and_min_for_signed_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
571                                               val_t: Ty<'tcx>) -> (Type, u64) {
572     match val_t.sty {
573         ty::ty_int(t) => {
574             let llty = Type::int_from_ty(cx.ccx(), t);
575             let min = match t {
576                 ast::TyIs if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
577                 ast::TyIs => i64::MIN as u64,
578                 ast::TyI8 => i8::MIN as u64,
579                 ast::TyI16 => i16::MIN as u64,
580                 ast::TyI32 => i32::MIN as u64,
581                 ast::TyI64 => i64::MIN as u64,
582             };
583             (llty, min)
584         }
585         _ => unreachable!(),
586     }
587 }
588
589 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
590                                 cx: Block<'blk, 'tcx>,
591                                 call_info: NodeIdAndSpan,
592                                 divrem: ast::BinOp,
593                                 lhs: ValueRef,
594                                 rhs: ValueRef,
595                                 rhs_t: Ty<'tcx>)
596                                 -> Block<'blk, 'tcx> {
597     let (zero_text, overflow_text) = if divrem.node == ast::BiDiv {
598         ("attempted to divide by zero",
599          "attempted to divide with overflow")
600     } else {
601         ("attempted remainder with a divisor of zero",
602          "attempted remainder with overflow")
603     };
604     let debug_loc = call_info.debug_loc();
605
606     let (is_zero, is_signed) = match rhs_t.sty {
607         ty::ty_int(t) => {
608             let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0, false);
609             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
610         }
611         ty::ty_uint(t) => {
612             let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0, false);
613             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
614         }
615         ty::ty_struct(_, _) if type_is_simd(cx.tcx(), rhs_t) => {
616             let mut res = C_bool(cx.ccx(), false);
617             for i in 0 .. simd_size(cx.tcx(), rhs_t) {
618                 res = Or(cx, res,
619                          IsNull(cx,
620                                 ExtractElement(cx, rhs, C_int(cx.ccx(), i as i64))), debug_loc);
621             }
622             (res, false)
623         }
624         _ => {
625             cx.sess().bug(&format!("fail-if-zero on unexpected type: {}",
626                                   ty_to_string(cx.tcx(), rhs_t)));
627         }
628     };
629     let bcx = with_cond(cx, is_zero, |bcx| {
630         controlflow::trans_fail(bcx, call_info, InternedString::new(zero_text))
631     });
632
633     // To quote LLVM's documentation for the sdiv instruction:
634     //
635     //      Division by zero leads to undefined behavior. Overflow also leads
636     //      to undefined behavior; this is a rare case, but can occur, for
637     //      example, by doing a 32-bit division of -2147483648 by -1.
638     //
639     // In order to avoid undefined behavior, we perform runtime checks for
640     // signed division/remainder which would trigger overflow. For unsigned
641     // integers, no action beyond checking for zero need be taken.
642     if is_signed {
643         let (llty, min) = llty_and_min_for_signed_ty(cx, rhs_t);
644         let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
645                              C_integral(llty, !0, false), debug_loc);
646         with_cond(bcx, minus_one, |bcx| {
647             let is_min = ICmp(bcx, llvm::IntEQ, lhs,
648                               C_integral(llty, min, true), debug_loc);
649             with_cond(bcx, is_min, |bcx| {
650                 controlflow::trans_fail(bcx,
651                                         call_info,
652                                         InternedString::new(overflow_text))
653             })
654         })
655     } else {
656         bcx
657     }
658 }
659
660 pub fn trans_external_path<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
661                                      did: ast::DefId, t: Ty<'tcx>) -> ValueRef {
662     let name = csearch::get_symbol(&ccx.sess().cstore, did);
663     match t.sty {
664         ty::ty_bare_fn(_, ref fn_ty) => {
665             match ccx.sess().target.target.adjust_abi(fn_ty.abi) {
666                 Rust | RustCall => {
667                     get_extern_rust_fn(ccx, t, &name[..], did)
668                 }
669                 RustIntrinsic => {
670                     ccx.sess().bug("unexpected intrinsic in trans_external_path")
671                 }
672                 _ => {
673                     let llfn = foreign::register_foreign_item_fn(ccx, fn_ty.abi, t, &name[..]);
674                     let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
675                     attributes::from_fn_attrs(ccx, &attrs, llfn);
676                     llfn
677                 }
678             }
679         }
680         _ => {
681             get_extern_const(ccx, did, t)
682         }
683     }
684 }
685
686 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
687                           llfn: ValueRef,
688                           llargs: &[ValueRef],
689                           fn_ty: Ty<'tcx>,
690                           debug_loc: DebugLoc)
691                           -> (ValueRef, Block<'blk, 'tcx>) {
692     let _icx = push_ctxt("invoke_");
693     if bcx.unreachable.get() {
694         return (C_null(Type::i8(bcx.ccx())), bcx);
695     }
696
697     let attributes = attributes::from_fn_type(bcx.ccx(), fn_ty);
698
699     match bcx.opt_node_id {
700         None => {
701             debug!("invoke at ???");
702         }
703         Some(id) => {
704             debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
705         }
706     }
707
708     if need_invoke(bcx) {
709         debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
710         for &llarg in llargs {
711             debug!("arg: {}", bcx.val_to_string(llarg));
712         }
713         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
714         let landing_pad = bcx.fcx.get_landing_pad();
715
716         let llresult = Invoke(bcx,
717                               llfn,
718                               &llargs[..],
719                               normal_bcx.llbb,
720                               landing_pad,
721                               Some(attributes),
722                               debug_loc);
723         return (llresult, normal_bcx);
724     } else {
725         debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
726         for &llarg in llargs {
727             debug!("arg: {}", bcx.val_to_string(llarg));
728         }
729
730         let llresult = Call(bcx,
731                             llfn,
732                             &llargs[..],
733                             Some(attributes),
734                             debug_loc);
735         return (llresult, bcx);
736     }
737 }
738
739 pub fn need_invoke(bcx: Block) -> bool {
740     if bcx.sess().no_landing_pads() {
741         return false;
742     }
743
744     // Avoid using invoke if we are already inside a landing pad.
745     if bcx.is_lpad {
746         return false;
747     }
748
749     bcx.fcx.needs_invoke()
750 }
751
752 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
753                                      v: ValueRef, t: Ty<'tcx>) -> ValueRef {
754     let _icx = push_ctxt("load_if_immediate");
755     if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
756     return v;
757 }
758
759 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
760 /// differs from the type used for SSA values. Also handles various special cases where the type
761 /// gives us better information about what we are loading.
762 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
763                            ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
764     if cx.unreachable.get() || type_is_zero_size(cx.ccx(), t) {
765         return C_undef(type_of::type_of(cx.ccx(), t));
766     }
767
768     let ptr = to_arg_ty_ptr(cx, ptr, t);
769     let align = type_of::align_of(cx.ccx(), t);
770
771     if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
772         let load = Load(cx, ptr);
773         unsafe {
774             llvm::LLVMSetAlignment(load, align);
775         }
776         return load;
777     }
778
779     unsafe {
780         let global = llvm::LLVMIsAGlobalVariable(ptr);
781         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
782             let val = llvm::LLVMGetInitializer(global);
783             if !val.is_null() {
784                 return from_arg_ty(cx, val, t);
785             }
786         }
787     }
788
789     let val =  if ty::type_is_bool(t) {
790         LoadRangeAssert(cx, ptr, 0, 2, llvm::False)
791     } else if ty::type_is_char(t) {
792         // a char is a Unicode codepoint, and so takes values from 0
793         // to 0x10FFFF inclusive only.
794         LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
795     } else if (ty::type_is_region_ptr(t) || ty::type_is_unique(t))
796         && !common::type_is_fat_ptr(cx.tcx(), t) {
797             LoadNonNull(cx, ptr)
798     } else {
799         Load(cx, ptr)
800     };
801
802     unsafe {
803         llvm::LLVMSetAlignment(val, align);
804     }
805
806     from_arg_ty(cx, val, t)
807 }
808
809 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
810 /// differs from the type used for SSA values.
811 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
812     if cx.unreachable.get() {
813         return;
814     }
815
816     let store = Store(cx, to_arg_ty(cx, v, t), to_arg_ty_ptr(cx, dst, t));
817     unsafe {
818         llvm::LLVMSetAlignment(store, type_of::align_of(cx.ccx(), t));
819     }
820 }
821
822 pub fn to_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
823     if ty::type_is_bool(ty) {
824         ZExt(bcx, val, Type::i8(bcx.ccx()))
825     } else {
826         val
827     }
828 }
829
830 pub fn from_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
831     if ty::type_is_bool(ty) {
832         Trunc(bcx, val, Type::i1(bcx.ccx()))
833     } else {
834         val
835     }
836 }
837
838 pub fn to_arg_ty_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef, ty: Ty<'tcx>) -> ValueRef {
839     if type_is_immediate(bcx.ccx(), ty) && type_of::type_of(bcx.ccx(), ty).is_aggregate() {
840         // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
841         // for this leads to bad optimizations, so its arg type is an appropriately sized integer
842         // and we have to convert it
843         BitCast(bcx, ptr, type_of::arg_type_of(bcx.ccx(), ty).ptr_to())
844     } else {
845         ptr
846     }
847 }
848
849 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &ast::Local)
850                               -> Block<'blk, 'tcx> {
851     debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
852     let _indenter = indenter();
853     let _icx = push_ctxt("init_local");
854     _match::store_local(bcx, local)
855 }
856
857 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
858                              is_lpad: bool,
859                              llbb: BasicBlockRef)
860                              -> Block<'blk, 'tcx> {
861     common::BlockS::new(llbb, is_lpad, None, fcx)
862 }
863
864 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
865                                 val: ValueRef,
866                                 f: F)
867                                 -> Block<'blk, 'tcx> where
868     F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>,
869 {
870     let _icx = push_ctxt("with_cond");
871
872     if bcx.unreachable.get() ||
873             (common::is_const(val) && common::const_to_uint(val) == 0) {
874         return bcx;
875     }
876
877     let fcx = bcx.fcx;
878     let next_cx = fcx.new_temp_block("next");
879     let cond_cx = fcx.new_temp_block("cond");
880     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
881     let after_cx = f(cond_cx);
882     if !after_cx.terminated.get() {
883         Br(after_cx, next_cx.llbb, DebugLoc::None);
884     }
885     next_cx
886 }
887
888 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
889     if cx.sess().opts.optimize == config::No {
890         return;
891     }
892
893     let _icx = push_ctxt("lifetime_start");
894     let ccx = cx.ccx();
895
896     let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
897     let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
898     let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
899     Call(cx, lifetime_start, &[llsize, ptr], None, DebugLoc::None);
900 }
901
902 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
903     if cx.sess().opts.optimize == config::No {
904         return;
905     }
906
907     let _icx = push_ctxt("lifetime_end");
908     let ccx = cx.ccx();
909
910     let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
911     let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
912     let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
913     Call(cx, lifetime_end, &[llsize, ptr], None, DebugLoc::None);
914 }
915
916 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
917     let _icx = push_ctxt("call_memcpy");
918     let ccx = cx.ccx();
919     let key = match &ccx.sess().target.target.target_pointer_width[..] {
920         "32" => "llvm.memcpy.p0i8.p0i8.i32",
921         "64" => "llvm.memcpy.p0i8.p0i8.i64",
922         tws => panic!("Unsupported target word size for memcpy: {}", tws),
923     };
924     let memcpy = ccx.get_intrinsic(&key);
925     let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
926     let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
927     let size = IntCast(cx, n_bytes, ccx.int_type());
928     let align = C_i32(ccx, align as i32);
929     let volatile = C_bool(ccx, false);
930     Call(cx, memcpy, &[dst_ptr, src_ptr, size, align, volatile], None, DebugLoc::None);
931 }
932
933 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
934                              dst: ValueRef, src: ValueRef,
935                              t: Ty<'tcx>) {
936     let _icx = push_ctxt("memcpy_ty");
937     let ccx = bcx.ccx();
938     if ty::type_is_structural(t) {
939         let llty = type_of::type_of(ccx, t);
940         let llsz = llsize_of(ccx, llty);
941         let llalign = type_of::align_of(ccx, t);
942         call_memcpy(bcx, dst, src, llsz, llalign as u32);
943     } else {
944         store_ty(bcx, load_ty(bcx, src, t), dst, t);
945     }
946 }
947
948 pub fn drop_done_fill_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
949     if cx.unreachable.get() { return; }
950     let _icx = push_ctxt("drop_done_fill_mem");
951     let bcx = cx;
952     memfill(&B(bcx), llptr, t, adt::DTOR_DONE);
953 }
954
955 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
956     if cx.unreachable.get() { return; }
957     let _icx = push_ctxt("init_zero_mem");
958     let bcx = cx;
959     memfill(&B(bcx), llptr, t, 0);
960 }
961
962 // Always use this function instead of storing a constant byte to the memory
963 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
964 // allocation for large data structures, and the generated code will be
965 // awful. (A telltale sign of this is large quantities of
966 // `mov [byte ptr foo],0` in the generated code.)
967 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
968     let _icx = push_ctxt("memfill");
969     let ccx = b.ccx;
970
971     let llty = type_of::type_of(ccx, ty);
972
973     let intrinsic_key = match &ccx.sess().target.target.target_pointer_width[..] {
974         "32" => "llvm.memset.p0i8.i32",
975         "64" => "llvm.memset.p0i8.i64",
976         tws => panic!("Unsupported target word size for memset: {}", tws),
977     };
978
979     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
980     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
981     let llzeroval = C_u8(ccx, byte as usize);
982     let size = machine::llsize_of(ccx, llty);
983     let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
984     let volatile = C_bool(ccx, false);
985     b.call(llintrinsicfn, &[llptr, llzeroval, size, align, volatile], None);
986 }
987
988 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, name: &str) -> ValueRef {
989     let _icx = push_ctxt("alloc_ty");
990     let ccx = bcx.ccx();
991     let ty = type_of::type_of(ccx, t);
992     assert!(!ty::type_has_params(t));
993     let val = alloca(bcx, ty, name);
994     return val;
995 }
996
997 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
998     let p = alloca_no_lifetime(cx, ty, name);
999     call_lifetime_start(cx, p);
1000     p
1001 }
1002
1003 pub fn alloca_no_lifetime(cx: Block, ty: Type, name: &str) -> ValueRef {
1004     let _icx = push_ctxt("alloca");
1005     if cx.unreachable.get() {
1006         unsafe {
1007             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1008         }
1009     }
1010     debuginfo::clear_source_location(cx.fcx);
1011     Alloca(cx, ty, name)
1012 }
1013
1014 // Creates the alloca slot which holds the pointer to the slot for the final return value
1015 pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1016                                           output_type: Ty<'tcx>) -> ValueRef {
1017     let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1018
1019     // We create an alloca to hold a pointer of type `output_type`
1020     // which will hold the pointer to the right alloca which has the
1021     // final ret value
1022     if fcx.needs_ret_allocas {
1023         // Let's create the stack slot
1024         let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1025
1026         // and if we're using an out pointer, then store that in our newly made slot
1027         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1028             let outptr = get_param(fcx.llfn, 0);
1029
1030             let b = fcx.ccx.builder();
1031             b.position_before(fcx.alloca_insert_pt.get().unwrap());
1032             b.store(outptr, slot);
1033         }
1034
1035         slot
1036
1037     // But if there are no nested returns, we skip the indirection and have a single
1038     // retslot
1039     } else {
1040         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1041             get_param(fcx.llfn, 0)
1042         } else {
1043             AllocaFcx(fcx, lloutputtype, "sret_slot")
1044         }
1045     }
1046 }
1047
1048 struct FindNestedReturn {
1049     found: bool,
1050 }
1051
1052 impl FindNestedReturn {
1053     fn new() -> FindNestedReturn {
1054         FindNestedReturn { found: false }
1055     }
1056 }
1057
1058 impl<'v> Visitor<'v> for FindNestedReturn {
1059     fn visit_expr(&mut self, e: &ast::Expr) {
1060         match e.node {
1061             ast::ExprRet(..) => {
1062                 self.found = true;
1063             }
1064             _ => visit::walk_expr(self, e)
1065         }
1066     }
1067 }
1068
1069 fn build_cfg(tcx: &ty::ctxt, id: ast::NodeId) -> (ast::NodeId, Option<cfg::CFG>) {
1070     let blk = match tcx.map.find(id) {
1071         Some(ast_map::NodeItem(i)) => {
1072             match i.node {
1073                 ast::ItemFn(_, _, _, _, ref blk) => {
1074                     blk
1075                 }
1076                 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1077             }
1078         }
1079         Some(ast_map::NodeTraitItem(trait_item)) => {
1080             match trait_item.node {
1081                 ast::MethodTraitItem(_, Some(ref body)) => body,
1082                 _ => {
1083                     tcx.sess.bug("unexpected variant: trait item other than a \
1084                                   provided method in has_nested_returns")
1085                 }
1086             }
1087         }
1088         Some(ast_map::NodeImplItem(impl_item)) => {
1089             match impl_item.node {
1090                 ast::MethodImplItem(_, ref body) => body,
1091                 _ => {
1092                     tcx.sess.bug("unexpected variant: non-method impl item in \
1093                                   has_nested_returns")
1094                 }
1095             }
1096         }
1097         Some(ast_map::NodeExpr(e)) => {
1098             match e.node {
1099                 ast::ExprClosure(_, _, ref blk) => blk,
1100                 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1101             }
1102         }
1103         Some(ast_map::NodeVariant(..)) |
1104         Some(ast_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1105
1106         // glue, shims, etc
1107         None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1108
1109         _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
1110                                    tcx.map.path_to_string(id)))
1111     };
1112
1113     (blk.id, Some(cfg::CFG::new(tcx, blk)))
1114 }
1115
1116 // Checks for the presence of "nested returns" in a function.
1117 // Nested returns are when the inner expression of a return expression
1118 // (the 'expr' in 'return expr') contains a return expression. Only cases
1119 // where the outer return is actually reachable are considered. Implicit
1120 // returns from the end of blocks are considered as well.
1121 //
1122 // This check is needed to handle the case where the inner expression is
1123 // part of a larger expression that may have already partially-filled the
1124 // return slot alloca. This can cause errors related to clean-up due to
1125 // the clobbering of the existing value in the return slot.
1126 fn has_nested_returns(tcx: &ty::ctxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1127     for n in cfg.graph.depth_traverse(cfg.entry) {
1128         match tcx.map.find(n.id()) {
1129             Some(ast_map::NodeExpr(ex)) => {
1130                 if let ast::ExprRet(Some(ref ret_expr)) = ex.node {
1131                     let mut visitor = FindNestedReturn::new();
1132                     visit::walk_expr(&mut visitor, &**ret_expr);
1133                     if visitor.found {
1134                         return true;
1135                     }
1136                 }
1137             }
1138             Some(ast_map::NodeBlock(blk)) if blk.id == blk_id => {
1139                 let mut visitor = FindNestedReturn::new();
1140                 visit::walk_expr_opt(&mut visitor, &blk.expr);
1141                 if visitor.found {
1142                     return true;
1143                 }
1144             }
1145             _ => {}
1146         }
1147     }
1148
1149     return false;
1150 }
1151
1152 // NB: must keep 4 fns in sync:
1153 //
1154 //  - type_of_fn
1155 //  - create_datums_for_fn_args.
1156 //  - new_fn_ctxt
1157 //  - trans_args
1158 //
1159 // Be warned! You must call `init_function` before doing anything with the
1160 // returned function context.
1161 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1162                              llfndecl: ValueRef,
1163                              id: ast::NodeId,
1164                              has_env: bool,
1165                              output_type: ty::FnOutput<'tcx>,
1166                              param_substs: &'tcx Substs<'tcx>,
1167                              sp: Option<Span>,
1168                              block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1169                              -> FunctionContext<'a, 'tcx> {
1170     common::validate_substs(param_substs);
1171
1172     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1173            if id == !0 {
1174                "".to_string()
1175            } else {
1176                ccx.tcx().map.path_to_string(id).to_string()
1177            },
1178            id, param_substs.repr(ccx.tcx()));
1179
1180     let uses_outptr = match output_type {
1181         ty::FnConverging(output_type) => {
1182             let substd_output_type =
1183                 monomorphize::apply_param_substs(ccx.tcx(), param_substs, &output_type);
1184             type_of::return_uses_outptr(ccx, substd_output_type)
1185         }
1186         ty::FnDiverging => false
1187     };
1188     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1189     let (blk_id, cfg) = build_cfg(ccx.tcx(), id);
1190     let nested_returns = if let Some(ref cfg) = cfg {
1191         has_nested_returns(ccx.tcx(), cfg, blk_id)
1192     } else {
1193         false
1194     };
1195
1196     let mut fcx = FunctionContext {
1197           llfn: llfndecl,
1198           llenv: None,
1199           llretslotptr: Cell::new(None),
1200           param_env: ty::empty_parameter_environment(ccx.tcx()),
1201           alloca_insert_pt: Cell::new(None),
1202           llreturn: Cell::new(None),
1203           needs_ret_allocas: nested_returns,
1204           personality: Cell::new(None),
1205           caller_expects_out_pointer: uses_outptr,
1206           lllocals: RefCell::new(NodeMap()),
1207           llupvars: RefCell::new(NodeMap()),
1208           id: id,
1209           param_substs: param_substs,
1210           span: sp,
1211           block_arena: block_arena,
1212           ccx: ccx,
1213           debug_context: debug_context,
1214           scopes: RefCell::new(Vec::new()),
1215           cfg: cfg
1216     };
1217
1218     if has_env {
1219         fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1220     }
1221
1222     fcx
1223 }
1224
1225 /// Performs setup on a newly created function, creating the entry scope block
1226 /// and allocating space for the return pointer.
1227 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1228                                skip_retptr: bool,
1229                                output: ty::FnOutput<'tcx>)
1230                                -> Block<'a, 'tcx> {
1231     let entry_bcx = fcx.new_temp_block("entry-block");
1232
1233     // Use a dummy instruction as the insertion point for all allocas.
1234     // This is later removed in FunctionContext::cleanup.
1235     fcx.alloca_insert_pt.set(Some(unsafe {
1236         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1237         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1238     }));
1239
1240     if let ty::FnConverging(output_type) = output {
1241         // This shouldn't need to recompute the return type,
1242         // as new_fn_ctxt did it already.
1243         let substd_output_type = fcx.monomorphize(&output_type);
1244         if !return_type_is_void(fcx.ccx, substd_output_type) {
1245             // If the function returns nil/bot, there is no real return
1246             // value, so do not set `llretslotptr`.
1247             if !skip_retptr || fcx.caller_expects_out_pointer {
1248                 // Otherwise, we normally allocate the llretslotptr, unless we
1249                 // have been instructed to skip it for immediate return
1250                 // values.
1251                 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1252             }
1253         }
1254     }
1255
1256     entry_bcx
1257 }
1258
1259 // NB: must keep 4 fns in sync:
1260 //
1261 //  - type_of_fn
1262 //  - create_datums_for_fn_args.
1263 //  - new_fn_ctxt
1264 //  - trans_args
1265
1266 pub fn arg_kind<'a, 'tcx>(cx: &FunctionContext<'a, 'tcx>, t: Ty<'tcx>)
1267                           -> datum::Rvalue {
1268     use trans::datum::{ByRef, ByValue};
1269
1270     datum::Rvalue {
1271         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1272     }
1273 }
1274
1275 // work around bizarre resolve errors
1276 pub type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
1277
1278 // create_datums_for_fn_args: creates rvalue datums for each of the
1279 // incoming function arguments. These will later be stored into
1280 // appropriate lvalue datums.
1281 pub fn create_datums_for_fn_args<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1282                                            arg_tys: &[Ty<'tcx>])
1283                                            -> Vec<RvalueDatum<'tcx>> {
1284     let _icx = push_ctxt("create_datums_for_fn_args");
1285
1286     // Return an array wrapping the ValueRefs that we get from `get_param` for
1287     // each argument into datums.
1288     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1289         let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1290         datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1291     }).collect()
1292 }
1293
1294 /// Creates rvalue datums for each of the incoming function arguments and
1295 /// tuples the arguments. These will later be stored into appropriate lvalue
1296 /// datums.
1297 ///
1298 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1299 fn create_datums_for_fn_args_under_call_abi<'blk, 'tcx>(
1300         mut bcx: Block<'blk, 'tcx>,
1301         arg_scope: cleanup::CustomScopeIndex,
1302         arg_tys: &[Ty<'tcx>])
1303         -> Vec<RvalueDatum<'tcx>> {
1304     let mut result = Vec::new();
1305     for (i, &arg_ty) in arg_tys.iter().enumerate() {
1306         if i < arg_tys.len() - 1 {
1307             // Regular argument.
1308             let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1309             result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1310                                                                   arg_ty)));
1311             continue
1312         }
1313
1314         // This is the last argument. Tuple it.
1315         match arg_ty.sty {
1316             ty::ty_tup(ref tupled_arg_tys) => {
1317                 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1318                 let tuple =
1319                     unpack_datum!(bcx,
1320                                   datum::lvalue_scratch_datum(bcx,
1321                                                               arg_ty,
1322                                                               "tupled_args",
1323                                                               tuple_args_scope_id,
1324                                                               (),
1325                                                               |(),
1326                                                                mut bcx,
1327                                                                llval| {
1328                         for (j, &tupled_arg_ty) in
1329                                     tupled_arg_tys.iter().enumerate() {
1330                             let llarg =
1331                                 get_param(bcx.fcx.llfn,
1332                                           bcx.fcx.arg_pos(i + j) as c_uint);
1333                             let lldest = GEPi(bcx, llval, &[0, j]);
1334                             let datum = datum::Datum::new(
1335                                 llarg,
1336                                 tupled_arg_ty,
1337                                 arg_kind(bcx.fcx, tupled_arg_ty));
1338                             bcx = datum.store_to(bcx, lldest);
1339                         }
1340                         bcx
1341                     }));
1342                 let tuple = unpack_datum!(bcx,
1343                                           tuple.to_expr_datum()
1344                                                .to_rvalue_datum(bcx,
1345                                                                 "argtuple"));
1346                 result.push(tuple);
1347             }
1348             _ => {
1349                 bcx.tcx().sess.bug("last argument of a function with \
1350                                     `rust-call` ABI isn't a tuple?!")
1351             }
1352         };
1353
1354     }
1355
1356     result
1357 }
1358
1359 fn copy_args_to_allocas<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1360                                     arg_scope: cleanup::CustomScopeIndex,
1361                                     args: &[ast::Arg],
1362                                     arg_datums: Vec<RvalueDatum<'tcx>>)
1363                                     -> Block<'blk, 'tcx> {
1364     debug!("copy_args_to_allocas");
1365
1366     let _icx = push_ctxt("copy_args_to_allocas");
1367     let mut bcx = bcx;
1368
1369     let arg_scope_id = cleanup::CustomScope(arg_scope);
1370
1371     for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1372         // For certain mode/type combinations, the raw llarg values are passed
1373         // by value.  However, within the fn body itself, we want to always
1374         // have all locals and arguments be by-ref so that we can cancel the
1375         // cleanup and for better interaction with LLVM's debug info.  So, if
1376         // the argument would be passed by value, we store it into an alloca.
1377         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1378         // the event it's not truly needed.
1379
1380         bcx = _match::store_arg(bcx, &*args[i].pat, arg_datum, arg_scope_id);
1381         debuginfo::create_argument_metadata(bcx, &args[i]);
1382     }
1383
1384     bcx
1385 }
1386
1387 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1388 // and builds the return block.
1389 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1390                              last_bcx: Block<'blk, 'tcx>,
1391                              retty: ty::FnOutput<'tcx>,
1392                              ret_debug_loc: DebugLoc) {
1393     let _icx = push_ctxt("finish_fn");
1394
1395     let ret_cx = match fcx.llreturn.get() {
1396         Some(llreturn) => {
1397             if !last_bcx.terminated.get() {
1398                 Br(last_bcx, llreturn, DebugLoc::None);
1399             }
1400             raw_block(fcx, false, llreturn)
1401         }
1402         None => last_bcx
1403     };
1404
1405     // This shouldn't need to recompute the return type,
1406     // as new_fn_ctxt did it already.
1407     let substd_retty = fcx.monomorphize(&retty);
1408     build_return_block(fcx, ret_cx, substd_retty, ret_debug_loc);
1409
1410     debuginfo::clear_source_location(fcx);
1411     fcx.cleanup();
1412 }
1413
1414 // Builds the return block for a function.
1415 pub fn build_return_block<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1416                                       ret_cx: Block<'blk, 'tcx>,
1417                                       retty: ty::FnOutput<'tcx>,
1418                                       ret_debug_location: DebugLoc) {
1419     if fcx.llretslotptr.get().is_none() ||
1420        (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1421         return RetVoid(ret_cx, ret_debug_location);
1422     }
1423
1424     let retslot = if fcx.needs_ret_allocas {
1425         Load(ret_cx, fcx.llretslotptr.get().unwrap())
1426     } else {
1427         fcx.llretslotptr.get().unwrap()
1428     };
1429     let retptr = Value(retslot);
1430     match retptr.get_dominating_store(ret_cx) {
1431         // If there's only a single store to the ret slot, we can directly return
1432         // the value that was stored and omit the store and the alloca
1433         Some(s) => {
1434             let retval = s.get_operand(0).unwrap().get();
1435             s.erase_from_parent();
1436
1437             if retptr.has_no_uses() {
1438                 retptr.erase_from_parent();
1439             }
1440
1441             let retval = if retty == ty::FnConverging(fcx.ccx.tcx().types.bool) {
1442                 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1443             } else {
1444                 retval
1445             };
1446
1447             if fcx.caller_expects_out_pointer {
1448                 if let ty::FnConverging(retty) = retty {
1449                     store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1450                 }
1451                 RetVoid(ret_cx, ret_debug_location)
1452             } else {
1453                 Ret(ret_cx, retval, ret_debug_location)
1454             }
1455         }
1456         // Otherwise, copy the return value to the ret slot
1457         None => match retty {
1458             ty::FnConverging(retty) => {
1459                 if fcx.caller_expects_out_pointer {
1460                     memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1461                     RetVoid(ret_cx, ret_debug_location)
1462                 } else {
1463                     Ret(ret_cx, load_ty(ret_cx, retslot, retty), ret_debug_location)
1464                 }
1465             }
1466             ty::FnDiverging => {
1467                 if fcx.caller_expects_out_pointer {
1468                     RetVoid(ret_cx, ret_debug_location)
1469                 } else {
1470                     Ret(ret_cx, C_undef(Type::nil(fcx.ccx)), ret_debug_location)
1471                 }
1472             }
1473         }
1474     }
1475 }
1476
1477 /// Builds an LLVM function out of a source function.
1478 ///
1479 /// If the function closes over its environment a closure will be returned.
1480 pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1481                                    decl: &ast::FnDecl,
1482                                    body: &ast::Block,
1483                                    llfndecl: ValueRef,
1484                                    param_substs: &'tcx Substs<'tcx>,
1485                                    fn_ast_id: ast::NodeId,
1486                                    _attributes: &[ast::Attribute],
1487                                    output_type: ty::FnOutput<'tcx>,
1488                                    abi: Abi,
1489                                    closure_env: closure::ClosureEnv<'b>) {
1490     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1491
1492     let _icx = push_ctxt("trans_closure");
1493     attributes::emit_uwtable(llfndecl, true);
1494
1495     debug!("trans_closure(..., param_substs={})",
1496            param_substs.repr(ccx.tcx()));
1497
1498     let has_env = match closure_env {
1499         closure::ClosureEnv::Closure(_) => true,
1500         closure::ClosureEnv::NotClosure => false,
1501     };
1502
1503     let (arena, fcx): (TypedArena<_>, FunctionContext);
1504     arena = TypedArena::new();
1505     fcx = new_fn_ctxt(ccx,
1506                       llfndecl,
1507                       fn_ast_id,
1508                       has_env,
1509                       output_type,
1510                       param_substs,
1511                       Some(body.span),
1512                       &arena);
1513     let mut bcx = init_function(&fcx, false, output_type);
1514
1515     // cleanup scope for the incoming arguments
1516     let fn_cleanup_debug_loc =
1517         debuginfo::get_cleanup_debug_loc_for_ast_node(ccx, fn_ast_id, body.span, true);
1518     let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1519
1520     let block_ty = node_id_type(bcx, body.id);
1521
1522     // Set up arguments to the function.
1523     let monomorphized_arg_types =
1524         decl.inputs.iter()
1525                    .map(|arg| node_id_type(bcx, arg.id))
1526                    .collect::<Vec<_>>();
1527     let monomorphized_arg_types = match closure_env {
1528         closure::ClosureEnv::NotClosure => {
1529             monomorphized_arg_types
1530         }
1531
1532         // Tuple up closure argument types for the "rust-call" ABI.
1533         closure::ClosureEnv::Closure(_) => {
1534             vec![ty::mk_tup(ccx.tcx(), monomorphized_arg_types)]
1535         }
1536     };
1537     for monomorphized_arg_type in &monomorphized_arg_types {
1538         debug!("trans_closure: monomorphized_arg_type: {}",
1539                ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1540     }
1541     debug!("trans_closure: function lltype: {}",
1542            bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1543
1544     let arg_datums = match closure_env {
1545         closure::ClosureEnv::NotClosure if abi == RustCall => {
1546             create_datums_for_fn_args_under_call_abi(bcx, arg_scope, &monomorphized_arg_types[..])
1547         }
1548         _ => {
1549             let arg_tys = untuple_arguments_if_necessary(ccx, &monomorphized_arg_types, abi);
1550             create_datums_for_fn_args(&fcx, &arg_tys)
1551         }
1552     };
1553
1554     bcx = copy_args_to_allocas(bcx, arg_scope, &decl.inputs, arg_datums);
1555
1556     bcx = closure_env.load(bcx, cleanup::CustomScope(arg_scope));
1557
1558     // Up until here, IR instructions for this function have explicitly not been annotated with
1559     // source code location, so we don't step into call setup code. From here on, source location
1560     // emitting should be enabled.
1561     debuginfo::start_emitting_source_locations(&fcx);
1562
1563     let dest = match fcx.llretslotptr.get() {
1564         Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, ty::FnConverging(block_ty), "iret_slot")),
1565         None => {
1566             assert!(type_is_zero_size(bcx.ccx(), block_ty));
1567             expr::Ignore
1568         }
1569     };
1570
1571     // This call to trans_block is the place where we bridge between
1572     // translation calls that don't have a return value (trans_crate,
1573     // trans_mod, trans_item, et cetera) and those that do
1574     // (trans_block, trans_expr, et cetera).
1575     bcx = controlflow::trans_block(bcx, body, dest);
1576
1577     match dest {
1578         expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1579             Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1580         }
1581         _ => {}
1582     }
1583
1584     match fcx.llreturn.get() {
1585         Some(_) => {
1586             Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1587             fcx.pop_custom_cleanup_scope(arg_scope);
1588         }
1589         None => {
1590             // Microoptimization writ large: avoid creating a separate
1591             // llreturn basic block
1592             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1593         }
1594     };
1595
1596     // Put return block after all other blocks.
1597     // This somewhat improves single-stepping experience in debugger.
1598     unsafe {
1599         let llreturn = fcx.llreturn.get();
1600         if let Some(llreturn) = llreturn {
1601             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1602         }
1603     }
1604
1605     let ret_debug_loc = DebugLoc::At(fn_cleanup_debug_loc.id,
1606                                      fn_cleanup_debug_loc.span);
1607
1608     // Insert the mandatory first few basic blocks before lltop.
1609     finish_fn(&fcx, bcx, output_type, ret_debug_loc);
1610 }
1611
1612 /// Creates an LLVM function corresponding to a source language function.
1613 pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1614                           decl: &ast::FnDecl,
1615                           body: &ast::Block,
1616                           llfndecl: ValueRef,
1617                           param_substs: &'tcx Substs<'tcx>,
1618                           id: ast::NodeId,
1619                           attrs: &[ast::Attribute]) {
1620     let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1621     debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1622     let _icx = push_ctxt("trans_fn");
1623     let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1624     let output_type = ty::erase_late_bound_regions(ccx.tcx(), &ty::ty_fn_ret(fn_ty));
1625     let abi = ty::ty_fn_abi(fn_ty);
1626     trans_closure(ccx, decl, body, llfndecl, param_substs, id, attrs, output_type, abi,
1627                   closure::ClosureEnv::NotClosure);
1628 }
1629
1630 pub fn trans_enum_variant<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1631                                     _enum_id: ast::NodeId,
1632                                     variant: &ast::Variant,
1633                                     _args: &[ast::VariantArg],
1634                                     disr: ty::Disr,
1635                                     param_substs: &'tcx Substs<'tcx>,
1636                                     llfndecl: ValueRef) {
1637     let _icx = push_ctxt("trans_enum_variant");
1638
1639     trans_enum_variant_or_tuple_like_struct(
1640         ccx,
1641         variant.node.id,
1642         disr,
1643         param_substs,
1644         llfndecl);
1645 }
1646
1647 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1648                                                  ctor_ty: Ty<'tcx>,
1649                                                  disr: ty::Disr,
1650                                                  args: callee::CallArgs,
1651                                                  dest: expr::Dest,
1652                                                  debug_loc: DebugLoc)
1653                                                  -> Result<'blk, 'tcx> {
1654
1655     let ccx = bcx.fcx.ccx;
1656     let tcx = ccx.tcx();
1657
1658     let result_ty = match ctor_ty.sty {
1659         ty::ty_bare_fn(_, ref bft) => {
1660             ty::erase_late_bound_regions(bcx.tcx(), &bft.sig.output()).unwrap()
1661         }
1662         _ => ccx.sess().bug(
1663             &format!("trans_enum_variant_constructor: \
1664                      unexpected ctor return type {}",
1665                      ctor_ty.repr(tcx)))
1666     };
1667
1668     // Get location to store the result. If the user does not care about
1669     // the result, just make a stack slot
1670     let llresult = match dest {
1671         expr::SaveIn(d) => d,
1672         expr::Ignore => {
1673             if !type_is_zero_size(ccx, result_ty) {
1674                 alloc_ty(bcx, result_ty, "constructor_result")
1675             } else {
1676                 C_undef(type_of::type_of(ccx, result_ty))
1677             }
1678         }
1679     };
1680
1681     if !type_is_zero_size(ccx, result_ty) {
1682         match args {
1683             callee::ArgExprs(exprs) => {
1684                 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
1685                 bcx = expr::trans_adt(bcx,
1686                                       result_ty,
1687                                       disr,
1688                                       &fields[..],
1689                                       None,
1690                                       expr::SaveIn(llresult),
1691                                       debug_loc);
1692             }
1693             _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
1694         }
1695     }
1696
1697     // If the caller doesn't care about the result
1698     // drop the temporary we made
1699     let bcx = match dest {
1700         expr::SaveIn(_) => bcx,
1701         expr::Ignore => {
1702             let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
1703             if !type_is_zero_size(ccx, result_ty) {
1704                 call_lifetime_end(bcx, llresult);
1705             }
1706             bcx
1707         }
1708     };
1709
1710     Result::new(bcx, llresult)
1711 }
1712
1713 pub fn trans_tuple_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1714                                     _fields: &[ast::StructField],
1715                                     ctor_id: ast::NodeId,
1716                                     param_substs: &'tcx Substs<'tcx>,
1717                                     llfndecl: ValueRef) {
1718     let _icx = push_ctxt("trans_tuple_struct");
1719
1720     trans_enum_variant_or_tuple_like_struct(
1721         ccx,
1722         ctor_id,
1723         0,
1724         param_substs,
1725         llfndecl);
1726 }
1727
1728 fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1729                                                      ctor_id: ast::NodeId,
1730                                                      disr: ty::Disr,
1731                                                      param_substs: &'tcx Substs<'tcx>,
1732                                                      llfndecl: ValueRef) {
1733     let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1734     let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
1735
1736     let result_ty = match ctor_ty.sty {
1737         ty::ty_bare_fn(_, ref bft) => {
1738             ty::erase_late_bound_regions(ccx.tcx(), &bft.sig.output())
1739         }
1740         _ => ccx.sess().bug(
1741             &format!("trans_enum_variant_or_tuple_like_struct: \
1742                      unexpected ctor return type {}",
1743                     ty_to_string(ccx.tcx(), ctor_ty)))
1744     };
1745
1746     let (arena, fcx): (TypedArena<_>, FunctionContext);
1747     arena = TypedArena::new();
1748     fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1749                       param_substs, None, &arena);
1750     let bcx = init_function(&fcx, false, result_ty);
1751
1752     assert!(!fcx.needs_ret_allocas);
1753
1754     let arg_tys =
1755         ty::erase_late_bound_regions(
1756             ccx.tcx(), &ty::ty_fn_args(ctor_ty));
1757
1758     let arg_datums = create_datums_for_fn_args(&fcx, &arg_tys[..]);
1759
1760     if !type_is_zero_size(fcx.ccx, result_ty.unwrap()) {
1761         let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
1762         let repr = adt::represent_type(ccx, result_ty.unwrap());
1763         for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1764             let lldestptr = adt::trans_field_ptr(bcx,
1765                                                  &*repr,
1766                                                  dest,
1767                                                  disr,
1768                                                  i);
1769             arg_datum.store_to(bcx, lldestptr);
1770         }
1771         adt::trans_set_discr(bcx, &*repr, dest, disr);
1772     }
1773
1774     finish_fn(&fcx, bcx, result_ty, DebugLoc::None);
1775 }
1776
1777 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1778     let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1779
1780     let print_info = ccx.sess().print_enum_sizes();
1781
1782     let levels = ccx.tcx().node_lint_levels.borrow();
1783     let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCES);
1784     let lvlsrc = levels.get(&(id, lint_id));
1785     let is_allow = lvlsrc.map_or(true, |&(lvl, _)| lvl == lint::Allow);
1786
1787     if is_allow && !print_info {
1788         // we're not interested in anything here
1789         return
1790     }
1791
1792     let ty = ty::node_id_to_type(ccx.tcx(), id);
1793     let avar = adt::represent_type(ccx, ty);
1794     match *avar {
1795         adt::General(_, ref variants, _) => {
1796             for var in variants {
1797                 let mut size = 0;
1798                 for field in var.fields.iter().skip(1) {
1799                     // skip the discriminant
1800                     size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1801                 }
1802                 sizes.push(size);
1803             }
1804         },
1805         _ => { /* its size is either constant or unimportant */ }
1806     }
1807
1808     let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1809         |(l, s, li), (idx, &size)|
1810             if size > l {
1811                 (size, l, idx)
1812             } else if size > s {
1813                 (l, size, li)
1814             } else {
1815                 (l, s, li)
1816             }
1817     );
1818
1819     if print_info {
1820         let llty = type_of::sizing_type_of(ccx, ty);
1821
1822         let sess = &ccx.tcx().sess;
1823         sess.span_note(sp, &*format!("total size: {} bytes", llsize_of_real(ccx, llty)));
1824         match *avar {
1825             adt::General(..) => {
1826                 for (i, var) in enum_def.variants.iter().enumerate() {
1827                     ccx.tcx().sess.span_note(var.span,
1828                                              &*format!("variant data: {} bytes", sizes[i]));
1829                 }
1830             }
1831             _ => {}
1832         }
1833     }
1834
1835     // we only warn if the largest variant is at least thrice as large as
1836     // the second-largest.
1837     if !is_allow && largest > slargest * 3 && slargest > 0 {
1838         // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1839         // pass for the latter already ran.
1840         lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCES,
1841                             *lvlsrc.unwrap(), Some(sp),
1842                             &format!("enum variant is more than three times larger \
1843                                      ({} bytes) than the next largest (ignoring padding)",
1844                                     largest));
1845
1846         ccx.sess().span_note(enum_def.variants[largest_index].span,
1847                              "this variant is the largest");
1848     }
1849 }
1850
1851 pub struct TransItemVisitor<'a, 'tcx: 'a> {
1852     pub ccx: &'a CrateContext<'a, 'tcx>,
1853 }
1854
1855 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
1856     fn visit_item(&mut self, i: &ast::Item) {
1857         trans_item(self.ccx, i);
1858     }
1859 }
1860
1861 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
1862     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1863     // applicable to variable declarations and may not really make sense for
1864     // Rust code in the first place but whitelist them anyway and trust that
1865     // the user knows what s/he's doing. Who knows, unanticipated use cases
1866     // may pop up in the future.
1867     //
1868     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1869     // and don't have to be, LLVM treats them as no-ops.
1870     match name {
1871         "appending" => Some(llvm::AppendingLinkage),
1872         "available_externally" => Some(llvm::AvailableExternallyLinkage),
1873         "common" => Some(llvm::CommonLinkage),
1874         "extern_weak" => Some(llvm::ExternalWeakLinkage),
1875         "external" => Some(llvm::ExternalLinkage),
1876         "internal" => Some(llvm::InternalLinkage),
1877         "linkonce" => Some(llvm::LinkOnceAnyLinkage),
1878         "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
1879         "private" => Some(llvm::PrivateLinkage),
1880         "weak" => Some(llvm::WeakAnyLinkage),
1881         "weak_odr" => Some(llvm::WeakODRLinkage),
1882         _ => None,
1883     }
1884 }
1885
1886
1887 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
1888 #[derive(Copy, Clone)]
1889 pub enum ValueOrigin {
1890     /// The LLVM `Value` is in this context because the corresponding item was
1891     /// assigned to the current compilation unit.
1892     OriginalTranslation,
1893     /// The `Value`'s corresponding item was assigned to some other compilation
1894     /// unit, but the `Value` was translated in this context anyway because the
1895     /// item is marked `#[inline]`.
1896     InlinedCopy,
1897 }
1898
1899 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
1900 /// If the `llval` is the direct translation of a specific Rust item, `id`
1901 /// should be set to the `NodeId` of that item.  (This mapping should be
1902 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
1903 /// `None`.)  `llval_origin` indicates whether `llval` is the translation of an
1904 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
1905 /// assigned to a different compilation unit.
1906 pub fn update_linkage(ccx: &CrateContext,
1907                       llval: ValueRef,
1908                       id: Option<ast::NodeId>,
1909                       llval_origin: ValueOrigin) {
1910     match llval_origin {
1911         InlinedCopy => {
1912             // `llval` is a translation of an item defined in a separate
1913             // compilation unit.  This only makes sense if there are at least
1914             // two compilation units.
1915             assert!(ccx.sess().opts.cg.codegen_units > 1);
1916             // `llval` is a copy of something defined elsewhere, so use
1917             // `AvailableExternallyLinkage` to avoid duplicating code in the
1918             // output.
1919             llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
1920             return;
1921         },
1922         OriginalTranslation => {},
1923     }
1924
1925     if let Some(id) = id {
1926         let item = ccx.tcx().map.get(id);
1927         if let ast_map::NodeItem(i) = item {
1928             if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
1929                 if let Some(linkage) = llvm_linkage_by_name(&name) {
1930                     llvm::SetLinkage(llval, linkage);
1931                 } else {
1932                     ccx.sess().span_fatal(i.span, "invalid linkage specified");
1933                 }
1934                 return;
1935             }
1936         }
1937     }
1938
1939     match id {
1940         Some(id) if ccx.reachable().contains(&id) => {
1941             llvm::SetLinkage(llval, llvm::ExternalLinkage);
1942         },
1943         _ => {
1944             // `id` does not refer to an item in `ccx.reachable`.
1945             if ccx.sess().opts.cg.codegen_units > 1 {
1946                 llvm::SetLinkage(llval, llvm::ExternalLinkage);
1947             } else {
1948                 llvm::SetLinkage(llval, llvm::InternalLinkage);
1949             }
1950         },
1951     }
1952 }
1953
1954 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1955     let _icx = push_ctxt("trans_item");
1956
1957     let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
1958
1959     match item.node {
1960       ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1961         if !generics.is_type_parameterized() {
1962             let trans_everywhere = attr::requests_inline(&item.attrs);
1963             // Ignore `trans_everywhere` for cross-crate inlined items
1964             // (`from_external`).  `trans_item` will be called once for each
1965             // compilation unit that references the item, so it will still get
1966             // translated everywhere it's needed.
1967             for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
1968                 let llfn = get_item_val(ccx, item.id);
1969                 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
1970                 if abi != Rust {
1971                     foreign::trans_rust_fn_with_foreign_abi(ccx, &**decl, &**body, &item.attrs,
1972                                                             llfn, empty_substs, item.id, None);
1973                 } else {
1974                     trans_fn(ccx, &**decl, &**body, llfn, empty_substs, item.id, &item.attrs);
1975                 }
1976                 update_linkage(ccx, llfn, Some(item.id),
1977                                if is_origin { OriginalTranslation } else { InlinedCopy });
1978
1979                 if is_entry_fn(ccx.sess(), item.id) {
1980                     create_entry_wrapper(ccx, item.span, llfn);
1981                     // check for the #[rustc_error] annotation, which forces an
1982                     // error in trans. This is used to write compile-fail tests
1983                     // that actually test that compilation succeeds without
1984                     // reporting an error.
1985                     if ty::has_attr(ccx.tcx(), local_def(item.id), "rustc_error") {
1986                         ccx.tcx().sess.span_fatal(item.span, "compilation successful");
1987                     }
1988                 }
1989             }
1990         }
1991
1992         // Be sure to travel more than just one layer deep to catch nested
1993         // items in blocks and such.
1994         let mut v = TransItemVisitor{ ccx: ccx };
1995         v.visit_block(&**body);
1996       }
1997       ast::ItemImpl(_, _, ref generics, _, _, ref impl_items) => {
1998         meth::trans_impl(ccx,
1999                          item.ident,
2000                          &impl_items[..],
2001                          generics,
2002                          item.id);
2003       }
2004       ast::ItemMod(ref m) => {
2005         trans_mod(&ccx.rotate(), m);
2006       }
2007       ast::ItemEnum(ref enum_definition, ref gens) => {
2008         if gens.ty_params.is_empty() {
2009             // sizes only make sense for non-generic types
2010
2011             enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2012         }
2013       }
2014       ast::ItemConst(_, ref expr) => {
2015           // Recurse on the expression to catch items in blocks
2016           let mut v = TransItemVisitor{ ccx: ccx };
2017           v.visit_expr(&**expr);
2018       }
2019       ast::ItemStatic(_, m, ref expr) => {
2020           // Recurse on the expression to catch items in blocks
2021           let mut v = TransItemVisitor{ ccx: ccx };
2022           v.visit_expr(&**expr);
2023
2024           let g = consts::trans_static(ccx, m, item.id);
2025           update_linkage(ccx, g, Some(item.id), OriginalTranslation);
2026
2027           // Do static_assert checking. It can't really be done much earlier
2028           // because we need to get the value of the bool out of LLVM
2029           if attr::contains_name(&item.attrs, "static_assert") {
2030               if !ty::type_is_bool(ty::expr_ty(ccx.tcx(), expr)) {
2031                   ccx.sess().span_fatal(expr.span,
2032                                         "can only have static_assert on a static \
2033                                          with type `bool`");
2034               }
2035               if m == ast::MutMutable {
2036                   ccx.sess().span_fatal(expr.span,
2037                                         "cannot have static_assert on a mutable \
2038                                          static");
2039               }
2040
2041               let v = ccx.static_values().borrow().get(&item.id).unwrap().clone();
2042               unsafe {
2043                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2044                       ccx.sess().span_fatal(expr.span, "static assertion failed");
2045                   }
2046               }
2047           }
2048       },
2049       ast::ItemForeignMod(ref foreign_mod) => {
2050         foreign::trans_foreign_mod(ccx, foreign_mod);
2051       }
2052       ast::ItemTrait(..) => {
2053         // Inside of this trait definition, we won't be actually translating any
2054         // functions, but the trait still needs to be walked. Otherwise default
2055         // methods with items will not get translated and will cause ICE's when
2056         // metadata time comes around.
2057         let mut v = TransItemVisitor{ ccx: ccx };
2058         visit::walk_item(&mut v, item);
2059       }
2060       _ => {/* fall through */ }
2061     }
2062 }
2063
2064 // Translate a module. Doing this amounts to translating the items in the
2065 // module; there ends up being no artifact (aside from linkage names) of
2066 // separate modules in the compiled program.  That's because modules exist
2067 // only as a convenience for humans working with the code, to organize names
2068 // and control visibility.
2069 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2070     let _icx = push_ctxt("trans_mod");
2071     for item in &m.items {
2072         trans_item(ccx, &**item);
2073     }
2074 }
2075
2076
2077 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2078 pub fn register_fn_llvmty(ccx: &CrateContext,
2079                           sp: Span,
2080                           sym: String,
2081                           node_id: ast::NodeId,
2082                       cc: llvm::CallConv,
2083                           llfty: Type) -> ValueRef {
2084     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2085
2086     let llfn = declare::define_fn(ccx, &sym[..], cc, llfty,
2087                                    ty::FnConverging(ty::mk_nil(ccx.tcx()))).unwrap_or_else(||{
2088         ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2089     });
2090     finish_register_fn(ccx, sym, node_id, llfn);
2091     llfn
2092 }
2093
2094 fn finish_register_fn(ccx: &CrateContext, sym: String, node_id: ast::NodeId,
2095                       llfn: ValueRef) {
2096     ccx.item_symbols().borrow_mut().insert(node_id, sym);
2097
2098     // The stack exhaustion lang item shouldn't have a split stack because
2099     // otherwise it would continue to be exhausted (bad), and both it and the
2100     // eh_personality functions need to be externally linkable.
2101     let def = ast_util::local_def(node_id);
2102     if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2103         attributes::split_stack(llfn, false);
2104         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2105     }
2106     if ccx.tcx().lang_items.eh_personality() == Some(def) {
2107         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2108     }
2109 }
2110
2111 fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2112                          sp: Span,
2113                          sym: String,
2114                          node_id: ast::NodeId,
2115                          node_type: Ty<'tcx>)
2116                          -> ValueRef {
2117     if let ty::ty_bare_fn(_, ref f) = node_type.sty {
2118         if f.abi != Rust && f.abi != RustCall {
2119             ccx.sess().span_bug(sp, &format!("only the `{}` or `{}` calling conventions are valid \
2120                                               for this function; `{}` was specified",
2121                                               Rust.name(), RustCall.name(), f.abi.name()));
2122         }
2123     } else {
2124         ccx.sess().span_bug(sp, "expected bare rust function")
2125     }
2126
2127     let llfn = declare::define_rust_fn(ccx, &sym[..], node_type).unwrap_or_else(||{
2128         ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2129     });
2130     finish_register_fn(ccx, sym, node_id, llfn);
2131     llfn
2132 }
2133
2134 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2135     match *sess.entry_fn.borrow() {
2136         Some((entry_id, _)) => node_id == entry_id,
2137         None => false
2138     }
2139 }
2140
2141 /// Create the `main` function which will initialise the rust runtime and call users’ main
2142 /// function.
2143 pub fn create_entry_wrapper(ccx: &CrateContext,
2144                            sp: Span,
2145                            main_llfn: ValueRef) {
2146     let et = ccx.sess().entry_type.get().unwrap();
2147     match et {
2148         config::EntryMain => {
2149             create_entry_fn(ccx, sp, main_llfn, true);
2150         }
2151         config::EntryStart => create_entry_fn(ccx, sp, main_llfn, false),
2152         config::EntryNone => {}    // Do nothing.
2153     }
2154
2155     fn create_entry_fn(ccx: &CrateContext,
2156                        sp: Span,
2157                        rust_main: ValueRef,
2158                        use_start_lang_item: bool) {
2159         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()],
2160                                &ccx.int_type());
2161
2162         let llfn = declare::define_cfn(ccx, "main", llfty,
2163                                        ty::mk_nil(ccx.tcx())).unwrap_or_else(||{
2164             ccx.sess().span_err(sp, "entry symbol `main` defined multiple times");
2165             // FIXME: We should be smart and show a better diagnostic here.
2166             ccx.sess().help("did you use #[no_mangle] on `fn main`? Use #[start] instead");
2167             ccx.sess().abort_if_errors();
2168             panic!();
2169         });
2170
2171         // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2172         // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2173         if ccx.sess().target.target.options.is_like_windows {
2174             unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2175         }
2176
2177         let llbb = unsafe {
2178             llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn,
2179                                                 "top\0".as_ptr() as *const _)
2180         };
2181         let bld = ccx.raw_builder();
2182         unsafe {
2183             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2184
2185             debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2186
2187             let (start_fn, args) = if use_start_lang_item {
2188                 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2189                     Ok(id) => id,
2190                     Err(s) => { ccx.sess().fatal(&s[..]); }
2191                 };
2192                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2193                     get_item_val(ccx, start_def_id.node)
2194                 } else {
2195                     let start_fn_type = csearch::get_type(ccx.tcx(),
2196                                                           start_def_id).ty;
2197                     trans_external_path(ccx, start_def_id, start_fn_type)
2198                 };
2199
2200                 let args = {
2201                     let opaque_rust_main = llvm::LLVMBuildPointerCast(bld,
2202                         rust_main, Type::i8p(ccx).to_ref(),
2203                         "rust_main\0".as_ptr() as *const _);
2204
2205                     vec!(
2206                         opaque_rust_main,
2207                         get_param(llfn, 0),
2208                         get_param(llfn, 1)
2209                      )
2210                 };
2211                 (start_fn, args)
2212             } else {
2213                 debug!("using user-defined start fn");
2214                 let args = vec!(
2215                     get_param(llfn, 0 as c_uint),
2216                     get_param(llfn, 1 as c_uint)
2217                 );
2218
2219                 (rust_main, args)
2220             };
2221
2222             let result = llvm::LLVMBuildCall(bld,
2223                                              start_fn,
2224                                              args.as_ptr(),
2225                                              args.len() as c_uint,
2226                                              noname());
2227
2228             llvm::LLVMBuildRet(bld, result);
2229         }
2230     }
2231 }
2232
2233 fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, id: ast::NodeId,
2234                            ty: Ty<'tcx>, attrs: &[ast::Attribute]) -> String {
2235     match ccx.external_srcs().borrow().get(&id) {
2236         Some(&did) => {
2237             let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2238             debug!("found item {} in other crate...", sym);
2239             return sym;
2240         }
2241         None => {}
2242     }
2243
2244     match attr::find_export_name_attr(ccx.sess().diagnostic(), attrs) {
2245         // Use provided name
2246         Some(name) => name.to_string(),
2247         _ => ccx.tcx().map.with_path(id, |path| {
2248             if attr::contains_name(attrs, "no_mangle") {
2249                 // Don't mangle
2250                 path.last().unwrap().to_string()
2251             } else {
2252                 match weak_lang_items::link_name(attrs) {
2253                     Some(name) => name.to_string(),
2254                     None => {
2255                         // Usual name mangling
2256                         mangle_exported_name(ccx, path, ty, id)
2257                     }
2258                 }
2259             }
2260         })
2261     }
2262 }
2263
2264 fn contains_null(s: &str) -> bool {
2265     s.bytes().any(|b| b == 0)
2266 }
2267
2268 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2269     debug!("get_item_val(id=`{}`)", id);
2270
2271     match ccx.item_vals().borrow().get(&id).cloned() {
2272         Some(v) => return v,
2273         None => {}
2274     }
2275
2276     let item = ccx.tcx().map.get(id);
2277     debug!("get_item_val: id={} item={:?}", id, item);
2278     let val = match item {
2279         ast_map::NodeItem(i) => {
2280             let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2281             let sym = || exported_name(ccx, id, ty, &i.attrs);
2282
2283             let v = match i.node {
2284                 ast::ItemStatic(_, _, ref expr) => {
2285                     // If this static came from an external crate, then
2286                     // we need to get the symbol from csearch instead of
2287                     // using the current crate's name/version
2288                     // information in the hash of the symbol
2289                     let sym = sym();
2290                     debug!("making {}", sym);
2291
2292                     // We need the translated value here, because for enums the
2293                     // LLVM type is not fully determined by the Rust type.
2294                     let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2295                     let (v, ty) = consts::const_expr(ccx, &**expr, empty_substs);
2296                     ccx.static_values().borrow_mut().insert(id, v);
2297                     unsafe {
2298                         // boolean SSA values are i1, but they have to be stored in i8 slots,
2299                         // otherwise some LLVM optimization passes don't work as expected
2300                         let llty = if ty::type_is_bool(ty) {
2301                             llvm::LLVMInt8TypeInContext(ccx.llcx())
2302                         } else {
2303                             llvm::LLVMTypeOf(v)
2304                         };
2305
2306                         // FIXME(nagisa): probably should be declare_global, because no definition
2307                         // is happening here, but we depend on it being defined here from
2308                         // const::trans_static. This all logic should be replaced.
2309                         let g = declare::define_global(ccx, &sym[..],
2310                                                        Type::from_ref(llty)).unwrap_or_else(||{
2311                             ccx.sess().span_fatal(i.span, &format!("symbol `{}` is already defined",
2312                                                                    sym))
2313                         });
2314
2315                         if attr::contains_name(&i.attrs,
2316                                                "thread_local") {
2317                             llvm::set_thread_local(g, true);
2318                         }
2319                         ccx.item_symbols().borrow_mut().insert(i.id, sym);
2320                         g
2321                     }
2322                 }
2323
2324                 ast::ItemFn(_, _, abi, _, _) => {
2325                     let sym = sym();
2326                     let llfn = if abi == Rust {
2327                         register_fn(ccx, i.span, sym, i.id, ty)
2328                     } else {
2329                         foreign::register_rust_fn_with_foreign_abi(ccx, i.span, sym, i.id)
2330                     };
2331                     attributes::from_fn_attrs(ccx, &i.attrs, llfn);
2332                     llfn
2333                 }
2334
2335                 _ => ccx.sess().bug("get_item_val: weird result in table")
2336             };
2337
2338             match attr::first_attr_value_str_by_name(&i.attrs,
2339                                                      "link_section") {
2340                 Some(sect) => {
2341                     if contains_null(&sect) {
2342                         ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`",
2343                                                  &sect));
2344                     }
2345                     unsafe {
2346                         let buf = CString::new(sect.as_bytes()).unwrap();
2347                         llvm::LLVMSetSection(v, buf.as_ptr());
2348                     }
2349                 },
2350                 None => ()
2351             }
2352
2353             v
2354         }
2355
2356         ast_map::NodeTraitItem(trait_item) => {
2357             debug!("get_item_val(): processing a NodeTraitItem");
2358             match trait_item.node {
2359                 ast::MethodTraitItem(_, Some(_)) => {
2360                     register_method(ccx, id, &trait_item.attrs, trait_item.span)
2361                 }
2362                 _ => {
2363                     ccx.sess().span_bug(trait_item.span,
2364                         "unexpected variant: trait item other than a provided \
2365                          method in get_item_val()");
2366                 }
2367             }
2368         }
2369
2370         ast_map::NodeImplItem(impl_item) => {
2371             match impl_item.node {
2372                 ast::MethodImplItem(..) => {
2373                     register_method(ccx, id, &impl_item.attrs, impl_item.span)
2374                 }
2375                 _ => {
2376                     ccx.sess().span_bug(impl_item.span,
2377                         "unexpected variant: non-method impl item in \
2378                          get_item_val()");
2379                 }
2380             }
2381         }
2382
2383         ast_map::NodeForeignItem(ni) => {
2384             match ni.node {
2385                 ast::ForeignItemFn(..) => {
2386                     let abi = ccx.tcx().map.get_foreign_abi(id);
2387                     let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2388                     let name = foreign::link_name(&*ni);
2389                     let llfn = foreign::register_foreign_item_fn(ccx, abi, ty, &name);
2390                     attributes::from_fn_attrs(ccx, &ni.attrs, llfn);
2391                     llfn
2392                 }
2393                 ast::ForeignItemStatic(..) => {
2394                     foreign::register_static(ccx, &*ni)
2395                 }
2396             }
2397         }
2398
2399         ast_map::NodeVariant(ref v) => {
2400             let llfn;
2401             let args = match v.node.kind {
2402                 ast::TupleVariantKind(ref args) => args,
2403                 ast::StructVariantKind(_) => {
2404                     ccx.sess().bug("struct variant kind unexpected in get_item_val")
2405                 }
2406             };
2407             assert!(!args.is_empty());
2408             let ty = ty::node_id_to_type(ccx.tcx(), id);
2409             let parent = ccx.tcx().map.get_parent(id);
2410             let enm = ccx.tcx().map.expect_item(parent);
2411             let sym = exported_name(ccx,
2412                                     id,
2413                                     ty,
2414                                     &enm.attrs);
2415
2416             llfn = match enm.node {
2417                 ast::ItemEnum(_, _) => {
2418                     register_fn(ccx, (*v).span, sym, id, ty)
2419                 }
2420                 _ => ccx.sess().bug("NodeVariant, shouldn't happen")
2421             };
2422             attributes::inline(llfn, attributes::InlineAttr::Hint);
2423             llfn
2424         }
2425
2426         ast_map::NodeStructCtor(struct_def) => {
2427             // Only register the constructor if this is a tuple-like struct.
2428             let ctor_id = match struct_def.ctor_id {
2429                 None => {
2430                     ccx.sess().bug("attempt to register a constructor of \
2431                                     a non-tuple-like struct")
2432                 }
2433                 Some(ctor_id) => ctor_id,
2434             };
2435             let parent = ccx.tcx().map.get_parent(id);
2436             let struct_item = ccx.tcx().map.expect_item(parent);
2437             let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2438             let sym = exported_name(ccx,
2439                                     id,
2440                                     ty,
2441                                     &struct_item.attrs);
2442             let llfn = register_fn(ccx, struct_item.span,
2443                                    sym, ctor_id, ty);
2444             attributes::inline(llfn, attributes::InlineAttr::Hint);
2445             llfn
2446         }
2447
2448         ref variant => {
2449             ccx.sess().bug(&format!("get_item_val(): unexpected variant: {:?}",
2450                                    variant))
2451         }
2452     };
2453
2454     // All LLVM globals and functions are initially created as external-linkage
2455     // declarations.  If `trans_item`/`trans_fn` later turns the declaration
2456     // into a definition, it adjusts the linkage then (using `update_linkage`).
2457     //
2458     // The exception is foreign items, which have their linkage set inside the
2459     // call to `foreign::register_*` above.  We don't touch the linkage after
2460     // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2461     // other item translation functions do).
2462
2463     ccx.item_vals().borrow_mut().insert(id, val);
2464     val
2465 }
2466
2467 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2468                    attrs: &[ast::Attribute], span: Span) -> ValueRef {
2469     let mty = ty::node_id_to_type(ccx.tcx(), id);
2470
2471     let sym = exported_name(ccx, id, mty, &attrs);
2472
2473     if let ty::ty_bare_fn(_, ref f) = mty.sty {
2474         let llfn = if f.abi == Rust || f.abi == RustCall {
2475             register_fn(ccx, span, sym, id, mty)
2476         } else {
2477             foreign::register_rust_fn_with_foreign_abi(ccx, span, sym, id)
2478         };
2479         attributes::from_fn_attrs(ccx, &attrs, llfn);
2480         return llfn;
2481     } else {
2482         ccx.sess().span_bug(span, "expected bare rust function");
2483     }
2484 }
2485
2486 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2487                                             ie: encoder::EncodeInlinedItem<'a>)
2488                                             -> encoder::EncodeParams<'a, 'tcx> {
2489     encoder::EncodeParams {
2490         diag: cx.sess().diagnostic(),
2491         tcx: cx.tcx(),
2492         reexports: cx.export_map(),
2493         item_symbols: cx.item_symbols(),
2494         link_meta: cx.link_meta(),
2495         cstore: &cx.sess().cstore,
2496         encode_inlined_item: ie,
2497         reachable: cx.reachable(),
2498     }
2499 }
2500
2501 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2502     use flate;
2503
2504     let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2505         *ty != config::CrateTypeExecutable
2506     });
2507     if !any_library {
2508         return Vec::new()
2509     }
2510
2511     let encode_inlined_item: encoder::EncodeInlinedItem =
2512         Box::new(|ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii));
2513
2514     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2515     let metadata = encoder::encode_metadata(encode_parms, krate);
2516     let mut compressed = encoder::metadata_encoding_version.to_vec();
2517     compressed.push_all(&flate::deflate_bytes(&metadata));
2518     let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2519     let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2520     let name = format!("rust_metadata_{}_{}",
2521                        cx.link_meta().crate_name,
2522                        cx.link_meta().crate_hash);
2523     let buf = CString::new(name).unwrap();
2524     let llglobal = unsafe {
2525         llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(),
2526                             buf.as_ptr())
2527     };
2528     unsafe {
2529         llvm::LLVMSetInitializer(llglobal, llconst);
2530         let name = loader::meta_section_name(cx.sess().target.target.options.is_like_osx);
2531         let name = CString::new(name).unwrap();
2532         llvm::LLVMSetSection(llglobal, name.as_ptr())
2533     }
2534     return metadata;
2535 }
2536
2537 /// Find any symbols that are defined in one compilation unit, but not declared
2538 /// in any other compilation unit.  Give these symbols internal linkage.
2539 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
2540     unsafe {
2541         let mut declared = HashSet::new();
2542
2543         let iter_globals = |llmod| {
2544             ValueIter {
2545                 cur: llvm::LLVMGetFirstGlobal(llmod),
2546                 step: llvm::LLVMGetNextGlobal,
2547             }
2548         };
2549
2550         let iter_functions = |llmod| {
2551             ValueIter {
2552                 cur: llvm::LLVMGetFirstFunction(llmod),
2553                 step: llvm::LLVMGetNextFunction,
2554             }
2555         };
2556
2557         // Collect all external declarations in all compilation units.
2558         for ccx in cx.iter() {
2559             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2560                 let linkage = llvm::LLVMGetLinkage(val);
2561                 // We only care about external declarations (not definitions)
2562                 // and available_externally definitions.
2563                 if !(linkage == llvm::ExternalLinkage as c_uint &&
2564                      llvm::LLVMIsDeclaration(val) != 0) &&
2565                    !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2566                     continue
2567                 }
2568
2569                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2570                                 .to_bytes().to_vec();
2571                 declared.insert(name);
2572             }
2573         }
2574
2575         // Examine each external definition.  If the definition is not used in
2576         // any other compilation unit, and is not reachable from other crates,
2577         // then give it internal linkage.
2578         for ccx in cx.iter() {
2579             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2580                 // We only care about external definitions.
2581                 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
2582                      llvm::LLVMIsDeclaration(val) == 0) {
2583                     continue
2584                 }
2585
2586                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2587                                 .to_bytes().to_vec();
2588                 if !declared.contains(&name) &&
2589                    !reachable.contains(str::from_utf8(&name).unwrap()) {
2590                     llvm::SetLinkage(val, llvm::InternalLinkage);
2591                 }
2592             }
2593         }
2594     }
2595
2596
2597     struct ValueIter {
2598         cur: ValueRef,
2599         step: unsafe extern "C" fn(ValueRef) -> ValueRef,
2600     }
2601
2602     impl Iterator for ValueIter {
2603         type Item = ValueRef;
2604
2605         fn next(&mut self) -> Option<ValueRef> {
2606             let old = self.cur;
2607             if !old.is_null() {
2608                 self.cur = unsafe {
2609                     let step: unsafe extern "C" fn(ValueRef) -> ValueRef =
2610                         mem::transmute_copy(&self.step);
2611                     step(old)
2612                 };
2613                 Some(old)
2614             } else {
2615                 None
2616             }
2617         }
2618     }
2619 }
2620
2621 pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
2622                          -> (ty::ctxt<'tcx>, CrateTranslation) {
2623     let ty::CrateAnalysis { ty_cx: tcx, export_map, reachable, name, .. } = analysis;
2624     let krate = tcx.map.krate();
2625
2626     let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
2627         v
2628     } else {
2629         tcx.sess.opts.debug_assertions
2630     };
2631
2632     let check_dropflag = if let Some(v) = tcx.sess.opts.debugging_opts.force_dropflag_checks {
2633         v
2634     } else {
2635         tcx.sess.opts.debug_assertions
2636     };
2637
2638     // Before we touch LLVM, make sure that multithreading is enabled.
2639     unsafe {
2640         use std::sync::{Once, ONCE_INIT};
2641         static INIT: Once = ONCE_INIT;
2642         static mut POISONED: bool = false;
2643         INIT.call_once(|| {
2644             if llvm::LLVMStartMultithreaded() != 1 {
2645                 // use an extra bool to make sure that all future usage of LLVM
2646                 // cannot proceed despite the Once not running more than once.
2647                 POISONED = true;
2648             }
2649         });
2650
2651         if POISONED {
2652             tcx.sess.bug("couldn't enable multi-threaded LLVM");
2653         }
2654     }
2655
2656     let link_meta = link::build_link_meta(&tcx.sess, krate, name);
2657
2658     let codegen_units = tcx.sess.opts.cg.codegen_units;
2659     let shared_ccx = SharedCrateContext::new(&link_meta.crate_name,
2660                                              codegen_units,
2661                                              tcx,
2662                                              export_map,
2663                                              Sha256::new(),
2664                                              link_meta.clone(),
2665                                              reachable,
2666                                              check_overflow,
2667                                              check_dropflag);
2668
2669     {
2670         let ccx = shared_ccx.get_ccx(0);
2671
2672         // First, verify intrinsics.
2673         intrinsic::check_intrinsics(&ccx);
2674
2675         // Next, translate the module.
2676         {
2677             let _icx = push_ctxt("text");
2678             trans_mod(&ccx, &krate.module);
2679         }
2680     }
2681
2682     for ccx in shared_ccx.iter() {
2683         if ccx.sess().opts.debuginfo != NoDebugInfo {
2684             debuginfo::finalize(&ccx);
2685         }
2686     }
2687
2688     // Translate the metadata.
2689     let metadata = write_metadata(&shared_ccx, krate);
2690
2691     if shared_ccx.sess().trans_stats() {
2692         let stats = shared_ccx.stats();
2693         println!("--- trans stats ---");
2694         println!("n_glues_created: {}", stats.n_glues_created.get());
2695         println!("n_null_glues: {}", stats.n_null_glues.get());
2696         println!("n_real_glues: {}", stats.n_real_glues.get());
2697
2698         println!("n_fns: {}", stats.n_fns.get());
2699         println!("n_monos: {}", stats.n_monos.get());
2700         println!("n_inlines: {}", stats.n_inlines.get());
2701         println!("n_closures: {}", stats.n_closures.get());
2702         println!("fn stats:");
2703         stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
2704             insns_b.cmp(&insns_a)
2705         });
2706         for tuple in &*stats.fn_stats.borrow() {
2707             match *tuple {
2708                 (ref name, insns) => {
2709                     println!("{} insns, {}", insns, *name);
2710                 }
2711             }
2712         }
2713     }
2714     if shared_ccx.sess().count_llvm_insns() {
2715         for (k, v) in &*shared_ccx.stats().llvm_insns.borrow() {
2716             println!("{:7} {}", *v, *k);
2717         }
2718     }
2719
2720     let modules = shared_ccx.iter()
2721         .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
2722         .collect();
2723
2724     let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
2725         shared_ccx.item_symbols().borrow().get(id).map(|s| s.to_string())
2726     }).collect();
2727
2728     // For the purposes of LTO, we add to the reachable set all of the upstream
2729     // reachable extern fns. These functions are all part of the public ABI of
2730     // the final product, so LTO needs to preserve them.
2731     shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
2732         let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
2733         reachable.extend(syms.into_iter().map(|did| {
2734             csearch::get_symbol(&shared_ccx.sess().cstore, did)
2735         }));
2736     });
2737
2738     // Make sure that some other crucial symbols are not eliminated from the
2739     // module. This includes the main function, the crate map (used for debug
2740     // log settings and I/O), and finally the curious rust_stack_exhausted
2741     // symbol. This symbol is required for use by the libmorestack library that
2742     // we link in, so we must ensure that this symbol is not internalized (if
2743     // defined in the crate).
2744     reachable.push("main".to_string());
2745     reachable.push("rust_stack_exhausted".to_string());
2746
2747     // referenced from .eh_frame section on some platforms
2748     reachable.push("rust_eh_personality".to_string());
2749     // referenced from rt/rust_try.ll
2750     reachable.push("rust_eh_personality_catch".to_string());
2751
2752     if codegen_units > 1 {
2753         internalize_symbols(&shared_ccx, &reachable.iter().cloned().collect());
2754     }
2755
2756     let metadata_module = ModuleTranslation {
2757         llcx: shared_ccx.metadata_llcx(),
2758         llmod: shared_ccx.metadata_llmod(),
2759     };
2760     let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
2761     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
2762
2763     let translation = CrateTranslation {
2764         modules: modules,
2765         metadata_module: metadata_module,
2766         link: link_meta,
2767         metadata: metadata,
2768         reachable: reachable,
2769         crate_formats: formats,
2770         no_builtins: no_builtins,
2771     };
2772
2773     (shared_ccx.take_tcx(), translation)
2774 }