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