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