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