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