]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
5f063bb31ca5ae6b8430a17ed8d934c92d9c0274
[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::session;
31 use driver::session::{Session, NoDebugInfo, FullDebugInfo};
32 use driver::driver::OutputFilenames;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
34 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
35 use lib::llvm::{llvm, Vector};
36 use lib;
37 use metadata::{csearch, encoder};
38 use middle::astencode;
39 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::build::*;
43 use middle::trans::builder::{Builder, noname};
44 use middle::trans::callee;
45 use middle::trans::cleanup;
46 use middle::trans::cleanup::CleanupMethods;
47 use middle::trans::common::*;
48 use middle::trans::consts;
49 use middle::trans::controlflow;
50 use middle::trans::datum;
51 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
52 use middle::trans::debuginfo;
53 use middle::trans::expr;
54 use middle::trans::foreign;
55 use middle::trans::glue;
56 use middle::trans::inline;
57 use middle::trans::machine;
58 use middle::trans::machine::{llalign_of_min, llsize_of};
59 use middle::trans::meth;
60 use middle::trans::monomorphize;
61 use middle::trans::tvec;
62 use middle::trans::type_::Type;
63 use middle::trans::type_of;
64 use middle::trans::type_of::*;
65 use middle::trans::value::Value;
66 use middle::ty;
67 use middle::typeck;
68 use util::common::indenter;
69 use util::ppaux::{Repr, ty_to_str};
70 use util::sha2::Sha256;
71 use util::nodemap::NodeMap;
72
73 use arena::TypedArena;
74 use libc::c_uint;
75 use std::c_str::ToCStr;
76 use std::cell::{Cell, RefCell};
77 use std::local_data;
78 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
79 use syntax::ast_util::{local_def, is_local};
80 use syntax::attr::AttrMetaMethods;
81 use syntax::attr;
82 use syntax::codemap::Span;
83 use syntax::parse::token::InternedString;
84 use syntax::visit::Visitor;
85 use syntax::visit;
86 use syntax::{ast, ast_util, ast_map};
87
88 use time;
89
90 local_data_key!(task_local_insn_key: Vec<&'static str> )
91
92 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
93     local_data::get(task_local_insn_key, |c| {
94         match c {
95             Some(ctx) => blk(ctx.as_slice()),
96             None => ()
97         }
98     })
99 }
100
101 pub fn init_insn_ctxt() {
102     local_data::set(task_local_insn_key, Vec::new());
103 }
104
105 pub struct _InsnCtxt { _x: () }
106
107 #[unsafe_destructor]
108 impl Drop for _InsnCtxt {
109     fn drop(&mut self) {
110         local_data::modify(task_local_insn_key, |c| {
111             c.map(|mut ctx| {
112                 ctx.pop();
113                 ctx
114             })
115         })
116     }
117 }
118
119 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
120     debug!("new InsnCtxt: {}", s);
121     local_data::modify(task_local_insn_key, |c| {
122         c.map(|mut ctx| {
123             ctx.push(s);
124             ctx
125         })
126     });
127     _InsnCtxt { _x: () }
128 }
129
130 pub struct StatRecorder<'a> {
131     ccx: &'a CrateContext,
132     name: Option<~str>,
133     start: u64,
134     istart: uint,
135 }
136
137 impl<'a> StatRecorder<'a> {
138     pub fn new(ccx: &'a CrateContext, name: ~str) -> StatRecorder<'a> {
139         let start = if ccx.sess().trans_stats() {
140             time::precise_time_ns()
141         } else {
142             0
143         };
144         let istart = ccx.stats.n_llvm_insns.get();
145         StatRecorder {
146             ccx: ccx,
147             name: Some(name),
148             start: start,
149             istart: istart,
150         }
151     }
152 }
153
154 #[unsafe_destructor]
155 impl<'a> Drop for StatRecorder<'a> {
156     fn drop(&mut self) {
157         if self.ccx.sess().trans_stats() {
158             let end = time::precise_time_ns();
159             let elapsed = ((end - self.start) / 1_000_000) as uint;
160             let iend = self.ccx.stats.n_llvm_insns.get();
161             self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
162                                                        elapsed,
163                                                        iend - self.istart));
164             self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
165             // Reset LLVM insn count to avoid compound costs.
166             self.ccx.stats.n_llvm_insns.set(self.istart);
167         }
168     }
169 }
170
171 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
172 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
173            ty: Type, output: ty::t) -> ValueRef {
174     let llfn: ValueRef = name.with_c_str(|buf| {
175         unsafe {
176             llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
177         }
178     });
179
180     match ty::get(output).sty {
181         // functions returning bottom may unwind, but can never return normally
182         ty::ty_bot => {
183             unsafe {
184                 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
185             }
186         }
187         // `~` pointer return values never alias because ownership is transferred
188         // FIXME #6750 ~Trait cannot be directly marked as
189         // noalias because the actual object pointer is nested.
190         ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
191         ty::ty_vec(_, ty::VstoreUniq) | ty::ty_str(ty::VstoreUniq) => {
192             unsafe {
193                 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
194             }
195         }
196         _ => {}
197     }
198
199     lib::llvm::SetFunctionCallConv(llfn, cc);
200     // Function addresses in Rust are never significant, allowing functions to be merged.
201     lib::llvm::SetUnnamedAddr(llfn, true);
202
203     llfn
204 }
205
206 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
207 pub fn decl_cdecl_fn(llmod: ModuleRef,
208                      name: &str,
209                      ty: Type,
210                      output: ty::t) -> ValueRef {
211     decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
212 }
213
214 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
215 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef,
216                      name: &str, cc: lib::llvm::CallConv,
217                      ty: Type, output: ty::t) -> ValueRef {
218     match externs.find_equiv(&name) {
219         Some(n) => return *n,
220         None => {}
221     }
222     let f = decl_fn(llmod, name, cc, ty, output);
223     externs.insert(name.to_owned(), f);
224     f
225 }
226
227 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
228                       name: &str, did: ast::DefId) -> ValueRef {
229     match ccx.externs.borrow().find_equiv(&name) {
230         Some(n) => return *n,
231         None => ()
232     }
233
234     let f = decl_rust_fn(ccx, false, inputs, output, name);
235     csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| {
236         set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).collect::<~[_]>(), f)
237     });
238
239     ccx.externs.borrow_mut().insert(name.to_owned(), f);
240     f
241 }
242
243 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
244                     inputs: &[ty::t], output: ty::t,
245                     name: &str) -> ValueRef {
246     use middle::ty::{BrAnon, ReLateBound};
247
248     let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
249     let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
250
251     let uses_outptr = type_of::return_uses_outptr(ccx, output);
252     let offset = if uses_outptr { 1 } else { 0 };
253     let offset = if has_env { offset + 1 } else { offset };
254
255     for (i, &arg_ty) in inputs.iter().enumerate() {
256         let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
257         match ty::get(arg_ty).sty {
258             // `~` pointer parameters never alias because ownership is transferred
259             // FIXME #6750 ~Trait cannot be directly marked as
260             // noalias because the actual object pointer is nested.
261             ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
262             ty::ty_vec(_, ty::VstoreUniq) | ty::ty_str(ty::VstoreUniq) |
263             ty::ty_closure(~ty::ClosureTy {store: ty::UniqTraitStore, ..}) => {
264                 unsafe {
265                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
266                 }
267             },
268             // When a reference in an argument has no named lifetime, it's
269             // impossible for that reference to escape this function(ie, be
270             // returned).
271             ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
272                 debug!("marking argument of {} as nocapture because of anonymous lifetime", name);
273                 unsafe {
274                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
275                 }
276             },
277             _ => {
278                 // For non-immediate arguments the callee gets its own copy of
279                 // the value on the stack, so there are no aliases
280                 if !type_is_immediate(ccx, arg_ty) {
281                     unsafe {
282                         llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
283                         llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
284                     }
285                 }
286             }
287         }
288     }
289
290     // The out pointer will never alias with any other pointers, as the object only exists at a
291     // language level after the call. It can also be tagged with SRet to indicate that it is
292     // guaranteed to point to a usable block of memory for the type.
293     if uses_outptr {
294         unsafe {
295             let outptr = llvm::LLVMGetParam(llfn, 0);
296             llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
297             llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
298         }
299     }
300
301     llfn
302 }
303
304 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
305                              inputs: &[ty::t], output: ty::t,
306                              name: &str) -> ValueRef {
307     let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
308     lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
309     llfn
310 }
311
312 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
313                         name: &str, ty: Type) -> ValueRef {
314     match externs.find_equiv(&name) {
315         Some(n) => return *n,
316         None => ()
317     }
318     unsafe {
319         let c = name.with_c_str(|buf| {
320             llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
321         });
322         externs.insert(name.to_owned(), c);
323         return c;
324     }
325 }
326
327 // Returns a pointer to the body for the box. The box may be an opaque
328 // box. The result will be casted to the type of body_t, if it is statically
329 // known.
330 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
331     let _icx = push_ctxt("at_box_body");
332     let ccx = bcx.ccx();
333     let ty = Type::at_box(ccx, type_of(ccx, body_t));
334     let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
335     GEPi(bcx, boxptr, [0u, abi::box_field_body])
336 }
337
338 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
339     match bcx.tcx().lang_items.require(it) {
340         Ok(id) => id,
341         Err(s) => {
342             bcx.sess().fatal(format!("allocation of `{}` {}",
343                                      bcx.ty_to_str(info_ty), s));
344         }
345     }
346 }
347
348 // The following malloc_raw_dyn* functions allocate a box to contain
349 // a given type, but with a potentially dynamic size.
350
351 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
352                           ptr_ty: ty::t,
353                           size: ValueRef)
354                           -> Result<'a> {
355     let _icx = push_ctxt("malloc_raw_exchange");
356     let ccx = bcx.ccx();
357
358     // Allocate space:
359     let r = callee::trans_lang_call(bcx,
360         require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
361         [size],
362         None);
363
364     let llty_ptr = type_of::type_of(ccx, ptr_ty);
365     rslt(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
366 }
367
368 pub fn malloc_raw_dyn_managed<'a>(
369                       bcx: &'a Block<'a>,
370                       t: ty::t,
371                       alloc_fn: LangItem,
372                       size: ValueRef)
373                       -> Result<'a> {
374     let _icx = push_ctxt("malloc_raw_managed");
375     let ccx = bcx.ccx();
376
377     let langcall = require_alloc_fn(bcx, t, alloc_fn);
378
379     // Grab the TypeRef type of box_ptr_ty.
380     let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
381     let llty = type_of(ccx, box_ptr_ty);
382     let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
383
384     // Allocate space:
385     let drop_glue = glue::get_drop_glue(ccx, t);
386     let r = callee::trans_lang_call(
387         bcx,
388         langcall,
389         [
390             PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
391             size,
392             llalign
393         ],
394         None);
395     rslt(r.bcx, PointerCast(r.bcx, r.val, llty))
396 }
397
398 // Type descriptor and type glue stuff
399
400 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> @tydesc_info {
401     match ccx.tydescs.borrow().find(&t) {
402         Some(&inf) => return inf,
403         _ => { }
404     }
405
406     ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
407     let inf = glue::declare_tydesc(ccx, t);
408
409     ccx.tydescs.borrow_mut().insert(t, inf);
410     return inf;
411 }
412
413 #[allow(dead_code)] // useful
414 pub fn set_optimize_for_size(f: ValueRef) {
415     lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
416 }
417
418 pub fn set_no_inline(f: ValueRef) {
419     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
420 }
421
422 #[allow(dead_code)] // useful
423 pub fn set_no_unwind(f: ValueRef) {
424     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
425 }
426
427 // Tell LLVM to emit the information necessary to unwind the stack for the
428 // function f.
429 pub fn set_uwtable(f: ValueRef) {
430     lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
431 }
432
433 pub fn set_inline_hint(f: ValueRef) {
434     lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
435 }
436
437 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
438     use syntax::attr::*;
439     // Set the inline hint if there is one
440     match find_inline_attr(attrs) {
441         InlineHint   => set_inline_hint(llfn),
442         InlineAlways => set_always_inline(llfn),
443         InlineNever  => set_no_inline(llfn),
444         InlineNone   => { /* fallthrough */ }
445     }
446
447     // Add the no-split-stack attribute if requested
448     if contains_name(attrs, "no_split_stack") {
449         set_no_split_stack(llfn);
450     }
451
452     if contains_name(attrs, "cold") {
453         unsafe { llvm::LLVMAddColdAttribute(llfn) }
454     }
455 }
456
457 pub fn set_always_inline(f: ValueRef) {
458     lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
459 }
460
461 pub fn set_no_split_stack(f: ValueRef) {
462     "no-split-stack".with_c_str(|buf| {
463         unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
464     })
465 }
466
467 // Double-check that we never ask LLVM to declare the same symbol twice. It
468 // silently mangles such symbols, breaking our linkage model.
469 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
470     if ccx.all_llvm_symbols.borrow().contains(&sym) {
471         ccx.sess().bug(~"duplicate LLVM symbol: " + sym);
472     }
473     ccx.all_llvm_symbols.borrow_mut().insert(sym);
474 }
475
476
477 pub fn get_res_dtor(ccx: &CrateContext,
478                     did: ast::DefId,
479                     parent_id: ast::DefId,
480                     substs: &[ty::t])
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     if !substs.is_empty() {
489         assert_eq!(did.krate, ast::LOCAL_CRATE);
490         let tsubsts = ty::substs {
491             regions: ty::ErasedRegions,
492             self_ty: None,
493             tps: Vec::from_slice(substs),
494         };
495
496         let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, &tsubsts);
497         let (val, _) = monomorphize::monomorphic_fn(ccx, did, &tsubsts, vtables, None, None);
498
499         val
500     } else if did.krate == ast::LOCAL_CRATE {
501         get_item_val(ccx, did.node)
502     } else {
503         let tcx = ccx.tcx();
504         let name = csearch::get_symbol(&ccx.sess().cstore, did);
505         let class_ty = ty::subst_tps(tcx,
506                                      substs,
507                                      None,
508                                      ty::lookup_item_type(tcx, parent_id).ty);
509         let llty = type_of_dtor(ccx, class_ty);
510
511         get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
512                       lib::llvm::CCallConv, llty, ty::mk_nil())
513     }
514 }
515
516 // Structural comparison: a rather involved form of glue.
517 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
518     if cx.sess().opts.cg.save_temps {
519         s.with_c_str(|buf| {
520             unsafe {
521                 llvm::LLVMSetValueName(v, buf)
522             }
523         })
524     }
525 }
526
527
528 // Used only for creating scalar comparison glue.
529 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
530
531 // NB: This produces an i1, not a Rust bool (i8).
532 pub fn compare_scalar_types<'a>(
533                             cx: &'a Block<'a>,
534                             lhs: ValueRef,
535                             rhs: ValueRef,
536                             t: ty::t,
537                             op: ast::BinOp)
538                             -> Result<'a> {
539     let f = |a| rslt(cx, compare_scalar_values(cx, lhs, rhs, a, op));
540
541     match ty::get(t).sty {
542         ty::ty_nil => f(nil_type),
543         ty::ty_bool | ty::ty_ptr(_) |
544         ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
545         ty::ty_int(_) => f(signed_int),
546         ty::ty_float(_) => f(floating_point),
547             // Should never get here, because t is scalar.
548         _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
549     }
550 }
551
552
553 // A helper function to do the actual comparison of scalar values.
554 pub fn compare_scalar_values<'a>(
555                              cx: &'a Block<'a>,
556                              lhs: ValueRef,
557                              rhs: ValueRef,
558                              nt: scalar_type,
559                              op: ast::BinOp)
560                              -> ValueRef {
561     let _icx = push_ctxt("compare_scalar_values");
562     fn die(cx: &Block) -> ! {
563         cx.sess().bug("compare_scalar_values: must be a comparison operator");
564     }
565     match nt {
566       nil_type => {
567         // We don't need to do actual comparisons for nil.
568         // () == () holds but () < () does not.
569         match op {
570           ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(cx.ccx(), true),
571           ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(cx.ccx(), false),
572           // refinements would be nice
573           _ => die(cx)
574         }
575       }
576       floating_point => {
577         let cmp = match op {
578           ast::BiEq => lib::llvm::RealOEQ,
579           ast::BiNe => lib::llvm::RealUNE,
580           ast::BiLt => lib::llvm::RealOLT,
581           ast::BiLe => lib::llvm::RealOLE,
582           ast::BiGt => lib::llvm::RealOGT,
583           ast::BiGe => lib::llvm::RealOGE,
584           _ => die(cx)
585         };
586         return FCmp(cx, cmp, lhs, rhs);
587       }
588       signed_int => {
589         let cmp = match op {
590           ast::BiEq => lib::llvm::IntEQ,
591           ast::BiNe => lib::llvm::IntNE,
592           ast::BiLt => lib::llvm::IntSLT,
593           ast::BiLe => lib::llvm::IntSLE,
594           ast::BiGt => lib::llvm::IntSGT,
595           ast::BiGe => lib::llvm::IntSGE,
596           _ => die(cx)
597         };
598         return ICmp(cx, cmp, lhs, rhs);
599       }
600       unsigned_int => {
601         let cmp = match op {
602           ast::BiEq => lib::llvm::IntEQ,
603           ast::BiNe => lib::llvm::IntNE,
604           ast::BiLt => lib::llvm::IntULT,
605           ast::BiLe => lib::llvm::IntULE,
606           ast::BiGt => lib::llvm::IntUGT,
607           ast::BiGe => lib::llvm::IntUGE,
608           _ => die(cx)
609         };
610         return ICmp(cx, cmp, lhs, rhs);
611       }
612     }
613 }
614
615 pub type val_and_ty_fn<'r,'b> =
616     |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
617
618 // Iterates through the elements of a structural type.
619 pub fn iter_structural_ty<'r,
620                           'b>(
621                           cx: &'b Block<'b>,
622                           av: ValueRef,
623                           t: ty::t,
624                           f: val_and_ty_fn<'r,'b>)
625                           -> &'b Block<'b> {
626     let _icx = push_ctxt("iter_structural_ty");
627
628     fn iter_variant<'r,
629                     'b>(
630                     cx: &'b Block<'b>,
631                     repr: &adt::Repr,
632                     av: ValueRef,
633                     variant: @ty::VariantInfo,
634                     tps: &[ty::t],
635                     f: val_and_ty_fn<'r,'b>)
636                     -> &'b Block<'b> {
637         let _icx = push_ctxt("iter_variant");
638         let tcx = cx.tcx();
639         let mut cx = cx;
640
641         for (i, &arg) in variant.args.iter().enumerate() {
642             cx = f(cx,
643                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
644                    ty::subst_tps(tcx, tps, None, arg));
645         }
646         return cx;
647     }
648
649     let mut cx = cx;
650     match ty::get(t).sty {
651       ty::ty_struct(..) => {
652           let repr = adt::represent_type(cx.ccx(), t);
653           expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
654               for (i, field_ty) in field_tys.iter().enumerate() {
655                   let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
656                   cx = f(cx, llfld_a, field_ty.mt.ty);
657               }
658           })
659       }
660       ty::ty_str(ty::VstoreFixed(n)) |
661       ty::ty_vec(_, ty::VstoreFixed(n)) => {
662         let unit_ty = ty::sequence_element_type(cx.tcx(), t);
663         let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
664         cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
665       }
666       ty::ty_tup(ref args) => {
667           let repr = adt::represent_type(cx.ccx(), t);
668           for (i, arg) in args.iter().enumerate() {
669               let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
670               cx = f(cx, llfld_a, *arg);
671           }
672       }
673       ty::ty_enum(tid, ref substs) => {
674           let fcx = cx.fcx;
675           let ccx = fcx.ccx;
676
677           let repr = adt::represent_type(ccx, t);
678           let variants = ty::enum_variants(ccx.tcx(), tid);
679           let n_variants = (*variants).len();
680
681           // NB: we must hit the discriminant first so that structural
682           // comparison know not to proceed when the discriminants differ.
683
684           match adt::trans_switch(cx, repr, av) {
685               (_match::single, None) => {
686                   cx = iter_variant(cx, repr, av, *variants.get(0),
687                                     substs.tps.as_slice(), f);
688               }
689               (_match::switch, Some(lldiscrim_a)) => {
690                   cx = f(cx, lldiscrim_a, ty::mk_int());
691                   let unr_cx = fcx.new_temp_block("enum-iter-unr");
692                   Unreachable(unr_cx);
693                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
694                                         n_variants);
695                   let next_cx = fcx.new_temp_block("enum-iter-next");
696
697                   for variant in (*variants).iter() {
698                       let variant_cx =
699                           fcx.new_temp_block(~"enum-iter-variant-" +
700                                              variant.disr_val.to_str());
701                       match adt::trans_case(cx, repr, variant.disr_val) {
702                           _match::single_result(r) => {
703                               AddCase(llswitch, r.val, variant_cx.llbb)
704                           }
705                           _ => ccx.sess().unimpl("value from adt::trans_case \
706                                                   in iter_structural_ty")
707                       }
708                       let variant_cx =
709                           iter_variant(variant_cx,
710                                        repr,
711                                        av,
712                                        *variant,
713                                        substs.tps.as_slice(),
714                                        |x,y,z| f(x,y,z));
715                       Br(variant_cx, next_cx.llbb);
716                   }
717                   cx = next_cx;
718               }
719               _ => ccx.sess().unimpl("value from adt::trans_switch \
720                                       in iter_structural_ty")
721           }
722       }
723       _ => cx.sess().unimpl("type in iter_structural_ty")
724     }
725     return cx;
726 }
727
728 pub fn cast_shift_expr_rhs<'a>(
729                            cx: &'a Block<'a>,
730                            op: ast::BinOp,
731                            lhs: ValueRef,
732                            rhs: ValueRef)
733                            -> ValueRef {
734     cast_shift_rhs(op, lhs, rhs,
735                    |a,b| Trunc(cx, a, b),
736                    |a,b| ZExt(cx, a, b))
737 }
738
739 pub fn cast_shift_const_rhs(op: ast::BinOp,
740                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
741     cast_shift_rhs(op, lhs, rhs,
742                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
743                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
744 }
745
746 pub fn cast_shift_rhs(op: ast::BinOp,
747                       lhs: ValueRef,
748                       rhs: ValueRef,
749                       trunc: |ValueRef, Type| -> ValueRef,
750                       zext: |ValueRef, Type| -> ValueRef)
751                       -> ValueRef {
752     // Shifts may have any size int on the rhs
753     unsafe {
754         if ast_util::is_shift_binop(op) {
755             let mut rhs_llty = val_ty(rhs);
756             let mut lhs_llty = val_ty(lhs);
757             if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
758             if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
759             let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
760             let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
761             if lhs_sz < rhs_sz {
762                 trunc(rhs, lhs_llty)
763             } else if lhs_sz > rhs_sz {
764                 // FIXME (#1877: If shifting by negative
765                 // values becomes not undefined then this is wrong.
766                 zext(rhs, lhs_llty)
767             } else {
768                 rhs
769             }
770         } else {
771             rhs
772         }
773     }
774 }
775
776 pub fn fail_if_zero<'a>(
777                     cx: &'a Block<'a>,
778                     span: Span,
779                     divrem: ast::BinOp,
780                     rhs: ValueRef,
781                     rhs_t: ty::t)
782                     -> &'a Block<'a> {
783     let text = if divrem == ast::BiDiv {
784         "attempted to divide by zero"
785     } else {
786         "attempted remainder with a divisor of zero"
787     };
788     let is_zero = match ty::get(rhs_t).sty {
789       ty::ty_int(t) => {
790         let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
791         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
792       }
793       ty::ty_uint(t) => {
794         let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
795         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
796       }
797       _ => {
798         cx.sess().bug(~"fail-if-zero on unexpected type: " +
799                       ty_to_str(cx.tcx(), rhs_t));
800       }
801     };
802     with_cond(cx, is_zero, |bcx| {
803         controlflow::trans_fail(bcx, span, InternedString::new(text))
804     })
805 }
806
807 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
808     let name = csearch::get_symbol(&ccx.sess().cstore, did);
809     match ty::get(t).sty {
810         ty::ty_bare_fn(ref fn_ty) => {
811             match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
812                                        ccx.sess().targ_cfg.arch) {
813                 Some(Rust) | Some(RustIntrinsic) => {
814                     get_extern_rust_fn(ccx,
815                                        fn_ty.sig.inputs.as_slice(),
816                                        fn_ty.sig.output,
817                                        name,
818                                        did)
819                 }
820                 Some(..) | None => {
821                     let c = foreign::llvm_calling_convention(ccx, fn_ty.abi);
822                     let cconv = c.unwrap_or(lib::llvm::CCallConv);
823                     let llty = type_of_fn_from_ty(ccx, t);
824                     get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod,
825                                   name, cconv, llty, fn_ty.sig.output)
826                 }
827             }
828         }
829         ty::ty_closure(ref f) => {
830             get_extern_rust_fn(ccx,
831                                f.sig.inputs.as_slice(),
832                                f.sig.output,
833                                name,
834                                did)
835         }
836         _ => {
837             let llty = type_of(ccx, t);
838             get_extern_const(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
839                              llty)
840         }
841     }
842 }
843
844 pub fn invoke<'a>(
845               bcx: &'a Block<'a>,
846               llfn: ValueRef,
847               llargs: Vec<ValueRef> ,
848               attributes: &[(uint, lib::llvm::Attribute)],
849               call_info: Option<NodeInfo>)
850               -> (ValueRef, &'a Block<'a>) {
851     let _icx = push_ctxt("invoke_");
852     if bcx.unreachable.get() {
853         return (C_null(Type::i8(bcx.ccx())), bcx);
854     }
855
856     match bcx.opt_node_id {
857         None => {
858             debug!("invoke at ???");
859         }
860         Some(id) => {
861             debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
862         }
863     }
864
865     if need_invoke(bcx) {
866         debug!("invoking {} at {}", llfn, bcx.llbb);
867         for &llarg in llargs.iter() {
868             debug!("arg: {}", llarg);
869         }
870         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
871         let landing_pad = bcx.fcx.get_landing_pad();
872
873         match call_info {
874             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
875             None => debuginfo::clear_source_location(bcx.fcx)
876         };
877
878         let llresult = Invoke(bcx,
879                               llfn,
880                               llargs.as_slice(),
881                               normal_bcx.llbb,
882                               landing_pad,
883                               attributes);
884         return (llresult, normal_bcx);
885     } else {
886         debug!("calling {} at {}", llfn, bcx.llbb);
887         for &llarg in llargs.iter() {
888             debug!("arg: {}", llarg);
889         }
890
891         match call_info {
892             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
893             None => debuginfo::clear_source_location(bcx.fcx)
894         };
895
896         let llresult = Call(bcx, llfn, llargs.as_slice(), attributes);
897         return (llresult, bcx);
898     }
899 }
900
901 pub fn need_invoke(bcx: &Block) -> bool {
902     if bcx.sess().no_landing_pads() {
903         return false;
904     }
905
906     // Avoid using invoke if we are already inside a landing pad.
907     if bcx.is_lpad {
908         return false;
909     }
910
911     bcx.fcx.needs_invoke()
912 }
913
914 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
915     let _icx = push_ctxt("load_if_immediate");
916     if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
917     return v;
918 }
919
920 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
921     match local.pat.node {
922         ast::PatWild => true, _ => false
923     }
924 }
925
926 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
927                   -> &'a Block<'a> {
928
929     debug!("init_local(bcx={}, local.id={:?})",
930            bcx.to_str(), local.id);
931     let _indenter = indenter();
932
933     let _icx = push_ctxt("init_local");
934
935     if ignore_lhs(bcx, local) {
936         // Handle let _ = e; just like e;
937         match local.init {
938             Some(init) => {
939                 return controlflow::trans_stmt_semi(bcx, init)
940             }
941             None => { return bcx; }
942         }
943     }
944
945     _match::store_local(bcx, local)
946 }
947
948 pub fn raw_block<'a>(
949                  fcx: &'a FunctionContext<'a>,
950                  is_lpad: bool,
951                  llbb: BasicBlockRef)
952                  -> &'a Block<'a> {
953     Block::new(llbb, is_lpad, None, fcx)
954 }
955
956 pub fn with_cond<'a>(
957                  bcx: &'a Block<'a>,
958                  val: ValueRef,
959                  f: |&'a Block<'a>| -> &'a Block<'a>)
960                  -> &'a Block<'a> {
961     let _icx = push_ctxt("with_cond");
962     let fcx = bcx.fcx;
963     let next_cx = fcx.new_temp_block("next");
964     let cond_cx = fcx.new_temp_block("cond");
965     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
966     let after_cx = f(cond_cx);
967     if !after_cx.terminated.get() {
968         Br(after_cx, next_cx.llbb);
969     }
970     next_cx
971 }
972
973 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
974     let _icx = push_ctxt("call_memcpy");
975     let ccx = cx.ccx();
976     let key = match ccx.sess().targ_cfg.arch {
977         X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
978         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
979     };
980     let memcpy = ccx.get_intrinsic(&key);
981     let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
982     let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
983     let size = IntCast(cx, n_bytes, ccx.int_type);
984     let align = C_i32(ccx, align as i32);
985     let volatile = C_i1(ccx, false);
986     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
987 }
988
989 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
990     let _icx = push_ctxt("memcpy_ty");
991     let ccx = bcx.ccx();
992     if ty::type_is_structural(t) {
993         let llty = type_of::type_of(ccx, t);
994         let llsz = llsize_of(ccx, llty);
995         let llalign = llalign_of_min(ccx, llty);
996         call_memcpy(bcx, dst, src, llsz, llalign as u32);
997     } else {
998         Store(bcx, Load(bcx, src), dst);
999     }
1000 }
1001
1002 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1003     if cx.unreachable.get() { return; }
1004     let _icx = push_ctxt("zero_mem");
1005     let bcx = cx;
1006     let ccx = cx.ccx();
1007     let llty = type_of::type_of(ccx, t);
1008     memzero(&B(bcx), llptr, llty);
1009 }
1010
1011 // Always use this function instead of storing a zero constant to the memory
1012 // in question. If you store a zero constant, LLVM will drown in vreg
1013 // allocation for large data structures, and the generated code will be
1014 // awful. (A telltale sign of this is large quantities of
1015 // `mov [byte ptr foo],0` in the generated code.)
1016 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1017     let _icx = push_ctxt("memzero");
1018     let ccx = b.ccx;
1019
1020     let intrinsic_key = match ccx.sess().targ_cfg.arch {
1021         X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1022         X86_64 => "llvm.memset.p0i8.i64"
1023     };
1024
1025     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1026     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1027     let llzeroval = C_u8(ccx, 0);
1028     let size = machine::llsize_of(ccx, ty);
1029     let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1030     let volatile = C_i1(ccx, false);
1031     b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1032 }
1033
1034 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1035     let _icx = push_ctxt("alloc_ty");
1036     let ccx = bcx.ccx();
1037     let ty = type_of::type_of(ccx, t);
1038     assert!(!ty::type_has_params(t));
1039     let val = alloca(bcx, ty, name);
1040     return val;
1041 }
1042
1043 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1044     alloca_maybe_zeroed(cx, ty, name, false)
1045 }
1046
1047 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1048     let _icx = push_ctxt("alloca");
1049     if cx.unreachable.get() {
1050         unsafe {
1051             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1052         }
1053     }
1054     debuginfo::clear_source_location(cx.fcx);
1055     let p = Alloca(cx, ty, name);
1056     if zero {
1057         let b = cx.fcx.ccx.builder();
1058         b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1059         memzero(&b, p, ty);
1060     }
1061     p
1062 }
1063
1064 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1065     let _icx = push_ctxt("arrayalloca");
1066     if cx.unreachable.get() {
1067         unsafe {
1068             return llvm::LLVMGetUndef(ty.to_ref());
1069         }
1070     }
1071     debuginfo::clear_source_location(cx.fcx);
1072     return ArrayAlloca(cx, ty, v);
1073 }
1074
1075 // Creates and returns space for, or returns the argument representing, the
1076 // slot where the return value of the function must go.
1077 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1078                            -> ValueRef {
1079     unsafe {
1080         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1081             llvm::LLVMGetParam(fcx.llfn, 0)
1082         } else {
1083             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1084             let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1085             Alloca(bcx, lloutputtype, "__make_return_pointer")
1086         }
1087     }
1088 }
1089
1090 // NB: must keep 4 fns in sync:
1091 //
1092 //  - type_of_fn
1093 //  - create_datums_for_fn_args.
1094 //  - new_fn_ctxt
1095 //  - trans_args
1096 //
1097 // Be warned! You must call `init_function` before doing anything with the
1098 // returned function context.
1099 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1100                        llfndecl: ValueRef,
1101                        id: ast::NodeId,
1102                        has_env: bool,
1103                        output_type: ty::t,
1104                        param_substs: Option<@param_substs>,
1105                        sp: Option<Span>,
1106                        block_arena: &'a TypedArena<Block<'a>>)
1107                        -> FunctionContext<'a> {
1108     for p in param_substs.iter() { p.validate(); }
1109
1110     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1111            if id == -1 { ~"" } else { ccx.tcx.map.path_to_str(id) },
1112            id, param_substs.repr(ccx.tcx()));
1113
1114     let substd_output_type = match param_substs {
1115         None => output_type,
1116         Some(substs) => {
1117             ty::subst_tps(ccx.tcx(),
1118                           substs.tys.as_slice(),
1119                           substs.self_ty,
1120                           output_type)
1121         }
1122     };
1123     let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1124     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1125
1126     let mut fcx = FunctionContext {
1127           llfn: llfndecl,
1128           llenv: None,
1129           llretptr: Cell::new(None),
1130           entry_bcx: RefCell::new(None),
1131           alloca_insert_pt: Cell::new(None),
1132           llreturn: Cell::new(None),
1133           personality: Cell::new(None),
1134           caller_expects_out_pointer: uses_outptr,
1135           llargs: RefCell::new(NodeMap::new()),
1136           lllocals: RefCell::new(NodeMap::new()),
1137           llupvars: RefCell::new(NodeMap::new()),
1138           id: id,
1139           param_substs: param_substs,
1140           span: sp,
1141           block_arena: block_arena,
1142           ccx: ccx,
1143           debug_context: debug_context,
1144           scopes: RefCell::new(Vec::new())
1145     };
1146
1147     if has_env {
1148         fcx.llenv = Some(unsafe {
1149             llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1150         });
1151     }
1152
1153     fcx
1154 }
1155
1156 /// Performs setup on a newly created function, creating the entry scope block
1157 /// and allocating space for the return pointer.
1158 pub fn init_function<'a>(
1159                      fcx: &'a FunctionContext<'a>,
1160                      skip_retptr: bool,
1161                      output_type: ty::t,
1162                      param_substs: Option<@param_substs>) {
1163     let entry_bcx = fcx.new_temp_block("entry-block");
1164
1165     *fcx.entry_bcx.borrow_mut() = Some(entry_bcx);
1166
1167     // Use a dummy instruction as the insertion point for all allocas.
1168     // This is later removed in FunctionContext::cleanup.
1169     fcx.alloca_insert_pt.set(Some(unsafe {
1170         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1171         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1172     }));
1173
1174     let substd_output_type = match param_substs {
1175         None => output_type,
1176         Some(substs) => {
1177             ty::subst_tps(fcx.ccx.tcx(),
1178                           substs.tys.as_slice(),
1179                           substs.self_ty,
1180                           output_type)
1181         }
1182     };
1183
1184     if !return_type_is_void(fcx.ccx, substd_output_type) {
1185         // If the function returns nil/bot, there is no real return
1186         // value, so do not set `llretptr`.
1187         if !skip_retptr || fcx.caller_expects_out_pointer {
1188             // Otherwise, we normally allocate the llretptr, unless we
1189             // have been instructed to skip it for immediate return
1190             // values.
1191             fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1192         }
1193     }
1194 }
1195
1196 // NB: must keep 4 fns in sync:
1197 //
1198 //  - type_of_fn
1199 //  - create_datums_for_fn_args.
1200 //  - new_fn_ctxt
1201 //  - trans_args
1202
1203 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1204     use middle::trans::datum::{ByRef, ByValue};
1205
1206     datum::Rvalue {
1207         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1208     }
1209 }
1210
1211 // work around bizarre resolve errors
1212 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1213 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1214
1215 // create_datums_for_fn_args: creates rvalue datums for each of the
1216 // incoming function arguments. These will later be stored into
1217 // appropriate lvalue datums.
1218 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1219                                  arg_tys: &[ty::t])
1220                                  -> Vec<RvalueDatum> {
1221     let _icx = push_ctxt("create_datums_for_fn_args");
1222
1223     // Return an array wrapping the ValueRefs that we get from
1224     // llvm::LLVMGetParam for each argument into datums.
1225     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1226         let llarg = unsafe {
1227             llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1228         };
1229         datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1230     }).collect()
1231 }
1232
1233 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1234                             arg_scope: cleanup::CustomScopeIndex,
1235                             bcx: &'a Block<'a>,
1236                             args: &[ast::Arg],
1237                             arg_datums: Vec<RvalueDatum> )
1238                             -> &'a Block<'a> {
1239     debug!("copy_args_to_allocas");
1240
1241     let _icx = push_ctxt("copy_args_to_allocas");
1242     let mut bcx = bcx;
1243
1244     let arg_scope_id = cleanup::CustomScope(arg_scope);
1245
1246     for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1247         // For certain mode/type combinations, the raw llarg values are passed
1248         // by value.  However, within the fn body itself, we want to always
1249         // have all locals and arguments be by-ref so that we can cancel the
1250         // cleanup and for better interaction with LLVM's debug info.  So, if
1251         // the argument would be passed by value, we store it into an alloca.
1252         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1253         // the event it's not truly needed.
1254
1255         bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1256
1257         if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1258             debuginfo::create_argument_metadata(bcx, &args[i]);
1259         }
1260     }
1261
1262     bcx
1263 }
1264
1265 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1266 // and builds the return block.
1267 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1268                      last_bcx: &'a Block<'a>) {
1269     let _icx = push_ctxt("finish_fn");
1270
1271     let ret_cx = match fcx.llreturn.get() {
1272         Some(llreturn) => {
1273             if !last_bcx.terminated.get() {
1274                 Br(last_bcx, llreturn);
1275             }
1276             raw_block(fcx, false, llreturn)
1277         }
1278         None => last_bcx
1279     };
1280     build_return_block(fcx, ret_cx);
1281     debuginfo::clear_source_location(fcx);
1282     fcx.cleanup();
1283 }
1284
1285 // Builds the return block for a function.
1286 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1287     // Return the value if this function immediate; otherwise, return void.
1288     if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1289         return RetVoid(ret_cx);
1290     }
1291
1292     let retptr = Value(fcx.llretptr.get().unwrap());
1293     let retval = match retptr.get_dominating_store(ret_cx) {
1294         // If there's only a single store to the ret slot, we can directly return
1295         // the value that was stored and omit the store and the alloca
1296         Some(s) => {
1297             let retval = s.get_operand(0).unwrap().get();
1298             s.erase_from_parent();
1299
1300             if retptr.has_no_uses() {
1301                 retptr.erase_from_parent();
1302             }
1303
1304             retval
1305         }
1306         // Otherwise, load the return value from the ret slot
1307         None => Load(ret_cx, fcx.llretptr.get().unwrap())
1308     };
1309
1310
1311     Ret(ret_cx, retval);
1312 }
1313
1314 // trans_closure: Builds an LLVM function out of a source function.
1315 // If the function closes over its environment a closure will be
1316 // returned.
1317 pub fn trans_closure(ccx: &CrateContext,
1318                      decl: &ast::FnDecl,
1319                      body: &ast::Block,
1320                      llfndecl: ValueRef,
1321                      param_substs: Option<@param_substs>,
1322                      id: ast::NodeId,
1323                      _attributes: &[ast::Attribute],
1324                      output_type: ty::t,
1325                      maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1326     ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1327
1328     let _icx = push_ctxt("trans_closure");
1329     set_uwtable(llfndecl);
1330
1331     debug!("trans_closure(..., param_substs={})",
1332            param_substs.repr(ccx.tcx()));
1333
1334     let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1335         ty::ty_closure(_) => true,
1336         _ => false
1337     };
1338
1339     let arena = TypedArena::new();
1340     let fcx = new_fn_ctxt(ccx,
1341                           llfndecl,
1342                           id,
1343                           has_env,
1344                           output_type,
1345                           param_substs,
1346                           Some(body.span),
1347                           &arena);
1348     init_function(&fcx, false, output_type, param_substs);
1349
1350     // cleanup scope for the incoming arguments
1351     let arg_scope = fcx.push_custom_cleanup_scope();
1352
1353     // Create the first basic block in the function and keep a handle on it to
1354     //  pass to finish_fn later.
1355     let bcx_top = fcx.entry_bcx.borrow().clone().unwrap();
1356     let mut bcx = bcx_top;
1357     let block_ty = node_id_type(bcx, body.id);
1358
1359     // Set up arguments to the function.
1360     let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1361     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1362
1363     bcx = copy_args_to_allocas(&fcx,
1364                                arg_scope,
1365                                bcx,
1366                                decl.inputs.as_slice(),
1367                                arg_datums);
1368
1369     bcx = maybe_load_env(bcx);
1370
1371     // Up until here, IR instructions for this function have explicitly not been annotated with
1372     // source code location, so we don't step into call setup code. From here on, source location
1373     // emitting should be enabled.
1374     debuginfo::start_emitting_source_locations(&fcx);
1375
1376     let dest = match fcx.llretptr.get() {
1377         Some(e) => {expr::SaveIn(e)}
1378         None => {
1379             assert!(type_is_zero_size(bcx.ccx(), block_ty))
1380             expr::Ignore
1381         }
1382     };
1383
1384     // This call to trans_block is the place where we bridge between
1385     // translation calls that don't have a return value (trans_crate,
1386     // trans_mod, trans_item, et cetera) and those that do
1387     // (trans_block, trans_expr, et cetera).
1388     bcx = controlflow::trans_block(bcx, body, dest);
1389
1390     match fcx.llreturn.get() {
1391         Some(_) => {
1392             Br(bcx, fcx.return_exit_block());
1393             fcx.pop_custom_cleanup_scope(arg_scope);
1394         }
1395         None => {
1396             // Microoptimization writ large: avoid creating a separate
1397             // llreturn basic block
1398             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1399         }
1400     };
1401
1402     // Put return block after all other blocks.
1403     // This somewhat improves single-stepping experience in debugger.
1404     unsafe {
1405         let llreturn = fcx.llreturn.get();
1406         for &llreturn in llreturn.iter() {
1407             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1408         }
1409     }
1410
1411     // Insert the mandatory first few basic blocks before lltop.
1412     finish_fn(&fcx, bcx);
1413 }
1414
1415 // trans_fn: creates an LLVM function corresponding to a source language
1416 // function.
1417 pub fn trans_fn(ccx: &CrateContext,
1418                 decl: &ast::FnDecl,
1419                 body: &ast::Block,
1420                 llfndecl: ValueRef,
1421                 param_substs: Option<@param_substs>,
1422                 id: ast::NodeId,
1423                 attrs: &[ast::Attribute]) {
1424     let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id));
1425     debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1426     let _icx = push_ctxt("trans_fn");
1427     let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1428     trans_closure(ccx, decl, body, llfndecl,
1429                   param_substs, id, attrs, output_type, |bcx| bcx);
1430 }
1431
1432 pub fn trans_enum_variant(ccx: &CrateContext,
1433                           _enum_id: ast::NodeId,
1434                           variant: &ast::Variant,
1435                           _args: &[ast::VariantArg],
1436                           disr: ty::Disr,
1437                           param_substs: Option<@param_substs>,
1438                           llfndecl: ValueRef) {
1439     let _icx = push_ctxt("trans_enum_variant");
1440
1441     trans_enum_variant_or_tuple_like_struct(
1442         ccx,
1443         variant.node.id,
1444         disr,
1445         param_substs,
1446         llfndecl);
1447 }
1448
1449 pub fn trans_tuple_struct(ccx: &CrateContext,
1450                           _fields: &[ast::StructField],
1451                           ctor_id: ast::NodeId,
1452                           param_substs: Option<@param_substs>,
1453                           llfndecl: ValueRef) {
1454     let _icx = push_ctxt("trans_tuple_struct");
1455
1456     trans_enum_variant_or_tuple_like_struct(
1457         ccx,
1458         ctor_id,
1459         0,
1460         param_substs,
1461         llfndecl);
1462 }
1463
1464 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1465                                            ctor_id: ast::NodeId,
1466                                            disr: ty::Disr,
1467                                            param_substs: Option<@param_substs>,
1468                                            llfndecl: ValueRef) {
1469     let no_substs: &[ty::t] = [];
1470     let ty_param_substs = match param_substs {
1471         Some(ref substs) => {
1472             let v: &[ty::t] = substs.tys.as_slice();
1473             v
1474         }
1475         None => {
1476             let v: &[ty::t] = no_substs;
1477             v
1478         }
1479     };
1480
1481     let ctor_ty = ty::subst_tps(ccx.tcx(),
1482                                 ty_param_substs,
1483                                 None,
1484                                 ty::node_id_to_type(ccx.tcx(), ctor_id));
1485
1486     let result_ty = match ty::get(ctor_ty).sty {
1487         ty::ty_bare_fn(ref bft) => bft.sig.output,
1488         _ => ccx.sess().bug(
1489             format!("trans_enum_variant_or_tuple_like_struct: \
1490                   unexpected ctor return type {}",
1491                  ty_to_str(ccx.tcx(), ctor_ty)))
1492     };
1493
1494     let arena = TypedArena::new();
1495     let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1496                           param_substs, None, &arena);
1497     init_function(&fcx, false, result_ty, param_substs);
1498
1499     let arg_tys = ty::ty_fn_args(ctor_ty);
1500
1501     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1502
1503     let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1504
1505     if !type_is_zero_size(fcx.ccx, result_ty) {
1506         let repr = adt::represent_type(ccx, result_ty);
1507         adt::trans_start_init(bcx, repr, fcx.llretptr.get().unwrap(), disr);
1508         for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1509             let lldestptr = adt::trans_field_ptr(bcx,
1510                                                  repr,
1511                                                  fcx.llretptr.get().unwrap(),
1512                                                  disr,
1513                                                  i);
1514             arg_datum.store_to(bcx, lldestptr);
1515         }
1516     }
1517
1518     finish_fn(&fcx, bcx);
1519 }
1520
1521 pub fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1522                       id: ast::NodeId, vi: @Vec<@ty::VariantInfo>,
1523                       i: &mut uint) {
1524     for &variant in enum_definition.variants.iter() {
1525         let disr_val = vi.get(*i).disr_val;
1526         *i += 1;
1527
1528         match variant.node.kind {
1529             ast::TupleVariantKind(ref args) if args.len() > 0 => {
1530                 let llfn = get_item_val(ccx, variant.node.id);
1531                 trans_enum_variant(ccx, id, variant, args.as_slice(),
1532                                    disr_val, None, llfn);
1533             }
1534             ast::TupleVariantKind(_) => {
1535                 // Nothing to do.
1536             }
1537             ast::StructVariantKind(struct_def) => {
1538                 trans_struct_def(ccx, struct_def);
1539             }
1540         }
1541     }
1542 }
1543
1544 pub struct TransItemVisitor<'a> {
1545     pub ccx: &'a CrateContext,
1546 }
1547
1548 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1549     fn visit_item(&mut self, i: &ast::Item, _:()) {
1550         trans_item(self.ccx, i);
1551     }
1552 }
1553
1554 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1555     let _icx = push_ctxt("trans_item");
1556     match item.node {
1557       ast::ItemFn(decl, fn_style, _abi, ref generics, body) => {
1558         if fn_style == ast::ExternFn  {
1559             let llfndecl = get_item_val(ccx, item.id);
1560             foreign::trans_rust_fn_with_foreign_abi(
1561                 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1562         } else if !generics.is_type_parameterized() {
1563             let llfn = get_item_val(ccx, item.id);
1564             trans_fn(ccx,
1565                      decl,
1566                      body,
1567                      llfn,
1568                      None,
1569                      item.id,
1570                      item.attrs.as_slice());
1571         } else {
1572             // Be sure to travel more than just one layer deep to catch nested
1573             // items in blocks and such.
1574             let mut v = TransItemVisitor{ ccx: ccx };
1575             v.visit_block(body, ());
1576         }
1577       }
1578       ast::ItemImpl(ref generics, _, _, ref ms) => {
1579         meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1580       }
1581       ast::ItemMod(ref m) => {
1582         trans_mod(ccx, m);
1583       }
1584       ast::ItemEnum(ref enum_definition, ref generics) => {
1585         if !generics.is_type_parameterized() {
1586             let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1587             let mut i = 0;
1588             trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
1589         }
1590       }
1591       ast::ItemStatic(_, m, expr) => {
1592           consts::trans_const(ccx, m, item.id);
1593           // Do static_assert checking. It can't really be done much earlier
1594           // because we need to get the value of the bool out of LLVM
1595           if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1596               if m == ast::MutMutable {
1597                   ccx.sess().span_fatal(expr.span,
1598                                         "cannot have static_assert on a mutable \
1599                                          static");
1600               }
1601
1602               let v = ccx.const_values.borrow().get_copy(&item.id);
1603               unsafe {
1604                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1605                       ccx.sess().span_fatal(expr.span, "static assertion failed");
1606                   }
1607               }
1608           }
1609       },
1610       ast::ItemForeignMod(ref foreign_mod) => {
1611         foreign::trans_foreign_mod(ccx, foreign_mod);
1612       }
1613       ast::ItemStruct(struct_def, ref generics) => {
1614         if !generics.is_type_parameterized() {
1615             trans_struct_def(ccx, struct_def);
1616         }
1617       }
1618       ast::ItemTrait(..) => {
1619         // Inside of this trait definition, we won't be actually translating any
1620         // functions, but the trait still needs to be walked. Otherwise default
1621         // methods with items will not get translated and will cause ICE's when
1622         // metadata time comes around.
1623         let mut v = TransItemVisitor{ ccx: ccx };
1624         visit::walk_item(&mut v, item, ());
1625       }
1626       _ => {/* fall through */ }
1627     }
1628 }
1629
1630 pub fn trans_struct_def(ccx: &CrateContext, struct_def: @ast::StructDef) {
1631     // If this is a tuple-like struct, translate the constructor.
1632     match struct_def.ctor_id {
1633         // We only need to translate a constructor if there are fields;
1634         // otherwise this is a unit-like struct.
1635         Some(ctor_id) if struct_def.fields.len() > 0 => {
1636             let llfndecl = get_item_val(ccx, ctor_id);
1637             trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1638                                ctor_id, None, llfndecl);
1639         }
1640         Some(_) | None => {}
1641     }
1642 }
1643
1644 // Translate a module. Doing this amounts to translating the items in the
1645 // module; there ends up being no artifact (aside from linkage names) of
1646 // separate modules in the compiled program.  That's because modules exist
1647 // only as a convenience for humans working with the code, to organize names
1648 // and control visibility.
1649 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1650     let _icx = push_ctxt("trans_mod");
1651     for item in m.items.iter() {
1652         trans_item(ccx, *item);
1653     }
1654 }
1655
1656 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
1657                       llfn: ValueRef) {
1658     ccx.item_symbols.borrow_mut().insert(node_id, sym);
1659
1660     if !ccx.reachable.contains(&node_id) {
1661         lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1662     }
1663
1664     if is_entry_fn(ccx.sess(), node_id) && !ccx.sess().building_library.get() {
1665         create_entry_wrapper(ccx, sp, llfn);
1666     }
1667 }
1668
1669 fn register_fn(ccx: &CrateContext,
1670                sp: Span,
1671                sym: ~str,
1672                node_id: ast::NodeId,
1673                node_type: ty::t)
1674                -> ValueRef {
1675     let f = match ty::get(node_type).sty {
1676         ty::ty_bare_fn(ref f) => {
1677             assert!(f.abi == Rust || f.abi == RustIntrinsic);
1678             f
1679         }
1680         _ => fail!("expected bare rust fn or an intrinsic")
1681     };
1682
1683     let llfn = decl_rust_fn(ccx,
1684                             false,
1685                             f.sig.inputs.as_slice(),
1686                             f.sig.output,
1687                             sym);
1688     finish_register_fn(ccx, sp, sym, node_id, llfn);
1689     llfn
1690 }
1691
1692 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1693 pub fn register_fn_llvmty(ccx: &CrateContext,
1694                           sp: Span,
1695                           sym: ~str,
1696                           node_id: ast::NodeId,
1697                           cc: lib::llvm::CallConv,
1698                           fn_ty: Type,
1699                           output: ty::t) -> ValueRef {
1700     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1701
1702     let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty, output);
1703     finish_register_fn(ccx, sp, sym, node_id, llfn);
1704     llfn
1705 }
1706
1707 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1708     match *sess.entry_fn.borrow() {
1709         Some((entry_id, _)) => node_id == entry_id,
1710         None => false
1711     }
1712 }
1713
1714 // Create a _rust_main(args: ~[str]) function which will be called from the
1715 // runtime rust_start function
1716 pub fn create_entry_wrapper(ccx: &CrateContext,
1717                            _sp: Span,
1718                            main_llfn: ValueRef) {
1719     let et = ccx.sess().entry_type.get().unwrap();
1720     match et {
1721         session::EntryMain => {
1722             create_entry_fn(ccx, main_llfn, true);
1723         }
1724         session::EntryStart => create_entry_fn(ccx, main_llfn, false),
1725         session::EntryNone => {}    // Do nothing.
1726     }
1727
1728     fn create_entry_fn(ccx: &CrateContext,
1729                        rust_main: ValueRef,
1730                        use_start_lang_item: bool) {
1731         let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1732                                &ccx.int_type);
1733
1734         let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1735         let llbb = "top".with_c_str(|buf| {
1736             unsafe {
1737                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1738             }
1739         });
1740         let bld = ccx.builder.b;
1741         unsafe {
1742             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1743
1744             let (start_fn, args) = if use_start_lang_item {
1745                 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1746                     Ok(id) => id,
1747                     Err(s) => { ccx.sess().fatal(s); }
1748                 };
1749                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1750                     get_item_val(ccx, start_def_id.node)
1751                 } else {
1752                     let start_fn_type = csearch::get_type(ccx.tcx(),
1753                                                           start_def_id).ty;
1754                     trans_external_path(ccx, start_def_id, start_fn_type)
1755                 };
1756
1757                 let args = {
1758                     let opaque_rust_main = "rust_main".with_c_str(|buf| {
1759                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1760                     });
1761
1762                     vec!(
1763                         opaque_rust_main,
1764                         llvm::LLVMGetParam(llfn, 0),
1765                         llvm::LLVMGetParam(llfn, 1)
1766                      )
1767                 };
1768                 (start_fn, args)
1769             } else {
1770                 debug!("using user-defined start fn");
1771                 let args = vec!(
1772                     llvm::LLVMGetParam(llfn, 0 as c_uint),
1773                     llvm::LLVMGetParam(llfn, 1 as c_uint)
1774                 );
1775
1776                 (rust_main, args)
1777             };
1778
1779             let result = llvm::LLVMBuildCall(bld,
1780                                              start_fn,
1781                                              args.as_ptr(),
1782                                              args.len() as c_uint,
1783                                              noname());
1784
1785             llvm::LLVMBuildRet(bld, result);
1786         }
1787     }
1788 }
1789
1790 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1791                  ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
1792     match attr::first_attr_value_str_by_name(attrs, "export_name") {
1793         // Use provided name
1794         Some(name) => name.get().to_owned(),
1795
1796         _ => ccx.tcx.map.with_path(id, |mut path| {
1797             if attr::contains_name(attrs, "no_mangle") {
1798                 // Don't mangle
1799                 path.last().unwrap().to_str()
1800             } else {
1801                 // Usual name mangling
1802                 mangle_exported_name(ccx, path, ty, id)
1803             }
1804         })
1805     }
1806 }
1807
1808 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
1809     debug!("get_item_val(id=`{:?}`)", id);
1810
1811     match ccx.item_vals.borrow().find_copy(&id) {
1812         Some(v) => return v,
1813         None => {}
1814     }
1815
1816     let mut foreign = false;
1817     let item = ccx.tcx.map.get(id);
1818     let val = match item {
1819         ast_map::NodeItem(i) => {
1820             let ty = ty::node_id_to_type(ccx.tcx(), i.id);
1821             let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1822
1823             let v = match i.node {
1824                 ast::ItemStatic(_, _, expr) => {
1825                     // If this static came from an external crate, then
1826                     // we need to get the symbol from csearch instead of
1827                     // using the current crate's name/version
1828                     // information in the hash of the symbol
1829                     debug!("making {}", sym);
1830                     let (sym, is_local) = {
1831                         match ccx.external_srcs.borrow().find(&i.id) {
1832                             Some(&did) => {
1833                                 debug!("but found in other crate...");
1834                                 (csearch::get_symbol(&ccx.sess().cstore,
1835                                                      did), false)
1836                             }
1837                             None => (sym, true)
1838                         }
1839                     };
1840
1841                     // We need the translated value here, because for enums the
1842                     // LLVM type is not fully determined by the Rust type.
1843                     let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1844                     ccx.const_values.borrow_mut().insert(id, v);
1845                     let mut inlineable = inlineable;
1846
1847                     unsafe {
1848                         let llty = llvm::LLVMTypeOf(v);
1849                         let g = sym.with_c_str(|buf| {
1850                             llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1851                         });
1852
1853                         if !ccx.reachable.contains(&id) {
1854                             lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
1855                         }
1856
1857                         // Apply the `unnamed_addr` attribute if
1858                         // requested
1859                         if attr::contains_name(i.attrs.as_slice(),
1860                                                "address_insignificant") {
1861                             if ccx.reachable.contains(&id) {
1862                                 ccx.sess().span_bug(i.span,
1863                                     "insignificant static is reachable");
1864                             }
1865                             lib::llvm::SetUnnamedAddr(g, true);
1866
1867                             // This is a curious case where we must make
1868                             // all of these statics inlineable. If a
1869                             // global is tagged as
1870                             // address_insignificant, then LLVM won't
1871                             // coalesce globals unless they have an
1872                             // internal linkage type. This means that
1873                             // external crates cannot use this global.
1874                             // This is a problem for things like inner
1875                             // statics in generic functions, because the
1876                             // function will be inlined into another
1877                             // crate and then attempt to link to the
1878                             // static in the original crate, only to
1879                             // find that it's not there. On the other
1880                             // side of inlininig, the crates knows to
1881                             // not declare this static as
1882                             // available_externally (because it isn't)
1883                             inlineable = true;
1884                         }
1885
1886                         if attr::contains_name(i.attrs.as_slice(),
1887                                                "thread_local") {
1888                             lib::llvm::set_thread_local(g, true);
1889                         }
1890
1891                         if !inlineable {
1892                             debug!("{} not inlined", sym);
1893                             ccx.non_inlineable_statics.borrow_mut()
1894                                                       .insert(id);
1895                         }
1896
1897                         ccx.item_symbols.borrow_mut().insert(i.id, sym);
1898                         g
1899                     }
1900                 }
1901
1902                 ast::ItemFn(_, fn_style, _, _, _) => {
1903                     let llfn = if fn_style != ast::ExternFn {
1904                         register_fn(ccx, i.span, sym, i.id, ty)
1905                     } else {
1906                         foreign::register_rust_fn_with_foreign_abi(ccx,
1907                                                                    i.span,
1908                                                                    sym,
1909                                                                    i.id)
1910                     };
1911                     set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
1912                     llfn
1913                 }
1914
1915                 _ => fail!("get_item_val: weird result in table")
1916             };
1917
1918             match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
1919                                                      "link_section") {
1920                 Some(sect) => unsafe {
1921                     sect.get().with_c_str(|buf| {
1922                         llvm::LLVMSetSection(v, buf);
1923                     })
1924                 },
1925                 None => ()
1926             }
1927
1928             v
1929         }
1930
1931         ast_map::NodeTraitMethod(trait_method) => {
1932             debug!("get_item_val(): processing a NodeTraitMethod");
1933             match *trait_method {
1934                 ast::Required(_) => {
1935                     ccx.sess().bug("unexpected variant: required trait method in \
1936                                    get_item_val()");
1937                 }
1938                 ast::Provided(m) => {
1939                     register_method(ccx, id, m)
1940                 }
1941             }
1942         }
1943
1944         ast_map::NodeMethod(m) => {
1945             register_method(ccx, id, m)
1946         }
1947
1948         ast_map::NodeForeignItem(ni) => {
1949             foreign = true;
1950
1951             match ni.node {
1952                 ast::ForeignItemFn(..) => {
1953                     let abi = ccx.tcx.map.get_foreign_abi(id);
1954                     foreign::register_foreign_item_fn(ccx, abi, ni)
1955                 }
1956                 ast::ForeignItemStatic(..) => {
1957                     foreign::register_static(ccx, ni)
1958                 }
1959             }
1960         }
1961
1962         ast_map::NodeVariant(ref v) => {
1963             let llfn;
1964             let args = match v.node.kind {
1965                 ast::TupleVariantKind(ref args) => args,
1966                 ast::StructVariantKind(_) => {
1967                     fail!("struct variant kind unexpected in get_item_val")
1968                 }
1969             };
1970             assert!(args.len() != 0u);
1971             let ty = ty::node_id_to_type(ccx.tcx(), id);
1972             let parent = ccx.tcx.map.get_parent(id);
1973             let enm = ccx.tcx.map.expect_item(parent);
1974             let sym = exported_name(ccx,
1975                                     id,
1976                                     ty,
1977                                     enm.attrs.as_slice());
1978
1979             llfn = match enm.node {
1980                 ast::ItemEnum(_, _) => {
1981                     register_fn(ccx, (*v).span, sym, id, ty)
1982                 }
1983                 _ => fail!("NodeVariant, shouldn't happen")
1984             };
1985             set_inline_hint(llfn);
1986             llfn
1987         }
1988
1989         ast_map::NodeStructCtor(struct_def) => {
1990             // Only register the constructor if this is a tuple-like struct.
1991             let ctor_id = match struct_def.ctor_id {
1992                 None => {
1993                     ccx.sess().bug("attempt to register a constructor of \
1994                                     a non-tuple-like struct")
1995                 }
1996                 Some(ctor_id) => ctor_id,
1997             };
1998             let parent = ccx.tcx.map.get_parent(id);
1999             let struct_item = ccx.tcx.map.expect_item(parent);
2000             let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2001             let sym = exported_name(ccx,
2002                                     id,
2003                                     ty,
2004                                     struct_item.attrs
2005                                                .as_slice());
2006             let llfn = register_fn(ccx, struct_item.span,
2007                                    sym, ctor_id, ty);
2008             set_inline_hint(llfn);
2009             llfn
2010         }
2011
2012         ref variant => {
2013             ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2014                            variant))
2015         }
2016     };
2017
2018     // foreign items (extern fns and extern statics) don't have internal
2019     // linkage b/c that doesn't quite make sense. Otherwise items can
2020     // have internal linkage if they're not reachable.
2021     if !foreign && !ccx.reachable.contains(&id) {
2022         lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2023     }
2024
2025     ccx.item_vals.borrow_mut().insert(id, val);
2026     val
2027 }
2028
2029 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2030                    m: &ast::Method) -> ValueRef {
2031     let mty = ty::node_id_to_type(ccx.tcx(), id);
2032
2033     let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2034
2035     let llfn = register_fn(ccx, m.span, sym, id, mty);
2036     set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2037     llfn
2038 }
2039
2040 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2041     unsafe {
2042         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2043     }
2044 }
2045
2046 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2047     -> encoder::EncodeParams<'r> {
2048
2049         let diag = cx.sess().diagnostic();
2050         let item_symbols = &cx.item_symbols;
2051         let link_meta = &cx.link_meta;
2052         encoder::EncodeParams {
2053             diag: diag,
2054             tcx: cx.tcx(),
2055             reexports2: cx.exp_map2,
2056             item_symbols: item_symbols,
2057             non_inlineable_statics: &cx.non_inlineable_statics,
2058             link_meta: link_meta,
2059             cstore: &cx.sess().cstore,
2060             encode_inlined_item: ie,
2061         }
2062 }
2063
2064 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2065     use flate;
2066
2067     if !cx.sess().building_library.get() {
2068         return Vec::new()
2069     }
2070
2071     let encode_inlined_item: encoder::EncodeInlinedItem =
2072         |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii, &cx.maps);
2073
2074     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2075     let metadata = encoder::encode_metadata(encode_parms, krate);
2076     let compressed = encoder::metadata_encoding_version +
2077                         match flate::deflate_bytes(metadata.as_slice()) {
2078                             Some(compressed) => compressed,
2079                             None => cx.sess().fatal(format!("failed to compress metadata", ))
2080                         }.as_slice();
2081     let llmeta = C_bytes(cx, compressed);
2082     let llconst = C_struct(cx, [llmeta], false);
2083     let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2084                        cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2085     let llglobal = name.with_c_str(|buf| {
2086         unsafe {
2087             llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2088         }
2089     });
2090     unsafe {
2091         llvm::LLVMSetInitializer(llglobal, llconst);
2092         cx.sess().targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
2093             llvm::LLVMSetSection(llglobal, buf)
2094         });
2095     }
2096     return metadata;
2097 }
2098
2099 pub fn trans_crate(krate: ast::Crate,
2100                    analysis: CrateAnalysis,
2101                    output: &OutputFilenames) -> (ty::ctxt, CrateTranslation) {
2102     let CrateAnalysis { ty_cx: tcx, exp_map2, maps, reachable, .. } = analysis;
2103
2104     // Before we touch LLVM, make sure that multithreading is enabled.
2105     unsafe {
2106         use sync::one::{Once, ONCE_INIT};
2107         static mut INIT: Once = ONCE_INIT;
2108         static mut POISONED: bool = false;
2109         INIT.doit(|| {
2110             if llvm::LLVMStartMultithreaded() != 1 {
2111                 // use an extra bool to make sure that all future usage of LLVM
2112                 // cannot proceed despite the Once not running more than once.
2113                 POISONED = true;
2114             }
2115         });
2116
2117         if POISONED {
2118             tcx.sess.bug("couldn't enable multi-threaded LLVM");
2119         }
2120     }
2121
2122     let link_meta = link::build_link_meta(&krate, output.out_filestem);
2123
2124     // Append ".rs" to crate name as LLVM module identifier.
2125     //
2126     // LLVM code generator emits a ".file filename" directive
2127     // for ELF backends. Value of the "filename" is set as the
2128     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
2129     // crashes if the module identifer is same as other symbols
2130     // such as a function name in the module.
2131     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2132     let llmod_id = link_meta.crateid.name + ".rs";
2133
2134     let ccx = CrateContext::new(llmod_id, tcx, exp_map2, maps,
2135                                 Sha256::new(), link_meta, reachable);
2136     {
2137         let _icx = push_ctxt("text");
2138         trans_mod(&ccx, &krate.module);
2139     }
2140
2141     glue::emit_tydescs(&ccx);
2142     if ccx.sess().opts.debuginfo != NoDebugInfo {
2143         debuginfo::finalize(&ccx);
2144     }
2145
2146     // Translate the metadata.
2147     let metadata = write_metadata(&ccx, &krate);
2148     if ccx.sess().trans_stats() {
2149         println!("--- trans stats ---");
2150         println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2151         println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2152         println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2153         println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2154
2155         println!("n_fns: {}", ccx.stats.n_fns.get());
2156         println!("n_monos: {}", ccx.stats.n_monos.get());
2157         println!("n_inlines: {}", ccx.stats.n_inlines.get());
2158         println!("n_closures: {}", ccx.stats.n_closures.get());
2159         println!("fn stats:");
2160         ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2161             insns_b.cmp(&insns_a)
2162         });
2163         for tuple in ccx.stats.fn_stats.borrow().iter() {
2164             match *tuple {
2165                 (ref name, ms, insns) => {
2166                     println!("{} insns, {} ms, {}", insns, ms, *name);
2167                 }
2168             }
2169         }
2170     }
2171     if ccx.sess().count_llvm_insns() {
2172         for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2173             println!("{:7u} {}", *v, *k);
2174         }
2175     }
2176
2177     let llcx = ccx.llcx;
2178     let link_meta = ccx.link_meta.clone();
2179     let llmod = ccx.llmod;
2180
2181     let mut reachable: Vec<~str> = ccx.reachable.iter().filter_map(|id| {
2182         ccx.item_symbols.borrow().find(id).map(|s| s.to_owned())
2183     }).collect();
2184
2185     // Make sure that some other crucial symbols are not eliminated from the
2186     // module. This includes the main function, the crate map (used for debug
2187     // log settings and I/O), and finally the curious rust_stack_exhausted
2188     // symbol. This symbol is required for use by the libmorestack library that
2189     // we link in, so we must ensure that this symbol is not internalized (if
2190     // defined in the crate).
2191     reachable.push(~"main");
2192     reachable.push(~"rust_stack_exhausted");
2193     reachable.push(~"rust_eh_personality"); // referenced from .eh_frame section on some platforms
2194     reachable.push(~"rust_eh_personality_catch"); // referenced from rt/rust_try.ll
2195
2196     let metadata_module = ccx.metadata_llmod;
2197
2198     (ccx.tcx, CrateTranslation {
2199         context: llcx,
2200         module: llmod,
2201         link: link_meta,
2202         metadata_module: metadata_module,
2203         metadata: metadata,
2204         reachable: reachable,
2205     })
2206 }