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