]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
Change finalize -> drop.
[rust.git] / src / librustc / middle / trans / base.rs
1 // Copyright 2012-2013 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 many TypeRefs correspond to one ty::t; for instance, tup(int, int,
24 //     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25
26 use core::prelude::*;
27
28 use back::link::{mangle_exported_name};
29 use back::{link, abi};
30 use driver::session;
31 use driver::session::Session;
32 use lib::llvm::{ContextRef, ModuleRef, ValueRef, BasicBlockRef};
33 use lib::llvm::{llvm, True};
34 use lib;
35 use metadata::common::LinkMeta;
36 use metadata::{csearch, cstore, encoder};
37 use middle::astencode;
38 use middle::resolve;
39 use middle::trans::_match;
40 use middle::trans::adt;
41 use middle::trans::base;
42 use middle::trans::build::*;
43 use middle::trans::callee;
44 use middle::trans::common::*;
45 use middle::trans::consts;
46 use middle::trans::controlflow;
47 use middle::trans::datum;
48 use middle::trans::debuginfo;
49 use middle::trans::expr;
50 use middle::trans::foreign;
51 use middle::trans::glue;
52 use middle::trans::inline;
53 use middle::trans::machine;
54 use middle::trans::machine::{llalign_of_min, llsize_of};
55 use middle::trans::meth;
56 use middle::trans::monomorphize;
57 use middle::trans::reachable;
58 use middle::trans::shape::*;
59 use middle::trans::tvec;
60 use middle::trans::type_of;
61 use middle::trans::type_of::*;
62 use middle::ty;
63 use util::common::indenter;
64 use util::ppaux::{Repr, ty_to_str};
65
66 use middle::trans::type_::Type;
67
68 use core::hash;
69 use core::hashmap::{HashMap};
70 use core::int;
71 use core::io;
72 use core::libc::c_uint;
73 use core::str;
74 use core::uint;
75 use core::vec;
76 use core::local_data;
77 use extra::time;
78 use syntax::ast::ident;
79 use syntax::ast_map::{path, path_elt_to_str, path_name};
80 use syntax::ast_util::{local_def, path_to_ident};
81 use syntax::attr;
82 use syntax::codemap::span;
83 use syntax::parse::token;
84 use syntax::parse::token::{special_idents};
85 use syntax::print::pprust::stmt_to_str;
86 use syntax::visit;
87 use syntax::{ast, ast_util, codemap, ast_map};
88 use syntax::abi::{X86, X86_64, Arm, Mips};
89
90 pub use middle::trans::context::task_llcx;
91
92 fn task_local_insn_key(_v: @~[&'static str]) {}
93
94 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
95     unsafe {
96         let opt = local_data::local_data_get(task_local_insn_key);
97         if opt.is_some() {
98             blk(*opt.unwrap());
99         }
100     }
101 }
102
103 pub fn init_insn_ctxt() {
104     unsafe {
105         local_data::local_data_set(task_local_insn_key, @~[]);
106     }
107 }
108
109 pub struct _InsnCtxt { _x: () }
110
111 #[unsafe_destructor]
112 impl Drop for _InsnCtxt {
113     fn drop(&self) {
114         unsafe {
115             do local_data::local_data_modify(task_local_insn_key) |c| {
116                 do c.map_consume |@ctx| {
117                     let mut ctx = ctx;
118                     ctx.pop();
119                     @ctx
120                 }
121             }
122         }
123     }
124 }
125
126 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
127     debug!("new InsnCtxt: %s", s);
128     unsafe {
129         do local_data::local_data_modify(task_local_insn_key) |c| {
130             do c.map_consume |@ctx| {
131                 let mut ctx = ctx;
132                 ctx.push(s);
133                 @ctx
134             }
135         }
136     }
137     _InsnCtxt { _x: () }
138 }
139
140 fn fcx_has_nonzero_span(fcx: fn_ctxt) -> bool {
141     match fcx.span {
142         None => true,
143         Some(span) => *span.lo != 0 || *span.hi != 0
144     }
145 }
146
147 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
148     let llfn: ValueRef = do name.as_c_str |buf| {
149         unsafe {
150             llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
151         }
152     };
153
154     lib::llvm::SetFunctionCallConv(llfn, cc);
155     return llfn;
156 }
157
158 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
159     return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
160 }
161
162 // Only use this if you are going to actually define the function. It's
163 // not valid to simply declare a function as internal.
164 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: ~str, ty: Type) -> ValueRef {
165     let llfn = decl_cdecl_fn(llmod, name, ty);
166     lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
167     return llfn;
168 }
169
170 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: @str,
171                      cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
172     match externs.find_copy(&name) {
173         Some(n) => return n,
174         None => ()
175     }
176     let f = decl_fn(llmod, name, cc, ty);
177     externs.insert(name, f);
178     return f;
179 }
180
181 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
182                         name: @str, ty: Type) -> ValueRef {
183     match externs.find_copy(&name) {
184         Some(n) => return n,
185         None => ()
186     }
187     unsafe {
188         let c = do name.as_c_str |buf| {
189             llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
190         };
191         externs.insert(name, c);
192         return c;
193     }
194 }
195 pub fn umax(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
196     let _icx = push_ctxt("umax");
197     let cond = ICmp(cx, lib::llvm::IntULT, a, b);
198     return Select(cx, cond, b, a);
199 }
200
201 pub fn umin(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
202     let _icx = push_ctxt("umin");
203     let cond = ICmp(cx, lib::llvm::IntULT, a, b);
204     return Select(cx, cond, a, b);
205 }
206
207 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
208 // The type of the returned pointer is always i8*.  If you care about the
209 // return type, use bump_ptr().
210 pub fn ptr_offs(bcx: block, base: ValueRef, sz: ValueRef) -> ValueRef {
211     let _icx = push_ctxt("ptr_offs");
212     let raw = PointerCast(bcx, base, Type::i8p());
213     InBoundsGEP(bcx, raw, [sz])
214 }
215
216 // Increment a pointer by a given amount and then cast it to be a pointer
217 // to a given type.
218 pub fn bump_ptr(bcx: block, t: ty::t, base: ValueRef, sz: ValueRef) ->
219    ValueRef {
220     let _icx = push_ctxt("bump_ptr");
221     let ccx = bcx.ccx();
222     let bumped = ptr_offs(bcx, base, sz);
223     let typ = type_of(ccx, t).ptr_to();
224     PointerCast(bcx, bumped, typ)
225 }
226
227 // Returns a pointer to the body for the box. The box may be an opaque
228 // box. The result will be casted to the type of body_t, if it is statically
229 // known.
230 //
231 // The runtime equivalent is box_body() in "rust_internal.h".
232 pub fn opaque_box_body(bcx: block,
233                        body_t: ty::t,
234                        boxptr: ValueRef) -> ValueRef {
235     let _icx = push_ctxt("opaque_box_body");
236     let ccx = bcx.ccx();
237     let ty = type_of(ccx, body_t);
238     let ty = Type::box(ccx, &ty);
239     let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
240     GEPi(bcx, boxptr, [0u, abi::box_field_body])
241 }
242
243 // malloc_raw_dyn: allocates a box to contain a given type, but with a
244 // potentially dynamic size.
245 pub fn malloc_raw_dyn(bcx: block,
246                       t: ty::t,
247                       heap: heap,
248                       size: ValueRef) -> Result {
249     let _icx = push_ctxt("malloc_raw");
250     let ccx = bcx.ccx();
251
252     let (mk_fn, langcall) = match heap {
253         heap_managed | heap_managed_unique => {
254             (ty::mk_imm_box, bcx.tcx().lang_items.malloc_fn())
255         }
256         heap_exchange => {
257             (ty::mk_imm_uniq, bcx.tcx().lang_items.exchange_malloc_fn())
258         }
259     };
260
261     // Grab the TypeRef type of box_ptr_ty.
262     let box_ptr_ty = mk_fn(bcx.tcx(), t);
263     let llty = type_of(ccx, box_ptr_ty);
264
265     // Get the tydesc for the body:
266     let static_ti = get_tydesc(ccx, t);
267     glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
268
269     // Allocate space:
270     let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
271     let rval = alloca(bcx, Type::i8p());
272     let bcx = callee::trans_lang_call(
273         bcx,
274         langcall,
275         [tydesc, size],
276         expr::SaveIn(rval));
277     let r = rslt(bcx, PointerCast(bcx, Load(bcx, rval), llty));
278     maybe_set_managed_unique_rc(r.bcx, r.val, heap);
279     r
280 }
281
282 // malloc_raw: expects an unboxed type and returns a pointer to
283 // enough space for a box of that type.  This includes a rust_opaque_box
284 // header.
285 pub fn malloc_raw(bcx: block, t: ty::t, heap: heap) -> Result {
286     let ty = type_of(bcx.ccx(), t);
287     let size = llsize_of(bcx.ccx(), ty);
288     malloc_raw_dyn(bcx, t, heap, size)
289 }
290
291 pub struct MallocResult {
292     bcx: block,
293     box: ValueRef,
294     body: ValueRef
295 }
296
297 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
298 // and pulls out the body
299 pub fn malloc_general_dyn(bcx: block, t: ty::t, heap: heap, size: ValueRef)
300     -> MallocResult {
301     let _icx = push_ctxt("malloc_general");
302     let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
303     let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
304
305     MallocResult { bcx: bcx, box: llbox, body: body }
306 }
307
308 pub fn malloc_general(bcx: block, t: ty::t, heap: heap)
309     -> MallocResult {
310         let ty = type_of(bcx.ccx(), t);
311     malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
312 }
313 pub fn malloc_boxed(bcx: block, t: ty::t)
314     -> MallocResult {
315     malloc_general(bcx, t, heap_managed)
316 }
317
318 pub fn heap_for_unique(bcx: block, t: ty::t) -> heap {
319     if ty::type_contents(bcx.tcx(), t).contains_managed() {
320         heap_managed_unique
321     } else {
322         heap_exchange
323     }
324 }
325
326 pub fn maybe_set_managed_unique_rc(bcx: block, bx: ValueRef, heap: heap) {
327     if heap == heap_managed_unique {
328         // In cases where we are looking at a unique-typed allocation in the
329         // managed heap (thus have refcount 1 from the managed allocator),
330         // such as a ~(@foo) or such. These need to have their refcount forced
331         // to -2 so the annihilator ignores them.
332         let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
333         let rc_val = C_int(bcx.ccx(), -2);
334         Store(bcx, rc_val, rc);
335     }
336 }
337
338 pub fn malloc_unique(bcx: block, t: ty::t)
339     -> MallocResult {
340     malloc_general(bcx, t, heap_for_unique(bcx, t))
341 }
342
343 // Type descriptor and type glue stuff
344
345 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
346     get_tydesc(ccx, t).tydesc
347 }
348
349 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
350     match ccx.tydescs.find(&t) {
351         Some(&inf) => {
352             return inf;
353         }
354         _ => { }
355     }
356
357     ccx.stats.n_static_tydescs += 1u;
358     let inf = glue::declare_tydesc(ccx, t);
359     ccx.tydescs.insert(t, inf);
360     return inf;
361 }
362
363 pub fn set_optimize_for_size(f: ValueRef) {
364     unsafe {
365         llvm::LLVMAddFunctionAttr(f,
366                                   lib::llvm::OptimizeForSizeAttribute
367                                     as c_uint,
368                                   0);
369     }
370 }
371
372 pub fn set_no_inline(f: ValueRef) {
373     unsafe {
374         llvm::LLVMAddFunctionAttr(f,
375                                   lib::llvm::NoInlineAttribute as c_uint,
376                                   0);
377     }
378 }
379
380 pub fn set_no_unwind(f: ValueRef) {
381     unsafe {
382         llvm::LLVMAddFunctionAttr(f,
383                                   lib::llvm::NoUnwindAttribute as c_uint,
384                                   0);
385     }
386 }
387
388 // Tell LLVM to emit the information necessary to unwind the stack for the
389 // function f.
390 pub fn set_uwtable(f: ValueRef) {
391     unsafe {
392         llvm::LLVMAddFunctionAttr(f,
393                                   lib::llvm::UWTableAttribute as c_uint,
394                                   0);
395     }
396 }
397
398 pub fn set_inline_hint(f: ValueRef) {
399     unsafe {
400         llvm::LLVMAddFunctionAttr(f,
401                                   lib::llvm::InlineHintAttribute as c_uint,
402                                   0);
403     }
404 }
405
406 pub fn set_inline_hint_if_appr(attrs: &[ast::attribute],
407                                llfn: ValueRef) {
408     match attr::find_inline_attr(attrs) {
409       attr::ia_hint => set_inline_hint(llfn),
410       attr::ia_always => set_always_inline(llfn),
411       attr::ia_never => set_no_inline(llfn),
412       attr::ia_none => { /* fallthrough */ }
413     }
414 }
415
416 pub fn set_always_inline(f: ValueRef) {
417     unsafe {
418         llvm::LLVMAddFunctionAttr(f,
419                                   lib::llvm::AlwaysInlineAttribute as c_uint,
420                                   0);
421     }
422 }
423
424 pub fn set_fixed_stack_segment(f: ValueRef) {
425     unsafe {
426         llvm::LLVMAddFunctionAttr(f, 0, 1 << (39 - 32));
427     }
428 }
429
430 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
431     if ty::type_is_structural(t) {
432         set_optimize_for_size(f);
433     } else { set_always_inline(f); }
434 }
435
436 // Double-check that we never ask LLVM to declare the same symbol twice. It
437 // silently mangles such symbols, breaking our linkage model.
438 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
439     if ccx.all_llvm_symbols.contains(&sym) {
440         ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
441     }
442     ccx.all_llvm_symbols.insert(sym);
443 }
444
445
446 pub fn get_res_dtor(ccx: @mut CrateContext,
447                     did: ast::def_id,
448                     parent_id: ast::def_id,
449                     substs: &[ty::t])
450                  -> ValueRef {
451     let _icx = push_ctxt("trans_res_dtor");
452     if !substs.is_empty() {
453         let did = if did.crate != ast::local_crate {
454             inline::maybe_instantiate_inline(ccx, did, true)
455         } else {
456             did
457         };
458         assert_eq!(did.crate, ast::local_crate);
459         let tsubsts = ty::substs { self_r: None, self_ty: None,
460                                   tps: /*bad*/ substs.to_owned() };
461         let (val, _) = monomorphize::monomorphic_fn(ccx,
462                                                     did,
463                                                     &tsubsts,
464                                                     None,
465                                                     None,
466                                                     None);
467
468         val
469     } else if did.crate == ast::local_crate {
470         get_item_val(ccx, did.node)
471     } else {
472         let tcx = ccx.tcx;
473         let name = csearch::get_symbol(ccx.sess.cstore, did);
474         let class_ty = ty::subst_tps(tcx,
475                                      substs,
476                                      None,
477                                      ty::lookup_item_type(tcx, parent_id).ty);
478         let llty = type_of_dtor(ccx, class_ty);
479         let name = name.to_managed(); // :-(
480         get_extern_fn(&mut ccx.externs,
481                       ccx.llmod,
482                       name,
483                       lib::llvm::CCallConv,
484                       llty)
485     }
486 }
487
488 // Structural comparison: a rather involved form of glue.
489 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
490     if cx.sess.opts.save_temps {
491         let _: () = str::as_c_str(s, |buf| {
492             unsafe {
493                 llvm::LLVMSetValueName(v, buf)
494             }
495         });
496     }
497 }
498
499
500 // Used only for creating scalar comparison glue.
501 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
502
503 // NB: This produces an i1, not a Rust bool (i8).
504 pub fn compare_scalar_types(cx: block,
505                             lhs: ValueRef,
506                             rhs: ValueRef,
507                             t: ty::t,
508                             op: ast::binop)
509                          -> Result {
510     let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
511
512     match ty::get(t).sty {
513         ty::ty_nil => rslt(cx, f(nil_type)),
514         ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
515         ty::ty_int(_) => rslt(cx, f(signed_int)),
516         ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
517         ty::ty_float(_) => rslt(cx, f(floating_point)),
518         ty::ty_type => {
519             rslt(
520                 controlflow::trans_fail(
521                     cx, None,
522                     @"attempt to compare values of type type"),
523                 C_nil())
524         }
525         _ => {
526             // Should never get here, because t is scalar.
527             cx.sess().bug("non-scalar type passed to \
528                            compare_scalar_types")
529         }
530     }
531 }
532
533
534 // A helper function to do the actual comparison of scalar values.
535 pub fn compare_scalar_values(cx: block,
536                              lhs: ValueRef,
537                              rhs: ValueRef,
538                              nt: scalar_type,
539                              op: ast::binop)
540                           -> ValueRef {
541     let _icx = push_ctxt("compare_scalar_values");
542     fn die(cx: block) -> ! {
543         cx.tcx().sess.bug("compare_scalar_values: must be a\
544                            comparison operator");
545     }
546     match nt {
547       nil_type => {
548         // We don't need to do actual comparisons for nil.
549         // () == () holds but () < () does not.
550         match op {
551           ast::eq | ast::le | ast::ge => return C_i1(true),
552           ast::ne | ast::lt | ast::gt => return C_i1(false),
553           // refinements would be nice
554           _ => die(cx)
555         }
556       }
557       floating_point => {
558         let cmp = match op {
559           ast::eq => lib::llvm::RealOEQ,
560           ast::ne => lib::llvm::RealUNE,
561           ast::lt => lib::llvm::RealOLT,
562           ast::le => lib::llvm::RealOLE,
563           ast::gt => lib::llvm::RealOGT,
564           ast::ge => lib::llvm::RealOGE,
565           _ => die(cx)
566         };
567         return FCmp(cx, cmp, lhs, rhs);
568       }
569       signed_int => {
570         let cmp = match op {
571           ast::eq => lib::llvm::IntEQ,
572           ast::ne => lib::llvm::IntNE,
573           ast::lt => lib::llvm::IntSLT,
574           ast::le => lib::llvm::IntSLE,
575           ast::gt => lib::llvm::IntSGT,
576           ast::ge => lib::llvm::IntSGE,
577           _ => die(cx)
578         };
579         return ICmp(cx, cmp, lhs, rhs);
580       }
581       unsigned_int => {
582         let cmp = match op {
583           ast::eq => lib::llvm::IntEQ,
584           ast::ne => lib::llvm::IntNE,
585           ast::lt => lib::llvm::IntULT,
586           ast::le => lib::llvm::IntULE,
587           ast::gt => lib::llvm::IntUGT,
588           ast::ge => lib::llvm::IntUGE,
589           _ => die(cx)
590         };
591         return ICmp(cx, cmp, lhs, rhs);
592       }
593     }
594 }
595
596 pub type val_pair_fn = @fn(block, ValueRef, ValueRef) -> block;
597 pub type val_and_ty_fn = @fn(block, ValueRef, ty::t) -> block;
598
599 pub fn load_inbounds(cx: block, p: ValueRef, idxs: &[uint]) -> ValueRef {
600     return Load(cx, GEPi(cx, p, idxs));
601 }
602
603 pub fn store_inbounds(cx: block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
604     Store(cx, v, GEPi(cx, p, idxs));
605 }
606
607 // Iterates through the elements of a structural type.
608 pub fn iter_structural_ty(cx: block, av: ValueRef, t: ty::t,
609                           f: val_and_ty_fn) -> block {
610     let _icx = push_ctxt("iter_structural_ty");
611
612     fn iter_variant(cx: block, repr: &adt::Repr, av: ValueRef,
613                     variant: ty::VariantInfo,
614                     tps: &[ty::t], f: val_and_ty_fn) -> block {
615         let _icx = push_ctxt("iter_variant");
616         let tcx = cx.tcx();
617         let mut cx = cx;
618
619         for variant.args.iter().enumerate().advance |(i, &arg)| {
620             cx = f(cx,
621                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
622                    ty::subst_tps(tcx, tps, None, arg));
623         }
624         return cx;
625     }
626
627     let mut cx = cx;
628     match ty::get(t).sty {
629       ty::ty_struct(*) => {
630           let repr = adt::represent_type(cx.ccx(), t);
631           do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
632               for field_tys.iter().enumerate().advance |(i, field_ty)| {
633                   let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
634                   cx = f(cx, llfld_a, field_ty.mt.ty);
635               }
636           }
637       }
638       ty::ty_estr(ty::vstore_fixed(_)) |
639       ty::ty_evec(_, ty::vstore_fixed(_)) => {
640         let (base, len) = tvec::get_base_and_len(cx, av, t);
641         cx = tvec::iter_vec_raw(cx, base, t, len, f);
642       }
643       ty::ty_tup(ref args) => {
644           let repr = adt::represent_type(cx.ccx(), t);
645           for args.iter().enumerate().advance |(i, arg)| {
646               let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
647               cx = f(cx, llfld_a, *arg);
648           }
649       }
650       ty::ty_enum(tid, ref substs) => {
651           let ccx = cx.ccx();
652
653           let repr = adt::represent_type(ccx, t);
654           let variants = ty::enum_variants(ccx.tcx, tid);
655           let n_variants = (*variants).len();
656
657           // NB: we must hit the discriminant first so that structural
658           // comparison know not to proceed when the discriminants differ.
659
660           match adt::trans_switch(cx, repr, av) {
661               (_match::single, None) => {
662                   cx = iter_variant(cx, repr, av, variants[0],
663                                     substs.tps, f);
664               }
665               (_match::switch, Some(lldiscrim_a)) => {
666                   cx = f(cx, lldiscrim_a, ty::mk_int());
667                   let unr_cx = sub_block(cx, "enum-iter-unr");
668                   Unreachable(unr_cx);
669                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
670                                         n_variants);
671                   let next_cx = sub_block(cx, "enum-iter-next");
672
673                   for (*variants).iter().advance |variant| {
674                       let variant_cx =
675                           sub_block(cx, ~"enum-iter-variant-" +
676                                     int::to_str(variant.disr_val));
677                       let variant_cx =
678                           iter_variant(variant_cx, repr, av, *variant,
679                                        substs.tps, f);
680                       match adt::trans_case(cx, repr, variant.disr_val) {
681                           _match::single_result(r) => {
682                               AddCase(llswitch, r.val, variant_cx.llbb)
683                           }
684                           _ => ccx.sess.unimpl("value from adt::trans_case \
685                                                 in iter_structural_ty")
686                       }
687                       Br(variant_cx, next_cx.llbb);
688                   }
689                   cx = next_cx;
690               }
691               _ => ccx.sess.unimpl("value from adt::trans_switch \
692                                     in iter_structural_ty")
693           }
694       }
695       _ => cx.sess().unimpl("type in iter_structural_ty")
696     }
697     return cx;
698 }
699
700 pub fn cast_shift_expr_rhs(cx: block, op: ast::binop,
701                            lhs: ValueRef, rhs: ValueRef) -> ValueRef {
702     cast_shift_rhs(op, lhs, rhs,
703                    |a,b| Trunc(cx, a, b),
704                    |a,b| ZExt(cx, a, b))
705 }
706
707 pub fn cast_shift_const_rhs(op: ast::binop,
708                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
709     cast_shift_rhs(op, lhs, rhs,
710                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
711                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
712 }
713
714 pub fn cast_shift_rhs(op: ast::binop,
715                       lhs: ValueRef, rhs: ValueRef,
716                       trunc: &fn(ValueRef, Type) -> ValueRef,
717                       zext: &fn(ValueRef, Type) -> ValueRef)
718                    -> ValueRef {
719     // Shifts may have any size int on the rhs
720     unsafe {
721         if ast_util::is_shift_binop(op) {
722             let rhs_llty = val_ty(rhs);
723             let lhs_llty = val_ty(lhs);
724             let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
725             let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
726             if lhs_sz < rhs_sz {
727                 trunc(rhs, lhs_llty)
728             } else if lhs_sz > rhs_sz {
729                 // FIXME (#1877: If shifting by negative
730                 // values becomes not undefined then this is wrong.
731                 zext(rhs, lhs_llty)
732             } else {
733                 rhs
734             }
735         } else {
736             rhs
737         }
738     }
739 }
740
741 pub fn fail_if_zero(cx: block, span: span, divrem: ast::binop,
742                     rhs: ValueRef, rhs_t: ty::t) -> block {
743     let text = if divrem == ast::div {
744         @"attempted to divide by zero"
745     } else {
746         @"attempted remainder with a divisor of zero"
747     };
748     let is_zero = match ty::get(rhs_t).sty {
749       ty::ty_int(t) => {
750         let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
751         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
752       }
753       ty::ty_uint(t) => {
754         let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
755         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
756       }
757       _ => {
758         cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
759                           ty_to_str(cx.ccx().tcx, rhs_t));
760       }
761     };
762     do with_cond(cx, is_zero) |bcx| {
763         controlflow::trans_fail(bcx, Some(span), text)
764     }
765 }
766
767 pub fn null_env_ptr(bcx: block) -> ValueRef {
768     C_null(Type::opaque_box(bcx.ccx()).ptr_to())
769 }
770
771 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::def_id, t: ty::t)
772     -> ValueRef {
773     let name = csearch::get_symbol(ccx.sess.cstore, did).to_managed(); // Sad
774     match ty::get(t).sty {
775       ty::ty_bare_fn(_) | ty::ty_closure(_) => {
776         let llty = type_of_fn_from_ty(ccx, t);
777         return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
778                              lib::llvm::CCallConv, llty);
779       }
780       _ => {
781         let llty = type_of(ccx, t);
782         return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
783       }
784     };
785 }
786
787 pub fn invoke(bcx: block, llfn: ValueRef, llargs: ~[ValueRef])
788            -> (ValueRef, block) {
789     let _icx = push_ctxt("invoke_");
790     if bcx.unreachable {
791         return (C_null(Type::i8()), bcx);
792     }
793
794     match bcx.node_info {
795         None => debug!("invoke at ???"),
796         Some(node_info) => {
797             debug!("invoke at %s",
798                    bcx.sess().codemap.span_to_str(node_info.span));
799         }
800     }
801
802     if need_invoke(bcx) {
803         unsafe {
804             debug!("invoking %x at %x",
805                    ::core::cast::transmute(llfn),
806                    ::core::cast::transmute(bcx.llbb));
807             for llargs.iter().advance |&llarg| {
808                 debug!("arg: %x", ::core::cast::transmute(llarg));
809             }
810         }
811         let normal_bcx = sub_block(bcx, "normal return");
812         let llresult = Invoke(bcx,
813                               llfn,
814                               llargs,
815                               normal_bcx.llbb,
816                               get_landing_pad(bcx));
817         return (llresult, normal_bcx);
818     } else {
819         unsafe {
820             debug!("calling %x at %x",
821                    ::core::cast::transmute(llfn),
822                    ::core::cast::transmute(bcx.llbb));
823             for llargs.iter().advance |&llarg| {
824                 debug!("arg: %x", ::core::cast::transmute(llarg));
825             }
826         }
827         let llresult = Call(bcx, llfn, llargs);
828         return (llresult, bcx);
829     }
830 }
831
832 pub fn need_invoke(bcx: block) -> bool {
833     if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
834         return false;
835     }
836
837     // Avoid using invoke if we are already inside a landing pad.
838     if bcx.is_lpad {
839         return false;
840     }
841
842     if have_cached_lpad(bcx) {
843         return true;
844     }
845
846     // Walk the scopes to look for cleanups
847     let mut cur = bcx;
848     loop {
849         match cur.kind {
850             block_scope(inf) => {
851                 let inf = &mut *inf; // FIXME(#5074) workaround old borrowck
852                 for inf.cleanups.iter().advance |cleanup| {
853                     match *cleanup {
854                         clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
855                             if cleanup_type == normal_exit_and_unwind {
856                                 return true;
857                             }
858                         }
859                     }
860                 }
861             }
862             _ => ()
863         }
864         cur = match cur.parent {
865           Some(next) => next,
866           None => return false
867         }
868     }
869 }
870
871 pub fn have_cached_lpad(bcx: block) -> bool {
872     let mut res = false;
873     do in_lpad_scope_cx(bcx) |inf| {
874         match inf.landing_pad {
875           Some(_) => res = true,
876           None => res = false
877         }
878     }
879     return res;
880 }
881
882 pub fn in_lpad_scope_cx(bcx: block, f: &fn(si: &mut scope_info)) {
883     let mut bcx = bcx;
884     loop {
885         {
886             match bcx.kind {
887                 block_scope(inf) => {
888                     let len = { // FIXME(#5074) workaround old borrowck
889                         let inf = &mut *inf;
890                         inf.cleanups.len()
891                     };
892                     if len > 0u || bcx.parent.is_none() {
893                         f(inf);
894                         return;
895                     }
896                 }
897                 _ => ()
898             }
899         }
900         bcx = block_parent(bcx);
901     }
902 }
903
904 pub fn get_landing_pad(bcx: block) -> BasicBlockRef {
905     let _icx = push_ctxt("get_landing_pad");
906
907     let mut cached = None;
908     let mut pad_bcx = bcx; // Guaranteed to be set below
909     do in_lpad_scope_cx(bcx) |inf| {
910         // If there is a valid landing pad still around, use it
911         match inf.landing_pad {
912           Some(target) => cached = Some(target),
913           None => {
914             pad_bcx = lpad_block(bcx, "unwind");
915             inf.landing_pad = Some(pad_bcx.llbb);
916           }
917         }
918     }
919     // Can't return from block above
920     match cached { Some(b) => return b, None => () }
921     // The landing pad return type (the type being propagated). Not sure what
922     // this represents but it's determined by the personality function and
923     // this is what the EH proposal example uses.
924     let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
925     // The exception handling personality function. This is the C++
926     // personality function __gxx_personality_v0, wrapped in our naming
927     // convention.
928     let personality = bcx.ccx().upcalls.rust_personality;
929     // The only landing pad clause will be 'cleanup'
930     let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
931     // The landing pad block is a cleanup
932     SetCleanup(pad_bcx, llretval);
933
934     // Because we may have unwound across a stack boundary, we must call into
935     // the runtime to figure out which stack segment we are on and place the
936     // stack limit back into the TLS.
937     Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []);
938
939     // We store the retval in a function-central alloca, so that calls to
940     // Resume can find it.
941     match bcx.fcx.personality {
942       Some(addr) => Store(pad_bcx, llretval, addr),
943       None => {
944         let addr = alloca(pad_bcx, val_ty(llretval));
945         bcx.fcx.personality = Some(addr);
946         Store(pad_bcx, llretval, addr);
947       }
948     }
949
950     // Unwind all parent scopes, and finish with a Resume instr
951     cleanup_and_leave(pad_bcx, None, None);
952     return pad_bcx.llbb;
953 }
954
955 pub fn find_bcx_for_scope(bcx: block, scope_id: ast::node_id) -> block {
956     let mut bcx_sid = bcx;
957     loop {
958         bcx_sid = match bcx_sid.node_info {
959             Some(NodeInfo { id, _ }) if id == scope_id => {
960                 return bcx_sid
961               }
962
963                 // FIXME(#6268, #6248) hacky cleanup for nested method calls
964                 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
965                     return bcx_sid
966                 }
967
968                 _ => {
969                     match bcx_sid.parent {
970                         None => bcx.tcx().sess.bug(
971                             fmt!("no enclosing scope with id %d", scope_id)),
972                         Some(bcx_par) => bcx_par
973                     }
974                 }
975             }
976         }
977     }
978
979
980 pub fn do_spill(bcx: block, v: ValueRef, t: ty::t) -> ValueRef {
981     if ty::type_is_bot(t) {
982         return C_null(Type::i8p());
983     }
984     let llptr = alloc_ty(bcx, t);
985     Store(bcx, v, llptr);
986     return llptr;
987 }
988
989 // Since this function does *not* root, it is the caller's responsibility to
990 // ensure that the referent is pointed to by a root.
991 pub fn do_spill_noroot(cx: block, v: ValueRef) -> ValueRef {
992     let llptr = alloca(cx, val_ty(v));
993     Store(cx, v, llptr);
994     return llptr;
995 }
996
997 pub fn spill_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
998     let _icx = push_ctxt("spill_if_immediate");
999     if ty::type_is_immediate(t) { return do_spill(cx, v, t); }
1000     return v;
1001 }
1002
1003 pub fn load_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
1004     let _icx = push_ctxt("load_if_immediate");
1005     if ty::type_is_immediate(t) { return Load(cx, v); }
1006     return v;
1007 }
1008
1009 pub fn trans_trace(bcx: block, sp_opt: Option<span>, trace_str: @str) {
1010     if !bcx.sess().trace() { return; }
1011     let _icx = push_ctxt("trans_trace");
1012     add_comment(bcx, trace_str);
1013     let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1014     let (V_filename, V_line) = match sp_opt {
1015       Some(sp) => {
1016         let sess = bcx.sess();
1017         let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1018         (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1019       }
1020       None => {
1021         (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1022       }
1023     };
1024     let ccx = bcx.ccx();
1025     let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1026     let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1027     let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1028     Call(bcx, ccx.upcalls.trace, args);
1029 }
1030
1031 pub fn build_return(bcx: block) {
1032     let _icx = push_ctxt("build_return");
1033     Br(bcx, bcx.fcx.llreturn);
1034 }
1035
1036 pub fn ignore_lhs(_bcx: block, local: @ast::local) -> bool {
1037     match local.node.pat.node {
1038         ast::pat_wild => true, _ => false
1039     }
1040 }
1041
1042 pub fn init_local(bcx: block, local: @ast::local) -> block {
1043
1044     debug!("init_local(bcx=%s, local.id=%?)",
1045            bcx.to_str(), local.node.id);
1046     let _indenter = indenter();
1047
1048     let _icx = push_ctxt("init_local");
1049     let ty = node_id_type(bcx, local.node.id);
1050
1051     debug!("ty=%s", bcx.ty_to_str(ty));
1052
1053     if ignore_lhs(bcx, local) {
1054         // Handle let _ = e; just like e;
1055         match local.node.init {
1056             Some(init) => {
1057               return expr::trans_into(bcx, init, expr::Ignore);
1058             }
1059             None => { return bcx; }
1060         }
1061     }
1062
1063     let llptr = match bcx.fcx.lllocals.find_copy(&local.node.id) {
1064         Some(v) => v,
1065         _ => {
1066             bcx.tcx().sess.span_bug(local.span,
1067                                     "init_local: Someone forgot to document why it's\
1068                                      safe to assume local.node.init must be local_mem!");
1069         }
1070     };
1071
1072     let mut bcx = bcx;
1073     match local.node.init {
1074         Some(init) => {
1075             bcx = expr::trans_into(bcx, init, expr::SaveIn(llptr));
1076         }
1077         _ => {
1078             zero_mem(bcx, llptr, ty);
1079         }
1080     }
1081
1082     // Make a note to drop this slot on the way out.
1083     debug!("adding clean for %?/%s to bcx=%s",
1084            local.node.id, bcx.ty_to_str(ty),
1085            bcx.to_str());
1086     add_clean(bcx, llptr, ty);
1087
1088     return _match::bind_irrefutable_pat(bcx,
1089                                        local.node.pat,
1090                                        llptr,
1091                                        false,
1092                                        _match::BindLocal);
1093 }
1094
1095 pub fn trans_stmt(cx: block, s: &ast::stmt) -> block {
1096     let _icx = push_ctxt("trans_stmt");
1097     debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1098
1099     if cx.sess().asm_comments() {
1100         add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1101     }
1102
1103     let mut bcx = cx;
1104     debuginfo::update_source_pos(cx, s.span);
1105
1106     match s.node {
1107         ast::stmt_expr(e, _) | ast::stmt_semi(e, _) => {
1108             bcx = expr::trans_into(cx, e, expr::Ignore);
1109         }
1110         ast::stmt_decl(d, _) => {
1111             match d.node {
1112                 ast::decl_local(ref local) => {
1113                     bcx = init_local(bcx, *local);
1114                     if cx.sess().opts.extra_debuginfo
1115                         && fcx_has_nonzero_span(bcx.fcx) {
1116                         debuginfo::create_local_var(bcx, *local);
1117                     }
1118                 }
1119                 ast::decl_item(i) => trans_item(cx.fcx.ccx, i)
1120             }
1121         }
1122         ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro")
1123     }
1124
1125     return bcx;
1126 }
1127
1128 // You probably don't want to use this one. See the
1129 // next three functions instead.
1130 pub fn new_block(cx: fn_ctxt, parent: Option<block>, kind: block_kind,
1131                  is_lpad: bool, name: &str, opt_node_info: Option<NodeInfo>)
1132     -> block {
1133
1134     let s = if cx.ccx.sess.opts.save_temps || cx.ccx.sess.opts.debuginfo {
1135         (cx.ccx.names)(name)
1136     } else {
1137         special_idents::invalid
1138     };
1139     unsafe {
1140         let llbb = str::as_c_str(cx.ccx.sess.str_of(s), |buf| {
1141             llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1142         });
1143         let bcx = mk_block(llbb,
1144                            parent,
1145                            kind,
1146                            is_lpad,
1147                            opt_node_info,
1148                            cx);
1149         for parent.iter().advance |cx| {
1150             if cx.unreachable { Unreachable(bcx); }
1151         };
1152         bcx
1153     }
1154 }
1155
1156 pub fn simple_block_scope() -> block_kind {
1157     block_scope(@mut scope_info {
1158         loop_break: None,
1159         loop_label: None,
1160         cleanups: ~[],
1161         cleanup_paths: ~[],
1162         landing_pad: None
1163     })
1164 }
1165
1166 // Use this when you're at the top block of a function or the like.
1167 pub fn top_scope_block(fcx: fn_ctxt, opt_node_info: Option<NodeInfo>)
1168                     -> block {
1169     return new_block(fcx, None, simple_block_scope(), false,
1170                   "function top level", opt_node_info);
1171 }
1172
1173 pub fn scope_block(bcx: block,
1174                    opt_node_info: Option<NodeInfo>,
1175                    n: &str) -> block {
1176     return new_block(bcx.fcx, Some(bcx), simple_block_scope(), bcx.is_lpad,
1177                   n, opt_node_info);
1178 }
1179
1180 pub fn loop_scope_block(bcx: block,
1181                         loop_break: block,
1182                         loop_label: Option<ident>,
1183                         n: &str,
1184                         opt_node_info: Option<NodeInfo>) -> block {
1185     return new_block(bcx.fcx, Some(bcx), block_scope(@mut scope_info {
1186         loop_break: Some(loop_break),
1187         loop_label: loop_label,
1188         cleanups: ~[],
1189         cleanup_paths: ~[],
1190         landing_pad: None
1191     }), bcx.is_lpad, n, opt_node_info);
1192 }
1193
1194 // Use this when creating a block for the inside of a landing pad.
1195 pub fn lpad_block(bcx: block, n: &str) -> block {
1196     new_block(bcx.fcx, Some(bcx), block_non_scope, true, n, None)
1197 }
1198
1199 // Use this when you're making a general CFG BB within a scope.
1200 pub fn sub_block(bcx: block, n: &str) -> block {
1201     new_block(bcx.fcx, Some(bcx), block_non_scope, bcx.is_lpad, n, None)
1202 }
1203
1204 pub fn raw_block(fcx: fn_ctxt, is_lpad: bool, llbb: BasicBlockRef) -> block {
1205     mk_block(llbb, None, block_non_scope, is_lpad, None, fcx)
1206 }
1207
1208
1209 // trans_block_cleanups: Go through all the cleanups attached to this
1210 // block and execute them.
1211 //
1212 // When translating a block that introduces new variables during its scope, we
1213 // need to make sure those variables go out of scope when the block ends.  We
1214 // do that by running a 'cleanup' function for each variable.
1215 // trans_block_cleanups runs all the cleanup functions for the block.
1216 pub fn trans_block_cleanups(bcx: block, cleanups: ~[cleanup]) -> block {
1217     trans_block_cleanups_(bcx, cleanups, false)
1218 }
1219
1220 pub fn trans_block_cleanups_(bcx: block,
1221                              cleanups: &[cleanup],
1222                              /* cleanup_cx: block, */
1223                              is_lpad: bool) -> block {
1224     let _icx = push_ctxt("trans_block_cleanups");
1225     // NB: Don't short-circuit even if this block is unreachable because
1226     // GC-based cleanup needs to the see that the roots are live.
1227     let no_lpads =
1228         bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1229     if bcx.unreachable && !no_lpads { return bcx; }
1230     let mut bcx = bcx;
1231     for cleanups.rev_iter().advance |cu| {
1232         match *cu {
1233             clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1234                 // Some types don't need to be cleaned up during
1235                 // landing pads because they can be freed en mass later
1236                 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1237                     bcx = cfn(bcx);
1238                 }
1239             }
1240         }
1241     }
1242     return bcx;
1243 }
1244
1245 // In the last argument, Some(block) mean jump to this block, and none means
1246 // this is a landing pad and leaving should be accomplished with a resume
1247 // instruction.
1248 pub fn cleanup_and_leave(bcx: block,
1249                          upto: Option<BasicBlockRef>,
1250                          leave: Option<BasicBlockRef>) {
1251     let _icx = push_ctxt("cleanup_and_leave");
1252     let mut cur = bcx;
1253     let mut bcx = bcx;
1254     let is_lpad = leave == None;
1255     loop {
1256         debug!("cleanup_and_leave: leaving %s", cur.to_str());
1257
1258         if bcx.sess().trace() {
1259             trans_trace(
1260                 bcx, None,
1261                 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1262         }
1263
1264         match cur.kind {
1265             block_scope(inf) if !inf.empty_cleanups() => {
1266                 let (sub_cx, dest, inf_cleanups) = {
1267                     let inf = &mut *inf;
1268                     let mut skip = 0;
1269                     let mut dest = None;
1270                     {
1271                         let r = vec::rfind((*inf).cleanup_paths, |cp| cp.target == leave);
1272                         for r.iter().advance |cp| {
1273                             if cp.size == inf.cleanups.len() {
1274                                 Br(bcx, cp.dest);
1275                                 return;
1276                             }
1277
1278                             skip = cp.size;
1279                             dest = Some(cp.dest);
1280                         }
1281                     }
1282                     let sub_cx = sub_block(bcx, "cleanup");
1283                     Br(bcx, sub_cx.llbb);
1284                     inf.cleanup_paths.push(cleanup_path {
1285                         target: leave,
1286                         size: inf.cleanups.len(),
1287                         dest: sub_cx.llbb
1288                     });
1289                     (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1290                 };
1291                 bcx = trans_block_cleanups_(sub_cx,
1292                                             inf_cleanups,
1293                                             is_lpad);
1294                 for dest.iter().advance |&dest| {
1295                     Br(bcx, dest);
1296                     return;
1297                 }
1298             }
1299             _ => ()
1300         }
1301
1302         match upto {
1303           Some(bb) => { if cur.llbb == bb { break; } }
1304           _ => ()
1305         }
1306         cur = match cur.parent {
1307           Some(next) => next,
1308           None => { assert!(upto.is_none()); break; }
1309         };
1310     }
1311     match leave {
1312       Some(target) => Br(bcx, target),
1313       None => { Resume(bcx, Load(bcx, bcx.fcx.personality.get())); }
1314     }
1315 }
1316
1317 pub fn cleanup_and_Br(bcx: block, upto: block, target: BasicBlockRef) {
1318     let _icx = push_ctxt("cleanup_and_Br");
1319     cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1320 }
1321
1322 pub fn leave_block(bcx: block, out_of: block) -> block {
1323     let _icx = push_ctxt("leave_block");
1324     let next_cx = sub_block(block_parent(out_of), "next");
1325     if bcx.unreachable { Unreachable(next_cx); }
1326     cleanup_and_Br(bcx, out_of, next_cx.llbb);
1327     next_cx
1328 }
1329
1330 pub fn with_scope(bcx: block,
1331                   opt_node_info: Option<NodeInfo>,
1332                   name: &str,
1333                   f: &fn(block) -> block) -> block {
1334     let _icx = push_ctxt("with_scope");
1335
1336     debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1337            bcx.to_str(), opt_node_info, name);
1338     let _indenter = indenter();
1339
1340     let scope_cx = scope_block(bcx, opt_node_info, name);
1341     Br(bcx, scope_cx.llbb);
1342     leave_block(f(scope_cx), scope_cx)
1343 }
1344
1345 pub fn with_scope_result(bcx: block,
1346                          opt_node_info: Option<NodeInfo>,
1347                          name: &str,
1348                          f: &fn(block) -> Result) -> Result {
1349     let _icx = push_ctxt("with_scope_result");
1350     let scope_cx = scope_block(bcx, opt_node_info, name);
1351     Br(bcx, scope_cx.llbb);
1352     let Result {bcx, val} = f(scope_cx);
1353     rslt(leave_block(bcx, scope_cx), val)
1354 }
1355
1356 pub fn with_scope_datumblock(bcx: block, opt_node_info: Option<NodeInfo>,
1357                              name: &str, f: &fn(block) -> datum::DatumBlock)
1358                           -> datum::DatumBlock {
1359     use middle::trans::datum::DatumBlock;
1360
1361     let _icx = push_ctxt("with_scope_result");
1362     let scope_cx = scope_block(bcx, opt_node_info, name);
1363     Br(bcx, scope_cx.llbb);
1364     let DatumBlock {bcx, datum} = f(scope_cx);
1365     DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1366 }
1367
1368 pub fn block_locals(b: &ast::blk, it: &fn(@ast::local)) {
1369     for b.node.stmts.iter().advance |s| {
1370         match s.node {
1371           ast::stmt_decl(d, _) => {
1372             match d.node {
1373               ast::decl_local(ref local) => it(*local),
1374               _ => {} /* fall through */
1375             }
1376           }
1377           _ => {} /* fall through */
1378         }
1379     }
1380 }
1381
1382 pub fn alloc_local(cx: block, local: @ast::local) -> block {
1383     let _icx = push_ctxt("alloc_local");
1384     let t = node_id_type(cx, local.node.id);
1385     let simple_name = match local.node.pat.node {
1386       ast::pat_ident(_, pth, None) => Some(path_to_ident(pth)),
1387       _ => None
1388     };
1389     let val = alloc_ty(cx, t);
1390     if cx.sess().opts.debuginfo {
1391         for simple_name.iter().advance |name| {
1392             str::as_c_str(cx.ccx().sess.str_of(*name), |buf| {
1393                 unsafe {
1394                     llvm::LLVMSetValueName(val, buf)
1395                 }
1396             });
1397         }
1398     }
1399     cx.fcx.lllocals.insert(local.node.id, val);
1400     cx
1401 }
1402
1403
1404 pub fn with_cond(bcx: block, val: ValueRef, f: &fn(block) -> block) -> block {
1405     let _icx = push_ctxt("with_cond");
1406     let next_cx = base::sub_block(bcx, "next");
1407     let cond_cx = base::sub_block(bcx, "cond");
1408     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1409     let after_cx = f(cond_cx);
1410     if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1411     next_cx
1412 }
1413
1414 pub fn call_memcpy(cx: block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1415     let _icx = push_ctxt("call_memcpy");
1416     let ccx = cx.ccx();
1417     let key = match ccx.sess.targ_cfg.arch {
1418         X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1419         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1420     };
1421     let memcpy = ccx.intrinsics.get_copy(&key);
1422     let src_ptr = PointerCast(cx, src, Type::i8p());
1423     let dst_ptr = PointerCast(cx, dst, Type::i8p());
1424     let size = IntCast(cx, n_bytes, ccx.int_type);
1425     let align = C_i32(align as i32);
1426     let volatile = C_i1(false);
1427     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]);
1428 }
1429
1430 pub fn memcpy_ty(bcx: block, dst: ValueRef, src: ValueRef, t: ty::t) {
1431     let _icx = push_ctxt("memcpy_ty");
1432     let ccx = bcx.ccx();
1433     if ty::type_is_structural(t) {
1434         let llty = type_of::type_of(ccx, t);
1435         let llsz = llsize_of(ccx, llty);
1436         let llalign = llalign_of_min(ccx, llty);
1437         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1438     } else {
1439         Store(bcx, Load(bcx, src), dst);
1440     }
1441 }
1442
1443 pub fn zero_mem(cx: block, llptr: ValueRef, t: ty::t) {
1444     let _icx = push_ctxt("zero_mem");
1445     let bcx = cx;
1446     let ccx = cx.ccx();
1447     let llty = type_of::type_of(ccx, t);
1448     memzero(bcx, llptr, llty);
1449 }
1450
1451 // Always use this function instead of storing a zero constant to the memory
1452 // in question. If you store a zero constant, LLVM will drown in vreg
1453 // allocation for large data structures, and the generated code will be
1454 // awful. (A telltale sign of this is large quantities of
1455 // `mov [byte ptr foo],0` in the generated code.)
1456 pub fn memzero(cx: block, llptr: ValueRef, ty: Type) {
1457     let _icx = push_ctxt("memzero");
1458     let ccx = cx.ccx();
1459
1460     let intrinsic_key = match ccx.sess.targ_cfg.arch {
1461         X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1462         X86_64 => "llvm.memset.p0i8.i64"
1463     };
1464
1465     let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1466     let llptr = PointerCast(cx, llptr, Type::i8().ptr_to());
1467     let llzeroval = C_u8(0);
1468     let size = IntCast(cx, machine::llsize_of(ccx, ty), ccx.int_type);
1469     let align = C_i32(llalign_of_min(ccx, ty) as i32);
1470     let volatile = C_i1(false);
1471     Call(cx, llintrinsicfn, [llptr, llzeroval, size, align, volatile]);
1472 }
1473
1474 pub fn alloc_ty(bcx: block, t: ty::t) -> ValueRef {
1475     let _icx = push_ctxt("alloc_ty");
1476     let ccx = bcx.ccx();
1477     let ty = type_of::type_of(ccx, t);
1478     assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1479     let val = alloca(bcx, ty);
1480     return val;
1481 }
1482
1483 pub fn alloca(cx: block, ty: Type) -> ValueRef {
1484     alloca_maybe_zeroed(cx, ty, false)
1485 }
1486
1487 pub fn alloca_maybe_zeroed(cx: block, ty: Type, zero: bool) -> ValueRef {
1488     let _icx = push_ctxt("alloca");
1489     if cx.unreachable {
1490         unsafe {
1491             return llvm::LLVMGetUndef(ty.to_ref());
1492         }
1493     }
1494     let initcx = base::raw_block(cx.fcx, false, cx.fcx.llstaticallocas);
1495     let p = Alloca(initcx, ty);
1496     if zero { memzero(initcx, p, ty); }
1497     p
1498 }
1499
1500 pub fn arrayalloca(cx: block, ty: Type, v: ValueRef) -> ValueRef {
1501     let _icx = push_ctxt("arrayalloca");
1502     if cx.unreachable {
1503         unsafe {
1504             return llvm::LLVMGetUndef(ty.to_ref());
1505         }
1506     }
1507     return ArrayAlloca(base::raw_block(cx.fcx, false, cx.fcx.llstaticallocas), ty, v);
1508 }
1509
1510 pub struct BasicBlocks {
1511     sa: BasicBlockRef,
1512     rt: BasicBlockRef
1513 }
1514
1515 // Creates the standard set of basic blocks for a function
1516 pub fn mk_standard_basic_blocks(llfn: ValueRef) -> BasicBlocks {
1517     unsafe {
1518         let cx = task_llcx();
1519         BasicBlocks {
1520             sa: str::as_c_str("static_allocas",
1521                            |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)),
1522             rt: str::as_c_str("return",
1523                            |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf))
1524         }
1525     }
1526 }
1527
1528 // Creates and returns space for, or returns the argument representing, the
1529 // slot where the return value of the function must go.
1530 pub fn make_return_pointer(fcx: fn_ctxt, output_type: ty::t) -> ValueRef {
1531     unsafe {
1532         if !ty::type_is_immediate(output_type) {
1533             llvm::LLVMGetParam(fcx.llfn, 0)
1534         } else {
1535             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1536             alloca(raw_block(fcx, false, fcx.llstaticallocas), lloutputtype)
1537         }
1538     }
1539 }
1540
1541 // NB: must keep 4 fns in sync:
1542 //
1543 //  - type_of_fn
1544 //  - create_llargs_for_fn_args.
1545 //  - new_fn_ctxt
1546 //  - trans_args
1547 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1548                         path: path,
1549                         llfndecl: ValueRef,
1550                         id: ast::node_id,
1551                         output_type: ty::t,
1552                         impl_id: Option<ast::def_id>,
1553                         param_substs: Option<@param_substs>,
1554                         sp: Option<span>)
1555                      -> fn_ctxt {
1556     for param_substs.iter().advance |p| { p.validate(); }
1557
1558     debug!("new_fn_ctxt_w_id(path=%s, id=%?, impl_id=%?, \
1559             param_substs=%s)",
1560            path_str(ccx.sess, path),
1561            id,
1562            impl_id,
1563            param_substs.repr(ccx.tcx));
1564
1565     let llbbs = mk_standard_basic_blocks(llfndecl);
1566
1567     let substd_output_type = match param_substs {
1568         None => output_type,
1569         Some(substs) => {
1570             ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1571         }
1572     };
1573     let is_immediate = ty::type_is_immediate(substd_output_type);
1574     let fcx = @mut fn_ctxt_ {
1575           llfn: llfndecl,
1576           llenv: unsafe {
1577               llvm::LLVMGetUndef(Type::i8p().to_ref())
1578           },
1579           llretptr: None,
1580           llstaticallocas: llbbs.sa,
1581           llloadenv: None,
1582           llreturn: llbbs.rt,
1583           llself: None,
1584           personality: None,
1585           loop_ret: None,
1586           has_immediate_return_value: is_immediate,
1587           llargs: @mut HashMap::new(),
1588           lllocals: @mut HashMap::new(),
1589           llupvars: @mut HashMap::new(),
1590           id: id,
1591           impl_id: impl_id,
1592           param_substs: param_substs,
1593           span: sp,
1594           path: path,
1595           ccx: ccx
1596     };
1597     fcx.llenv = unsafe {
1598           llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1599     };
1600     if !ty::type_is_nil(substd_output_type) {
1601         fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1602     }
1603     fcx
1604 }
1605
1606 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1607                    path: path,
1608                    llfndecl: ValueRef,
1609                    output_type: ty::t,
1610                    sp: Option<span>)
1611                 -> fn_ctxt {
1612     new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, None, None, sp)
1613 }
1614
1615 // NB: must keep 4 fns in sync:
1616 //
1617 //  - type_of_fn
1618 //  - create_llargs_for_fn_args.
1619 //  - new_fn_ctxt
1620 //  - trans_args
1621
1622 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1623 // allocas created for them.
1624 //
1625 // When we translate a function, we need to map its incoming arguments to the
1626 // spaces that have been created for them (by code in the llallocas field of
1627 // the function's fn_ctxt).  create_llargs_for_fn_args populates the llargs
1628 // field of the fn_ctxt with
1629 pub fn create_llargs_for_fn_args(cx: fn_ctxt,
1630                                  self_arg: self_arg,
1631                                  args: &[ast::arg])
1632                               -> ~[ValueRef] {
1633     let _icx = push_ctxt("create_llargs_for_fn_args");
1634
1635     match self_arg {
1636       impl_self(tt) => {
1637         cx.llself = Some(ValSelfData {
1638             v: cx.llenv,
1639             t: tt,
1640             is_owned: false
1641         });
1642       }
1643       impl_owned_self(tt) => {
1644         cx.llself = Some(ValSelfData {
1645             v: cx.llenv,
1646             t: tt,
1647             is_owned: true
1648         });
1649       }
1650       no_self => ()
1651     }
1652
1653     // Return an array containing the ValueRefs that we get from
1654     // llvm::LLVMGetParam for each argument.
1655     vec::from_fn(args.len(), |i| {
1656         unsafe {
1657             let arg_n = cx.arg_pos(i);
1658             let arg = &args[i];
1659             let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint);
1660
1661             match arg.ty.node {
1662                 // `~` pointers never alias other parameters, because ownership was transferred
1663                 ast::ty_uniq(_) => {
1664                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1665                 }
1666                 // FIXME: #6785: `&mut` can only alias `&const` and `@mut`, we should check for
1667                 // those in the other parameters and then mark it as `noalias` if there aren't any
1668                 _ => {}
1669             }
1670
1671             llarg
1672         }
1673     })
1674 }
1675
1676 pub fn copy_args_to_allocas(fcx: fn_ctxt,
1677                             bcx: block,
1678                             args: &[ast::arg],
1679                             raw_llargs: &[ValueRef],
1680                             arg_tys: &[ty::t]) -> block {
1681     let _icx = push_ctxt("copy_args_to_allocas");
1682     let mut bcx = bcx;
1683
1684     match fcx.llself {
1685       Some(slf) => {
1686         // We really should do this regardless of whether self is owned, but
1687         // it doesn't work right with default method impls yet. (FIXME: #2794)
1688         if slf.is_owned {
1689             let self_val = if datum::appropriate_mode(slf.t).is_by_value() {
1690                 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1691                 let alloc = alloc_ty(bcx, slf.t);
1692                 Store(bcx, tmp, alloc);
1693                 alloc
1694             } else {
1695                 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1696             };
1697
1698             fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1699             add_clean(bcx, self_val, slf.t);
1700         }
1701       }
1702       _ => {}
1703     }
1704
1705     for uint::range(0, arg_tys.len()) |arg_n| {
1706         let arg_ty = arg_tys[arg_n];
1707         let raw_llarg = raw_llargs[arg_n];
1708         let arg_id = args[arg_n].id;
1709
1710         // For certain mode/type combinations, the raw llarg values are passed
1711         // by value.  However, within the fn body itself, we want to always
1712         // have all locals and arguments be by-ref so that we can cancel the
1713         // cleanup and for better interaction with LLVM's debug info.  So, if
1714         // the argument would be passed by value, we store it into an alloca.
1715         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1716         // the event it's not truly needed.
1717         // only by value if immediate:
1718         let llarg = if datum::appropriate_mode(arg_ty).is_by_value() {
1719             let alloc = alloc_ty(bcx, arg_ty);
1720             Store(bcx, raw_llarg, alloc);
1721             alloc
1722         } else {
1723             raw_llarg
1724         };
1725
1726         add_clean(bcx, llarg, arg_ty);
1727
1728         bcx = _match::bind_irrefutable_pat(bcx,
1729                                           args[arg_n].pat,
1730                                           llarg,
1731                                           false,
1732                                           _match::BindArgument);
1733
1734         fcx.llargs.insert(arg_id, llarg);
1735
1736         if fcx.ccx.sess.opts.extra_debuginfo && fcx_has_nonzero_span(fcx) {
1737             debuginfo::create_arg(bcx, args[arg_n], args[arg_n].ty.span);
1738         }
1739     }
1740
1741     return bcx;
1742 }
1743
1744 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1745 // and builds the return block.
1746 pub fn finish_fn(fcx: fn_ctxt, lltop: BasicBlockRef) {
1747     let _icx = push_ctxt("finish_fn");
1748     tie_up_header_blocks(fcx, lltop);
1749     build_return_block(fcx);
1750 }
1751
1752 // Builds the return block for a function.
1753 pub fn build_return_block(fcx: fn_ctxt) {
1754     let ret_cx = raw_block(fcx, false, fcx.llreturn);
1755
1756     // Return the value if this function immediate; otherwise, return void.
1757     if fcx.llretptr.is_some() && fcx.has_immediate_return_value {
1758         Ret(ret_cx, Load(ret_cx, fcx.llretptr.get()))
1759     } else {
1760         RetVoid(ret_cx)
1761     }
1762 }
1763
1764 pub fn tie_up_header_blocks(fcx: fn_ctxt, lltop: BasicBlockRef) {
1765     let _icx = push_ctxt("tie_up_header_blocks");
1766     match fcx.llloadenv {
1767         Some(ll) => {
1768             Br(raw_block(fcx, false, fcx.llstaticallocas), ll);
1769             Br(raw_block(fcx, false, ll), lltop);
1770         }
1771         None => {
1772             Br(raw_block(fcx, false, fcx.llstaticallocas), lltop);
1773         }
1774     }
1775 }
1776
1777 pub enum self_arg { impl_self(ty::t), impl_owned_self(ty::t), no_self, }
1778
1779 // trans_closure: Builds an LLVM function out of a source function.
1780 // If the function closes over its environment a closure will be
1781 // returned.
1782 pub fn trans_closure(ccx: @mut CrateContext,
1783                      path: path,
1784                      decl: &ast::fn_decl,
1785                      body: &ast::blk,
1786                      llfndecl: ValueRef,
1787                      self_arg: self_arg,
1788                      param_substs: Option<@param_substs>,
1789                      id: ast::node_id,
1790                      impl_id: Option<ast::def_id>,
1791                      attributes: &[ast::attribute],
1792                      output_type: ty::t,
1793                      maybe_load_env: &fn(fn_ctxt),
1794                      finish: &fn(block)) {
1795     ccx.stats.n_closures += 1;
1796     let _icx = push_ctxt("trans_closure");
1797     set_uwtable(llfndecl);
1798
1799     debug!("trans_closure(..., param_substs=%s)",
1800            param_substs.repr(ccx.tcx));
1801
1802     // Set up arguments to the function.
1803     let fcx = new_fn_ctxt_w_id(ccx,
1804                                path,
1805                                llfndecl,
1806                                id,
1807                                output_type,
1808                                impl_id,
1809                                param_substs,
1810                                Some(body.span));
1811     let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1812
1813     // Set the fixed stack segment flag if necessary.
1814     if attr::attrs_contains_name(attributes, "fixed_stack_segment") {
1815         set_no_inline(fcx.llfn);
1816         set_fixed_stack_segment(fcx.llfn);
1817     }
1818
1819     // Create the first basic block in the function and keep a handle on it to
1820     //  pass to finish_fn later.
1821     let bcx_top = top_scope_block(fcx, body.info());
1822     let mut bcx = bcx_top;
1823     let lltop = bcx.llbb;
1824     let block_ty = node_id_type(bcx, body.node.id);
1825
1826     let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1827     bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1828
1829     maybe_load_env(fcx);
1830
1831     // This call to trans_block is the place where we bridge between
1832     // translation calls that don't have a return value (trans_crate,
1833     // trans_mod, trans_item, et cetera) and those that do
1834     // (trans_block, trans_expr, et cetera).
1835     if body.node.expr.is_none() || ty::type_is_bot(block_ty) ||
1836         ty::type_is_nil(block_ty)
1837     {
1838         bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1839     } else {
1840         let dest = expr::SaveIn(fcx.llretptr.get());
1841         bcx = controlflow::trans_block(bcx, body, dest);
1842     }
1843
1844     finish(bcx);
1845     cleanup_and_Br(bcx, bcx_top, fcx.llreturn);
1846
1847     // Put return block after all other blocks.
1848     // This somewhat improves single-stepping experience in debugger.
1849     unsafe {
1850         llvm::LLVMMoveBasicBlockAfter(fcx.llreturn, bcx.llbb);
1851     }
1852
1853     // Insert the mandatory first few basic blocks before lltop.
1854     finish_fn(fcx, lltop);
1855 }
1856
1857 // trans_fn: creates an LLVM function corresponding to a source language
1858 // function.
1859 pub fn trans_fn(ccx: @mut CrateContext,
1860                 path: path,
1861                 decl: &ast::fn_decl,
1862                 body: &ast::blk,
1863                 llfndecl: ValueRef,
1864                 self_arg: self_arg,
1865                 param_substs: Option<@param_substs>,
1866                 id: ast::node_id,
1867                 impl_id: Option<ast::def_id>,
1868                 attrs: &[ast::attribute]) {
1869     let do_time = ccx.sess.trans_stats();
1870     let start = if do_time { time::get_time() }
1871                 else { time::Timespec::new(0, 0) };
1872     debug!("trans_fn(self_arg=%?, param_substs=%s)",
1873            self_arg,
1874            param_substs.repr(ccx.tcx));
1875     let _icx = push_ctxt("trans_fn");
1876     ccx.stats.n_fns += 1;
1877     let the_path_str = path_str(ccx.sess, path);
1878     let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1879     trans_closure(ccx,
1880                   path,
1881                   decl,
1882                   body,
1883                   llfndecl,
1884                   self_arg,
1885                   param_substs,
1886                   id,
1887                   impl_id,
1888                   attrs,
1889                   output_type,
1890                   |fcx| {
1891                       if ccx.sess.opts.extra_debuginfo
1892                           && fcx_has_nonzero_span(fcx) {
1893                           debuginfo::create_function(fcx);
1894                       }
1895                   },
1896                   |_bcx| { });
1897     if do_time {
1898         let end = time::get_time();
1899         ccx.log_fn_time(the_path_str, start, end);
1900     }
1901 }
1902
1903 pub fn trans_enum_variant(ccx: @mut CrateContext,
1904                           enum_id: ast::node_id,
1905                           variant: &ast::variant,
1906                           args: &[ast::variant_arg],
1907                           disr: int,
1908                           param_substs: Option<@param_substs>,
1909                           llfndecl: ValueRef) {
1910     let _icx = push_ctxt("trans_enum_variant");
1911     // Translate variant arguments to function arguments.
1912     let fn_args = do args.map |varg| {
1913         ast::arg {
1914             is_mutbl: false,
1915             ty: varg.ty,
1916             pat: ast_util::ident_to_pat(
1917                 ccx.tcx.sess.next_node_id(),
1918                 codemap::dummy_sp(),
1919                 special_idents::arg),
1920             id: varg.id,
1921         }
1922     };
1923
1924     let ty_param_substs = match param_substs {
1925         Some(ref substs) => { copy substs.tys }
1926         None => ~[]
1927     };
1928     let enum_ty = ty::subst_tps(ccx.tcx,
1929                                 ty_param_substs,
1930                                 None,
1931                                 ty::node_id_to_type(ccx.tcx, enum_id));
1932     let fcx = new_fn_ctxt_w_id(ccx,
1933                                ~[],
1934                                llfndecl,
1935                                variant.node.id,
1936                                enum_ty,
1937                                None,
1938                                param_substs,
1939                                None);
1940
1941     let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
1942     let bcx = top_scope_block(fcx, None);
1943     let lltop = bcx.llbb;
1944     let arg_tys = ty::ty_fn_args(node_id_type(bcx, variant.node.id));
1945     let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
1946
1947     // XXX is there a better way to reconstruct the ty::t?
1948     let repr = adt::represent_type(ccx, enum_ty);
1949
1950     debug!("trans_enum_variant: name=%s tps=%s repr=%? enum_ty=%s",
1951            unsafe { str::raw::from_c_str(llvm::LLVMGetValueName(llfndecl)) },
1952            ~"[" + ty_param_substs.map(|&t| ty_to_str(ccx.tcx, t)).connect(", ") + "]",
1953            repr, ty_to_str(ccx.tcx, enum_ty));
1954
1955     adt::trans_start_init(bcx, repr, fcx.llretptr.get(), disr);
1956     for args.iter().enumerate().advance |(i, va)| {
1957         let lldestptr = adt::trans_field_ptr(bcx,
1958                                              repr,
1959                                              fcx.llretptr.get(),
1960                                              disr,
1961                                              i);
1962
1963         // If this argument to this function is a enum, it'll have come in to
1964         // this function as an opaque blob due to the way that type_of()
1965         // works. So we have to cast to the destination's view of the type.
1966         let llarg = match fcx.llargs.find(&va.id) {
1967             Some(&x) => x,
1968             _ => fail!("trans_enum_variant: how do we know this works?"),
1969         };
1970         let arg_ty = arg_tys[i];
1971         memcpy_ty(bcx, lldestptr, llarg, arg_ty);
1972     }
1973     build_return(bcx);
1974     finish_fn(fcx, lltop);
1975 }
1976
1977 // NB: In theory this should be merged with the function above. But the AST
1978 // structures are completely different, so very little code would be shared.
1979 pub fn trans_tuple_struct(ccx: @mut CrateContext,
1980                           fields: &[@ast::struct_field],
1981                           ctor_id: ast::node_id,
1982                           param_substs: Option<@param_substs>,
1983                           llfndecl: ValueRef) {
1984     let _icx = push_ctxt("trans_tuple_struct");
1985
1986     // Translate struct fields to function arguments.
1987     let fn_args = do fields.map |field| {
1988         ast::arg {
1989             is_mutbl: false,
1990             ty: field.node.ty,
1991             pat: ast_util::ident_to_pat(ccx.tcx.sess.next_node_id(),
1992                                         codemap::dummy_sp(),
1993                                         special_idents::arg),
1994             id: field.node.id
1995         }
1996     };
1997
1998     // XXX is there a better way to reconstruct the ty::t?
1999     let ty_param_substs = match param_substs {
2000         Some(ref substs) => { copy substs.tys }
2001         None => ~[]
2002     };
2003     let ctor_ty = ty::subst_tps(ccx.tcx, ty_param_substs, None,
2004                                 ty::node_id_to_type(ccx.tcx, ctor_id));
2005     let tup_ty = match ty::get(ctor_ty).sty {
2006         ty::ty_bare_fn(ref bft) => bft.sig.output,
2007         _ => ccx.sess.bug(fmt!("trans_tuple_struct: unexpected ctor \
2008                                 return type %s",
2009                                ty_to_str(ccx.tcx, ctor_ty)))
2010     };
2011
2012     let fcx = new_fn_ctxt_w_id(ccx,
2013                                ~[],
2014                                llfndecl,
2015                                ctor_id,
2016                                tup_ty,
2017                                None,
2018                                param_substs,
2019                                None);
2020
2021     let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2022
2023     let bcx = top_scope_block(fcx, None);
2024     let lltop = bcx.llbb;
2025     let arg_tys = ty::ty_fn_args(node_id_type(bcx, ctor_id));
2026     let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2027
2028     let repr = adt::represent_type(ccx, tup_ty);
2029     adt::trans_start_init(bcx, repr, fcx.llretptr.get(), 0);
2030
2031     for fields.iter().enumerate().advance |(i, field)| {
2032         let lldestptr = adt::trans_field_ptr(bcx,
2033                                              repr,
2034                                              fcx.llretptr.get(),
2035                                              0,
2036                                              i);
2037         let llarg = fcx.llargs.get_copy(&field.node.id);
2038         let arg_ty = arg_tys[i];
2039         memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2040     }
2041
2042     build_return(bcx);
2043     finish_fn(fcx, lltop);
2044 }
2045
2046 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2047                       id: ast::node_id, vi: @~[ty::VariantInfo],
2048                       i: &mut uint) {
2049     for enum_definition.variants.iter().advance |variant| {
2050         let disr_val = vi[*i].disr_val;
2051         *i += 1;
2052
2053         match variant.node.kind {
2054             ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2055                 let llfn = get_item_val(ccx, variant.node.id);
2056                 trans_enum_variant(ccx, id, variant, *args,
2057                                    disr_val, None, llfn);
2058             }
2059             ast::tuple_variant_kind(_) => {
2060                 // Nothing to do.
2061             }
2062             ast::struct_variant_kind(struct_def) => {
2063                 trans_struct_def(ccx, struct_def);
2064             }
2065         }
2066     }
2067 }
2068
2069 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2070     let _icx = push_ctxt("trans_item");
2071     let path = match ccx.tcx.items.get_copy(&item.id) {
2072         ast_map::node_item(_, p) => p,
2073         // tjc: ?
2074         _ => fail!("trans_item"),
2075     };
2076     match item.node {
2077       ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2078         if purity == ast::extern_fn  {
2079             let llfndecl = get_item_val(ccx, item.id);
2080             foreign::trans_foreign_fn(ccx,
2081                                       vec::append(/*bad*/copy *path,
2082                                                   [path_name(item.ident)]),
2083                                       decl,
2084                                       body,
2085                                       llfndecl,
2086                                       item.id);
2087         } else if !generics.is_type_parameterized() {
2088             let llfndecl = get_item_val(ccx, item.id);
2089             trans_fn(ccx,
2090                      vec::append(/*bad*/copy *path, [path_name(item.ident)]),
2091                      decl,
2092                      body,
2093                      llfndecl,
2094                      no_self,
2095                      None,
2096                      item.id,
2097                      None,
2098                      item.attrs);
2099         } else {
2100             for body.node.stmts.iter().advance |stmt| {
2101                 match stmt.node {
2102                   ast::stmt_decl(@codemap::spanned { node: ast::decl_item(i),
2103                                                  _ }, _) => {
2104                     trans_item(ccx, i);
2105                   }
2106                   _ => ()
2107                 }
2108             }
2109         }
2110       }
2111       ast::item_impl(ref generics, _, _, ref ms) => {
2112         meth::trans_impl(ccx, /*bad*/copy *path, item.ident, *ms,
2113                          generics, None, item.id);
2114       }
2115       ast::item_mod(ref m) => {
2116         trans_mod(ccx, m);
2117       }
2118       ast::item_enum(ref enum_definition, ref generics) => {
2119         if !generics.is_type_parameterized() {
2120             let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2121             let mut i = 0;
2122             trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2123         }
2124       }
2125       ast::item_static(_, m, expr) => {
2126           consts::trans_const(ccx, m, item.id);
2127           // Do static_assert checking. It can't really be done much earlier because we need to get
2128           // the value of the bool out of LLVM
2129           for item.attrs.iter().advance |attr| {
2130               match attr.node.value.node {
2131                   ast::meta_word(x) => {
2132                       if x.slice(0, x.len()) == "static_assert" {
2133                           if m == ast::m_mutbl {
2134                               ccx.sess.span_fatal(expr.span,
2135                                                   "cannot have static_assert \
2136                                                    on a mutable static");
2137                           }
2138                           let v = ccx.const_values.get_copy(&item.id);
2139                           unsafe {
2140                               if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2141                                   ccx.sess.span_fatal(expr.span, "static assertion failed");
2142                               }
2143                           }
2144                       }
2145                   },
2146                   _ => ()
2147               }
2148           }
2149       },
2150       ast::item_foreign_mod(ref foreign_mod) => {
2151         foreign::trans_foreign_mod(ccx, path, foreign_mod);
2152       }
2153       ast::item_struct(struct_def, ref generics) => {
2154         if !generics.is_type_parameterized() {
2155             trans_struct_def(ccx, struct_def);
2156         }
2157       }
2158       _ => {/* fall through */ }
2159     }
2160 }
2161
2162 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2163     // If this is a tuple-like struct, translate the constructor.
2164     match struct_def.ctor_id {
2165         // We only need to translate a constructor if there are fields;
2166         // otherwise this is a unit-like struct.
2167         Some(ctor_id) if struct_def.fields.len() > 0 => {
2168             let llfndecl = get_item_val(ccx, ctor_id);
2169             trans_tuple_struct(ccx, struct_def.fields,
2170                                ctor_id, None, llfndecl);
2171         }
2172         Some(_) | None => {}
2173     }
2174 }
2175
2176 // Translate a module. Doing this amounts to translating the items in the
2177 // module; there ends up being no artifact (aside from linkage names) of
2178 // separate modules in the compiled program.  That's because modules exist
2179 // only as a convenience for humans working with the code, to organize names
2180 // and control visibility.
2181 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2182     let _icx = push_ctxt("trans_mod");
2183     for m.items.iter().advance |item| {
2184         trans_item(ccx, *item);
2185     }
2186 }
2187
2188 pub fn register_fn(ccx: @mut CrateContext,
2189                    sp: span,
2190                    path: path,
2191                    node_id: ast::node_id,
2192                    attrs: &[ast::attribute])
2193                 -> ValueRef {
2194     let t = ty::node_id_to_type(ccx.tcx, node_id);
2195     register_fn_full(ccx, sp, path, node_id, attrs, t)
2196 }
2197
2198 pub fn register_fn_full(ccx: @mut CrateContext,
2199                         sp: span,
2200                         path: path,
2201                         node_id: ast::node_id,
2202                         attrs: &[ast::attribute],
2203                         node_type: ty::t)
2204                      -> ValueRef {
2205     let llfty = type_of_fn_from_ty(ccx, node_type);
2206     register_fn_fuller(ccx, sp, path, node_id, attrs, node_type,
2207                        lib::llvm::CCallConv, llfty)
2208 }
2209
2210 pub fn register_fn_fuller(ccx: @mut CrateContext,
2211                           sp: span,
2212                           path: path,
2213                           node_id: ast::node_id,
2214                           attrs: &[ast::attribute],
2215                           node_type: ty::t,
2216                           cc: lib::llvm::CallConv,
2217                           fn_ty: Type)
2218                           -> ValueRef {
2219     debug!("register_fn_fuller creating fn for item %d with path %s",
2220            node_id,
2221            ast_map::path_to_str(path, token::get_ident_interner()));
2222
2223     let ps = if attr::attrs_contains_name(attrs, "no_mangle") {
2224         path_elt_to_str(*path.last(), token::get_ident_interner())
2225     } else {
2226         mangle_exported_name(ccx, /*bad*/copy path, node_type)
2227     };
2228
2229     let llfn = decl_fn(ccx.llmod, ps, cc, fn_ty);
2230     ccx.item_symbols.insert(node_id, ps);
2231
2232     // FIXME #4404 android JNI hacks
2233     let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2234                       (*ccx.sess.building_library &&
2235                        ccx.sess.targ_cfg.os == session::os_android));
2236     if is_entry {
2237         create_entry_wrapper(ccx, sp, llfn);
2238     }
2239     llfn
2240 }
2241
2242 pub fn is_entry_fn(sess: &Session, node_id: ast::node_id) -> bool {
2243     match *sess.entry_fn {
2244         Some((entry_id, _)) => node_id == entry_id,
2245         None => false
2246     }
2247 }
2248
2249 // Create a _rust_main(args: ~[str]) function which will be called from the
2250 // runtime rust_start function
2251 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2252                            _sp: span, main_llfn: ValueRef) {
2253     let et = ccx.sess.entry_type.unwrap();
2254     if et == session::EntryMain {
2255         let llfn = create_main(ccx, main_llfn);
2256         create_entry_fn(ccx, llfn, true);
2257     } else {
2258         create_entry_fn(ccx, main_llfn, false);
2259     }
2260
2261     fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2262         let nt = ty::mk_nil();
2263
2264         let llfty = type_of_fn(ccx, [], nt);
2265         let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2266                               lib::llvm::CCallConv, llfty);
2267
2268         let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2269
2270         // the args vector built in create_entry_fn will need
2271         // be updated if this assertion starts to fail.
2272         assert!(fcx.has_immediate_return_value);
2273
2274         let bcx = top_scope_block(fcx, None);
2275         let lltop = bcx.llbb;
2276
2277         // Call main.
2278         let llenvarg = unsafe {
2279             let env_arg = fcx.env_arg_pos();
2280             llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2281         };
2282         let args = ~[llenvarg];
2283         Call(bcx, main_llfn, args);
2284
2285         build_return(bcx);
2286         finish_fn(fcx, lltop);
2287         return llfdecl;
2288     }
2289
2290     fn create_entry_fn(ccx: @mut CrateContext,
2291                        rust_main: ValueRef,
2292                        use_start_lang_item: bool) {
2293         let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()], &ccx.int_type);
2294
2295         // FIXME #4404 android JNI hacks
2296         let llfn = if *ccx.sess.building_library {
2297             decl_cdecl_fn(ccx.llmod, "amain", llfty)
2298         } else {
2299             let main_name = match ccx.sess.targ_cfg.os {
2300                 session::os_win32 => ~"WinMain@16",
2301                 _ => ~"main",
2302             };
2303             decl_cdecl_fn(ccx.llmod, main_name, llfty)
2304         };
2305         let llbb = str::as_c_str("top", |buf| {
2306             unsafe {
2307                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2308             }
2309         });
2310         let bld = ccx.builder.B;
2311         unsafe {
2312             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2313
2314             let start_def_id = ccx.tcx.lang_items.start_fn();
2315             if start_def_id.crate != ast::local_crate {
2316                 let start_fn_type = csearch::get_type(ccx.tcx,
2317                                                       start_def_id).ty;
2318                 trans_external_path(ccx, start_def_id, start_fn_type);
2319             }
2320
2321             let crate_map = ccx.crate_map;
2322             let opaque_crate_map = do "crate_map".as_c_str |buf| {
2323                 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2324             };
2325
2326             let (start_fn, args) = if use_start_lang_item {
2327                 let start_def_id = ccx.tcx.lang_items.start_fn();
2328                 let start_fn = if start_def_id.crate == ast::local_crate {
2329                     get_item_val(ccx, start_def_id.node)
2330                 } else {
2331                     let start_fn_type = csearch::get_type(ccx.tcx,
2332                             start_def_id).ty;
2333                     trans_external_path(ccx, start_def_id, start_fn_type)
2334                 };
2335
2336                 let args = {
2337                     let opaque_rust_main = do "rust_main".as_c_str |buf| {
2338                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2339                     };
2340
2341                     ~[
2342                         C_null(Type::opaque_box(ccx).ptr_to()),
2343                         opaque_rust_main,
2344                         llvm::LLVMGetParam(llfn, 0),
2345                         llvm::LLVMGetParam(llfn, 1),
2346                         opaque_crate_map
2347                      ]
2348                 };
2349                 (start_fn, args)
2350             } else {
2351                 debug!("using user-defined start fn");
2352                 let args = {
2353                     ~[
2354                         C_null(Type::opaque_box(ccx).ptr_to()),
2355                         llvm::LLVMGetParam(llfn, 0 as c_uint),
2356                         llvm::LLVMGetParam(llfn, 1 as c_uint),
2357                         opaque_crate_map
2358                     ]
2359                 };
2360
2361                 (rust_main, args)
2362             };
2363
2364             let result = llvm::LLVMBuildCall(bld,
2365                                              start_fn,
2366                                              &args[0],
2367                                              args.len() as c_uint,
2368                                              noname());
2369             llvm::LLVMBuildRet(bld, result);
2370         }
2371     }
2372 }
2373
2374 pub fn fill_fn_pair(bcx: block, pair: ValueRef, llfn: ValueRef,
2375                     llenvptr: ValueRef) {
2376     let ccx = bcx.ccx();
2377     let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2378     Store(bcx, llfn, code_cell);
2379     let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2380     let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2381     Store(bcx, llenvblobptr, env_cell);
2382 }
2383
2384 pub fn item_path(ccx: &CrateContext, i: @ast::item) -> path {
2385     let base = match ccx.tcx.items.get_copy(&i.id) {
2386         ast_map::node_item(_, p) => p,
2387             // separate map for paths?
2388         _ => fail!("item_path")
2389     };
2390     vec::append(/*bad*/copy *base, [path_name(i.ident)])
2391 }
2392
2393 pub fn get_item_val(ccx: @mut CrateContext, id: ast::node_id) -> ValueRef {
2394     debug!("get_item_val(id=`%?`)", id);
2395     let val = ccx.item_vals.find_copy(&id);
2396     match val {
2397       Some(v) => v,
2398       None => {
2399         let mut exprt = false;
2400         let item = ccx.tcx.items.get_copy(&id);
2401         let val = match item {
2402           ast_map::node_item(i, pth) => {
2403             let my_path = vec::append(/*bad*/copy *pth,
2404                                       [path_name(i.ident)]);
2405             match i.node {
2406               ast::item_static(_, m, expr) => {
2407                 let typ = ty::node_id_to_type(ccx.tcx, i.id);
2408                 let s = mangle_exported_name(ccx, my_path, typ);
2409                 // We need the translated value here, because for enums the
2410                 // LLVM type is not fully determined by the Rust type.
2411                 let v = consts::const_expr(ccx, expr);
2412                 ccx.const_values.insert(id, v);
2413                 exprt = m == ast::m_mutbl;
2414                 unsafe {
2415                     let llty = llvm::LLVMTypeOf(v);
2416                     let g = str::as_c_str(s, |buf| {
2417                         llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2418                     });
2419                     ccx.item_symbols.insert(i.id, s);
2420                     g
2421                 }
2422               }
2423               ast::item_fn(_, purity, _, _, _) => {
2424                 let llfn = if purity != ast::extern_fn {
2425                     register_fn(ccx, i.span, my_path, i.id, i.attrs)
2426                 } else {
2427                     foreign::register_foreign_fn(ccx,
2428                                                  i.span,
2429                                                  my_path,
2430                                                  i.id,
2431                                                  i.attrs)
2432                 };
2433                 set_inline_hint_if_appr(i.attrs, llfn);
2434                 llfn
2435               }
2436               _ => fail!("get_item_val: weird result in table")
2437             }
2438           }
2439           ast_map::node_trait_method(trait_method, _, pth) => {
2440             debug!("get_item_val(): processing a node_trait_method");
2441             match *trait_method {
2442               ast::required(_) => {
2443                 ccx.sess.bug("unexpected variant: required trait method in \
2444                               get_item_val()");
2445               }
2446               ast::provided(m) => {
2447                 exprt = true;
2448                 register_method(ccx, id, pth, m)
2449               }
2450             }
2451           }
2452           ast_map::node_method(m, _, pth) => {
2453             exprt = true;
2454             register_method(ccx, id, pth, m)
2455           }
2456           ast_map::node_foreign_item(ni, _, _, pth) => {
2457             exprt = true;
2458             match ni.node {
2459                 ast::foreign_item_fn(*) => {
2460                     register_fn(ccx, ni.span,
2461                                 vec::append(/*bad*/copy *pth,
2462                                             [path_name(ni.ident)]),
2463                                 ni.id,
2464                                 ni.attrs)
2465                 }
2466                 ast::foreign_item_static(*) => {
2467                     let typ = ty::node_id_to_type(ccx.tcx, ni.id);
2468                     let ident = token::ident_to_str(&ni.ident);
2469                     let g = do str::as_c_str(ident) |buf| {
2470                         unsafe {
2471                             let ty = type_of(ccx, typ);
2472                             llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2473                         }
2474                     };
2475                     g
2476                 }
2477             }
2478           }
2479
2480           ast_map::node_variant(ref v, enm, pth) => {
2481             let llfn;
2482             match v.node.kind {
2483                 ast::tuple_variant_kind(ref args) => {
2484                     assert!(args.len() != 0u);
2485                     let pth = vec::append(/*bad*/copy *pth,
2486                                           [path_name(enm.ident),
2487                                            path_name((*v).node.name)]);
2488                     llfn = match enm.node {
2489                       ast::item_enum(_, _) => {
2490                         register_fn(ccx, (*v).span, pth, id, enm.attrs)
2491                       }
2492                       _ => fail!("node_variant, shouldn't happen")
2493                     };
2494                 }
2495                 ast::struct_variant_kind(_) => {
2496                     fail!("struct variant kind unexpected in get_item_val")
2497                 }
2498             }
2499             set_inline_hint(llfn);
2500             llfn
2501           }
2502
2503           ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2504             // Only register the constructor if this is a tuple-like struct.
2505             match struct_def.ctor_id {
2506                 None => {
2507                     ccx.tcx.sess.bug("attempt to register a constructor of \
2508                                   a non-tuple-like struct")
2509                 }
2510                 Some(ctor_id) => {
2511                     let llfn = register_fn(ccx,
2512                                            struct_item.span,
2513                                            /*bad*/copy *struct_path,
2514                                            ctor_id,
2515                                            struct_item.attrs);
2516                     set_inline_hint(llfn);
2517                     llfn
2518                 }
2519             }
2520           }
2521
2522           ref variant => {
2523             ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2524                               variant))
2525           }
2526         };
2527         if !(exprt || ccx.reachable.contains(&id)) {
2528             lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2529         }
2530         ccx.item_vals.insert(id, val);
2531         val
2532       }
2533     }
2534 }
2535
2536 pub fn register_method(ccx: @mut CrateContext,
2537                        id: ast::node_id,
2538                        pth: @ast_map::path,
2539                        m: @ast::method) -> ValueRef {
2540     let mty = ty::node_id_to_type(ccx.tcx, id);
2541     let pth = vec::append(/*bad*/copy *pth, [path_name((ccx.names)("meth")),
2542                                   path_name(m.ident)]);
2543     let llfn = register_fn_full(ccx, m.span, pth, id, m.attrs, mty);
2544     set_inline_hint_if_appr(m.attrs, llfn);
2545     llfn
2546 }
2547
2548 // The constant translation pass.
2549 pub fn trans_constant(ccx: @mut CrateContext, it: @ast::item) {
2550     let _icx = push_ctxt("trans_constant");
2551     match it.node {
2552       ast::item_enum(ref enum_definition, _) => {
2553         let vi = ty::enum_variants(ccx.tcx,
2554                                    ast::def_id { crate: ast::local_crate,
2555                                                  node: it.id });
2556         let mut i = 0;
2557         let path = item_path(ccx, it);
2558         for (*enum_definition).variants.iter().advance |variant| {
2559             let p = vec::append(/*bad*/copy path, [
2560                 path_name(variant.node.name),
2561                 path_name(special_idents::descrim)
2562             ]);
2563             let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed();
2564             let disr_val = vi[i].disr_val;
2565             note_unique_llvm_symbol(ccx, s);
2566             let discrim_gvar = str::as_c_str(s, |buf| {
2567                 unsafe {
2568                     llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2569                 }
2570             });
2571             unsafe {
2572                 llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, disr_val));
2573                 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
2574             }
2575             ccx.discrims.insert(
2576                 local_def(variant.node.id), discrim_gvar);
2577             ccx.discrim_symbols.insert(variant.node.id, s);
2578             i += 1;
2579         }
2580       }
2581       _ => ()
2582     }
2583 }
2584
2585 pub fn trans_constants(ccx: @mut CrateContext, crate: &ast::crate) {
2586     visit::visit_crate(
2587         crate, ((),
2588         visit::mk_simple_visitor(@visit::SimpleVisitor {
2589             visit_item: |a| trans_constant(ccx, a),
2590             ..*visit::default_simple_visitor()
2591         })));
2592 }
2593
2594 pub fn vp2i(cx: block, v: ValueRef) -> ValueRef {
2595     let ccx = cx.ccx();
2596     return PtrToInt(cx, v, ccx.int_type);
2597 }
2598
2599 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2600     unsafe {
2601         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2602     }
2603 }
2604
2605 macro_rules! ifn (
2606     ($name:expr, $args:expr, $ret:expr) => ({
2607         let name = $name;
2608         let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2609         intrinsics.insert(name, f);
2610     })
2611 )
2612
2613 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2614     let i8p = Type::i8p();
2615     let mut intrinsics = HashMap::new();
2616
2617     ifn!("llvm.memcpy.p0i8.p0i8.i32",
2618          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2619     ifn!("llvm.memcpy.p0i8.p0i8.i64",
2620          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2621     ifn!("llvm.memmove.p0i8.p0i8.i32",
2622          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2623     ifn!("llvm.memmove.p0i8.p0i8.i64",
2624          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2625     ifn!("llvm.memset.p0i8.i32",
2626          [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2627     ifn!("llvm.memset.p0i8.i64",
2628          [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2629
2630     ifn!("llvm.trap", [], Type::void());
2631     ifn!("llvm.frameaddress", [Type::i32()], i8p);
2632
2633     ifn!("llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2634     ifn!("llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2635     ifn!("llvm.pow.f32",  [Type::f32(), Type::f32()], Type::f32());
2636     ifn!("llvm.pow.f64",  [Type::f64(), Type::f64()], Type::f64());
2637
2638     ifn!("llvm.sqrt.f32", [Type::f32()], Type::f32());
2639     ifn!("llvm.sqrt.f64", [Type::f64()], Type::f64());
2640     ifn!("llvm.sin.f32",  [Type::f32()], Type::f32());
2641     ifn!("llvm.sin.f64",  [Type::f64()], Type::f64());
2642     ifn!("llvm.cos.f32",  [Type::f32()], Type::f32());
2643     ifn!("llvm.cos.f64",  [Type::f64()], Type::f64());
2644     ifn!("llvm.exp.f32",  [Type::f32()], Type::f32());
2645     ifn!("llvm.exp.f64",  [Type::f64()], Type::f64());
2646     ifn!("llvm.exp2.f32", [Type::f32()], Type::f32());
2647     ifn!("llvm.exp2.f64", [Type::f64()], Type::f64());
2648     ifn!("llvm.log.f32",  [Type::f32()], Type::f32());
2649     ifn!("llvm.log.f64",  [Type::f64()], Type::f64());
2650     ifn!("llvm.log10.f32",[Type::f32()], Type::f32());
2651     ifn!("llvm.log10.f64",[Type::f64()], Type::f64());
2652     ifn!("llvm.log2.f32", [Type::f32()], Type::f32());
2653     ifn!("llvm.log2.f64", [Type::f64()], Type::f64());
2654
2655     ifn!("llvm.fma.f32",  [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2656     ifn!("llvm.fma.f64",  [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2657
2658     ifn!("llvm.fabs.f32", [Type::f32()], Type::f32());
2659     ifn!("llvm.fabs.f64", [Type::f64()], Type::f64());
2660     ifn!("llvm.floor.f32",[Type::f32()], Type::f32());
2661     ifn!("llvm.floor.f64",[Type::f64()], Type::f64());
2662     ifn!("llvm.ceil.f32", [Type::f32()], Type::f32());
2663     ifn!("llvm.ceil.f64", [Type::f64()], Type::f64());
2664     ifn!("llvm.trunc.f32",[Type::f32()], Type::f32());
2665     ifn!("llvm.trunc.f64",[Type::f64()], Type::f64());
2666
2667     ifn!("llvm.ctpop.i8", [Type::i8()], Type::i8());
2668     ifn!("llvm.ctpop.i16",[Type::i16()], Type::i16());
2669     ifn!("llvm.ctpop.i32",[Type::i32()], Type::i32());
2670     ifn!("llvm.ctpop.i64",[Type::i64()], Type::i64());
2671
2672     ifn!("llvm.ctlz.i8",  [Type::i8() , Type::i1()], Type::i8());
2673     ifn!("llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2674     ifn!("llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2675     ifn!("llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2676
2677     ifn!("llvm.cttz.i8",  [Type::i8() , Type::i1()], Type::i8());
2678     ifn!("llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2679     ifn!("llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2680     ifn!("llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2681
2682     ifn!("llvm.bswap.i16",[Type::i16()], Type::i16());
2683     ifn!("llvm.bswap.i32",[Type::i32()], Type::i32());
2684     ifn!("llvm.bswap.i64",[Type::i64()], Type::i64());
2685
2686     return intrinsics;
2687 }
2688
2689 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2690     ifn!("llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2691     ifn!("llvm.dbg.value",   [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2692 }
2693
2694 pub fn trap(bcx: block) {
2695     match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2696       Some(&x) => { Call(bcx, x, []); },
2697       _ => bcx.sess().bug("unbound llvm.trap in trap")
2698     }
2699 }
2700
2701 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2702     if !ccx.sess.opts.gc || !ccx.uses_gc {
2703         return;
2704     }
2705
2706     let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2707     let gc_metadata = do str::as_c_str(gc_metadata_name) |buf| {
2708         unsafe {
2709             llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2710         }
2711     };
2712     unsafe {
2713         llvm::LLVMSetGlobalConstant(gc_metadata, True);
2714         lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2715         ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2716     }
2717 }
2718
2719 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2720     let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2721     let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2722     let map = do "_rust_mod_map".as_c_str |buf| {
2723         unsafe {
2724             llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2725         }
2726     };
2727     lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2728     let mut elts: ~[ValueRef] = ~[];
2729
2730     // This is not ideal, but the borrow checker doesn't
2731     // like the multiple borrows. At least, it doesn't
2732     // like them on the current snapshot. (2013-06-14)
2733     let mut keys = ~[];
2734     for ccx.module_data.each_key |k| {
2735         keys.push(k.to_managed());
2736     }
2737
2738     for keys.iter().advance |key| {
2739         let val = *ccx.module_data.find_equiv(key).get();
2740         let s_const = C_cstr(ccx, *key);
2741         let s_ptr = p2i(ccx, s_const);
2742         let v_ptr = p2i(ccx, val);
2743         let elt = C_struct([s_ptr, v_ptr]);
2744         elts.push(elt);
2745     }
2746     let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2747     elts.push(term);
2748     unsafe {
2749         llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2750     }
2751     return map;
2752 }
2753
2754
2755 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2756                       llmod: ModuleRef) -> ValueRef {
2757     let targ_cfg = sess.targ_cfg;
2758     let int_type = Type::int(targ_cfg.arch);
2759     let mut n_subcrates = 1;
2760     let cstore = sess.cstore;
2761     while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2762     let mapname = if *sess.building_library {
2763         fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2764     } else {
2765         ~"toplevel"
2766     };
2767     let sym_name = ~"_rust_crate_map_" + mapname;
2768     let arrtype = Type::array(&int_type, n_subcrates as u64);
2769     let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2770     let map = str::as_c_str(sym_name, |buf| {
2771         unsafe {
2772             llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2773         }
2774     });
2775     lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2776     return map;
2777 }
2778
2779 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2780     let mut subcrates: ~[ValueRef] = ~[];
2781     let mut i = 1;
2782     let cstore = ccx.sess.cstore;
2783     while cstore::have_crate_data(cstore, i) {
2784         let cdata = cstore::get_crate_data(cstore, i);
2785         let nm = fmt!("_rust_crate_map_%s_%s_%s",
2786                       cdata.name,
2787                       cstore::get_crate_vers(cstore, i),
2788                       cstore::get_crate_hash(cstore, i));
2789         let cr = str::as_c_str(nm, |buf| {
2790             unsafe {
2791                 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2792             }
2793         });
2794         subcrates.push(p2i(ccx, cr));
2795         i += 1;
2796     }
2797     subcrates.push(C_int(ccx, 0));
2798
2799     let llannihilatefn;
2800     let annihilate_def_id = ccx.tcx.lang_items.annihilate_fn();
2801     if annihilate_def_id.crate == ast::local_crate {
2802         llannihilatefn = get_item_val(ccx, annihilate_def_id.node);
2803     } else {
2804         let annihilate_fn_type = csearch::get_type(ccx.tcx,
2805                                                    annihilate_def_id).ty;
2806         llannihilatefn = trans_external_path(ccx,
2807                                              annihilate_def_id,
2808                                              annihilate_fn_type);
2809     }
2810
2811     unsafe {
2812         let mod_map = create_module_map(ccx);
2813         llvm::LLVMSetInitializer(map, C_struct(
2814             [C_i32(1),
2815              lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, Type::i8p().to_ref()),
2816              p2i(ccx, mod_map),
2817              C_array(ccx.int_type, subcrates)]));
2818     }
2819 }
2820
2821 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2822     -> encoder::EncodeParams<'r> {
2823
2824         let diag = cx.sess.diagnostic();
2825         let item_symbols = &cx.item_symbols;
2826         let discrim_symbols = &cx.discrim_symbols;
2827         let link_meta = &cx.link_meta;
2828         encoder::EncodeParams {
2829             diag: diag,
2830             tcx: cx.tcx,
2831             reachable: cx.reachable,
2832             reexports2: cx.exp_map2,
2833             item_symbols: item_symbols,
2834             discrim_symbols: discrim_symbols,
2835             link_meta: link_meta,
2836             cstore: cx.sess.cstore,
2837             encode_inlined_item: ie
2838         }
2839 }
2840
2841 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::crate) {
2842     if !*cx.sess.building_library { return; }
2843
2844     let encode_inlined_item: encoder::encode_inlined_item =
2845         |ecx, ebml_w, path, ii|
2846         astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2847
2848     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2849     let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2850     let llconst = C_struct([llmeta]);
2851     let mut llglobal = str::as_c_str("rust_metadata", |buf| {
2852         unsafe {
2853             llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2854         }
2855     });
2856     unsafe {
2857         llvm::LLVMSetInitializer(llglobal, llconst);
2858         str::as_c_str(cx.sess.targ_cfg.target_strs.meta_sect_name, |buf| {
2859             llvm::LLVMSetSection(llglobal, buf)
2860         });
2861         lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2862
2863         let t_ptr_i8 = Type::i8p();
2864         llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2865         let llvm_used = do "llvm.used".as_c_str |buf| {
2866             llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2867         };
2868         lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2869         llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2870     }
2871 }
2872
2873 // Writes the current ABI version into the crate.
2874 pub fn write_abi_version(ccx: &mut CrateContext) {
2875     mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
2876 }
2877
2878 pub fn trans_crate(sess: session::Session,
2879                    crate: @ast::crate,
2880                    tcx: ty::ctxt,
2881                    output: &Path,
2882                    emap2: resolve::ExportMap2,
2883                    maps: astencode::Maps) -> (ContextRef, ModuleRef, LinkMeta) {
2884
2885     let mut symbol_hasher = hash::default_state();
2886     let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
2887     let reachable = reachable::find_reachable(
2888         &crate.node.module,
2889         emap2,
2890         tcx,
2891         maps.method_map
2892     );
2893
2894     // Append ".rc" to crate name as LLVM module identifier.
2895     //
2896     // LLVM code generator emits a ".file filename" directive
2897     // for ELF backends. Value of the "filename" is set as the
2898     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
2899     // crashes if the module identifer is same as other symbols
2900     // such as a function name in the module.
2901     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2902     let llmod_id = link_meta.name.to_owned() + ".rc";
2903
2904     // FIXME(#6511): get LLVM building with --enable-threads so this
2905     //               function can be called
2906     // if !llvm::LLVMRustStartMultithreading() {
2907     //     sess.bug("couldn't enable multi-threaded LLVM");
2908     // }
2909
2910     let ccx = @mut CrateContext::new(sess, llmod_id, tcx, emap2, maps,
2911                                  symbol_hasher, link_meta, reachable);
2912     {
2913         let _icx = push_ctxt("data");
2914         trans_constants(ccx, crate);
2915     }
2916
2917     {
2918         let _icx = push_ctxt("text");
2919         trans_mod(ccx, &crate.node.module);
2920     }
2921
2922     decl_gc_metadata(ccx, llmod_id);
2923     fill_crate_map(ccx, ccx.crate_map);
2924     glue::emit_tydescs(ccx);
2925     write_abi_version(ccx);
2926     if ccx.sess.opts.debuginfo {
2927         debuginfo::finalize(ccx);
2928     }
2929
2930     // Translate the metadata.
2931     write_metadata(ccx, crate);
2932     if ccx.sess.trans_stats() {
2933         io::println("--- trans stats ---");
2934         io::println(fmt!("n_static_tydescs: %u",
2935                          ccx.stats.n_static_tydescs));
2936         io::println(fmt!("n_glues_created: %u",
2937                          ccx.stats.n_glues_created));
2938         io::println(fmt!("n_null_glues: %u", ccx.stats.n_null_glues));
2939         io::println(fmt!("n_real_glues: %u", ccx.stats.n_real_glues));
2940
2941         io::println(fmt!("n_fns: %u", ccx.stats.n_fns));
2942         io::println(fmt!("n_monos: %u", ccx.stats.n_monos));
2943         io::println(fmt!("n_inlines: %u", ccx.stats.n_inlines));
2944         io::println(fmt!("n_closures: %u", ccx.stats.n_closures));
2945     }
2946
2947     if ccx.sess.count_llvm_insns() {
2948         for ccx.stats.llvm_insns.each |&k, &v| {
2949             io::println(fmt!("%-7u %s", v, k));
2950         }
2951     }
2952
2953     let llcx = ccx.llcx;
2954     let link_meta = ccx.link_meta;
2955     let llmod = ccx.llmod;
2956
2957     return (llcx, llmod, link_meta);
2958 }