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