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