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