]> git.lizzy.rs Git - rust.git/blob - src/comp/middle/trans.rs
Use precise return type to allocate retslot in trans_args
[rust.git] / src / comp / middle / trans.rs
1 // trans.rs: Translate the completed AST to the LLVM IR.
2 //
3 // Some functions here, such as trans_block and trans_expr, return a value --
4 // the result of the translation to LLVM -- while others, such as trans_fn,
5 // trans_obj, and trans_item, are called only for the side effect of adding a
6 // particular definition to the LLVM IR output we're producing.
7 //
8 // Hopefully useful general knowledge about trans:
9 //
10 //   * There's no way to find out the ty::t type of a ValueRef.  Doing so
11 //     would be "trying to get the eggs out of an omelette" (credit:
12 //     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
13 //     but many TypeRefs correspond to one ty::t; for instance, tup(int, int,
14 //     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
15
16 import std::{map, time};
17 import std::map::hashmap;
18 import std::map::{new_int_hash, new_str_hash};
19 import option::{some, none};
20 import driver::session;
21 import front::attr;
22 import middle::{ty, gc, resolve, debuginfo};
23 import middle::freevars::*;
24 import back::{link, abi, upcall};
25 import syntax::{ast, ast_util, codemap};
26 import syntax::visit;
27 import syntax::codemap::span;
28 import syntax::print::pprust::{expr_to_str, stmt_to_str};
29 import visit::vt;
30 import util::common::*;
31 import lib::llvm::{llvm, mk_target_data, mk_type_names};
32 import lib::llvm::llvm::{ModuleRef, ValueRef, TypeRef, BasicBlockRef};
33 import lib::llvm::{True, False};
34 import link::{mangle_internal_name_by_type_only,
35               mangle_internal_name_by_seq,
36               mangle_internal_name_by_path,
37               mangle_internal_name_by_path_and_seq,
38               mangle_exported_name};
39 import metadata::{csearch, cstore};
40 import util::ppaux::{ty_to_str, ty_to_short_str};
41
42 import trans_common::*;
43 import trans_build::*;
44
45 import trans_objects::{trans_anon_obj, trans_obj};
46 import tvec = trans_vec;
47
48 fn type_of_1(bcx: @block_ctxt, t: ty::t) -> TypeRef {
49     let cx = bcx_ccx(bcx);
50     check type_has_static_size(cx, t);
51     type_of(cx, bcx.sp, t)
52 }
53
54 fn type_of(cx: @crate_ctxt, sp: span, t: ty::t) : type_has_static_size(cx, t)
55    -> TypeRef {
56     // Should follow from type_has_static_size -- argh.
57     // FIXME (requires Issue #586)
58     check non_ty_var(cx, t);
59     type_of_inner(cx, sp, t)
60 }
61
62 fn type_of_explicit_args(cx: @crate_ctxt, sp: span, inputs: [ty::arg]) ->
63    [TypeRef] {
64     let atys = [];
65     for arg in inputs {
66         let arg_ty = arg.ty;
67         // FIXME: would be nice to have a constraint on arg
68         // that would obviate the need for this check
69         check non_ty_var(cx, arg_ty);
70         let llty = type_of_inner(cx, sp, arg_ty);
71         atys += [arg.mode == ast::by_val ? llty : T_ptr(llty)];
72     }
73     ret atys;
74 }
75
76
77 // NB: must keep 4 fns in sync:
78 //
79 //  - type_of_fn
80 //  - create_llargs_for_fn_args.
81 //  - new_fn_ctxt
82 //  - trans_args
83 fn type_of_fn(cx: @crate_ctxt, sp: span, is_method: bool, inputs: [ty::arg],
84               output: ty::t, params: [ty::param_bounds]) -> TypeRef {
85     let atys: [TypeRef] = [];
86
87     // Arg 0: Output pointer.
88     check non_ty_var(cx, output);
89     let out_ty = T_ptr(type_of_inner(cx, sp, output));
90     atys += [out_ty];
91
92     // Arg 1: Env (closure-bindings / self-obj)
93     if is_method {
94         atys += [T_ptr(cx.rust_object_type)];
95     } else {
96         atys += [T_opaque_boxed_closure_ptr(cx)];
97     }
98
99     // Args >2: ty params, if not acquired via capture...
100     if !is_method {
101         for bounds in params {
102             atys += [T_ptr(cx.tydesc_type)];
103             for bound in *bounds {
104                 alt bound {
105                   ty::bound_iface(_) { atys += [T_ptr(T_dict())]; }
106                   _ {}
107                 }
108             }
109         }
110     }
111     // ... then explicit args.
112     atys += type_of_explicit_args(cx, sp, inputs);
113     ret T_fn(atys, llvm::LLVMVoidType());
114 }
115
116 // Given a function type and a count of ty params, construct an llvm type
117 fn type_of_fn_from_ty(cx: @crate_ctxt, sp: span, fty: ty::t,
118                       param_bounds: [ty::param_bounds]) -> TypeRef {
119     // FIXME: Check should be unnecessary, b/c it's implied
120     // by returns_non_ty_var(t). Make that a postcondition
121     // (see Issue #586)
122     let ret_ty = ty::ty_fn_ret(cx.tcx, fty);
123     ret type_of_fn(cx, sp, false, ty::ty_fn_args(cx.tcx, fty),
124                    ret_ty, param_bounds);
125 }
126
127 fn type_of_inner(cx: @crate_ctxt, sp: span, t: ty::t)
128     : non_ty_var(cx, t) -> TypeRef {
129     // Check the cache.
130
131     if cx.lltypes.contains_key(t) { ret cx.lltypes.get(t); }
132     let llty = alt ty::struct(cx.tcx, t) {
133       ty::ty_native(_) { T_ptr(T_i8()) }
134       ty::ty_nil. { T_nil() }
135       ty::ty_bot. {
136         T_nil() /* ...I guess? */
137       }
138       ty::ty_bool. { T_bool() }
139       ty::ty_int(t) { T_int_ty(cx, t) }
140       ty::ty_uint(t) { T_uint_ty(cx, t) }
141       ty::ty_float(t) { T_float_ty(cx, t) }
142       ty::ty_str. { T_ptr(T_vec(cx, T_i8())) }
143       ty::ty_tag(did, _) { type_of_tag(cx, sp, did, t) }
144       ty::ty_box(mt) {
145         let mt_ty = mt.ty;
146         check non_ty_var(cx, mt_ty);
147         T_ptr(T_box(cx, type_of_inner(cx, sp, mt_ty))) }
148       ty::ty_uniq(mt) {
149         let mt_ty = mt.ty;
150         check non_ty_var(cx, mt_ty);
151         T_ptr(type_of_inner(cx, sp, mt_ty)) }
152       ty::ty_vec(mt) {
153         let mt_ty = mt.ty;
154         if ty::type_has_dynamic_size(cx.tcx, mt_ty) {
155             T_ptr(cx.opaque_vec_type)
156         } else {
157             // should be unnecessary
158             check non_ty_var(cx, mt_ty);
159             T_ptr(T_vec(cx, type_of_inner(cx, sp, mt_ty))) }
160       }
161       ty::ty_ptr(mt) {
162         let mt_ty = mt.ty;
163         check non_ty_var(cx, mt_ty);
164         T_ptr(type_of_inner(cx, sp, mt_ty)) }
165       ty::ty_rec(fields) {
166         let tys: [TypeRef] = [];
167         for f: ty::field in fields {
168             let mt_ty = f.mt.ty;
169             check non_ty_var(cx, mt_ty);
170             tys += [type_of_inner(cx, sp, mt_ty)];
171         }
172         T_struct(tys)
173       }
174       ty::ty_fn(_) {
175         T_fn_pair(cx, type_of_fn_from_ty(cx, sp, t, []))
176       }
177       ty::ty_native_fn(args, out) {
178         let nft = native_fn_wrapper_type(cx, sp, [], t);
179         T_fn_pair(cx, nft)
180       }
181       ty::ty_obj(meths) { cx.rust_object_type }
182       ty::ty_res(_, sub, tps) {
183         let sub1 = ty::substitute_type_params(cx.tcx, tps, sub);
184         check non_ty_var(cx, sub1);
185         // FIXME #1184: Resource flag is larger than necessary
186         ret T_struct([cx.int_type, type_of_inner(cx, sp, sub1)]);
187       }
188       ty::ty_var(_) {
189         // Should be unreachable b/c of precondition.
190         // FIXME: would be nice to have a way of expressing this
191         // through postconditions, and then making it sound to omit
192         // cases in the alt
193         std::util::unreachable()
194       }
195       ty::ty_param(_, _) { T_typaram(cx.tn) }
196       ty::ty_send_type. | ty::ty_type. { T_ptr(cx.tydesc_type) }
197       ty::ty_tup(elts) {
198         let tys = [];
199         for elt in elts {
200             check non_ty_var(cx, elt);
201             tys += [type_of_inner(cx, sp, elt)];
202         }
203         T_struct(tys)
204       }
205       ty::ty_opaque_closure. {
206         T_opaque_closure(cx)
207       }
208       ty::ty_constr(subt,_) {
209         // FIXME: could be a constraint on ty_fn
210           check non_ty_var(cx, subt);
211           type_of_inner(cx, sp, subt)
212       }
213       _ {
214         fail "type_of_inner not implemented for this kind of type";
215       }
216     };
217     cx.lltypes.insert(t, llty);
218     ret llty;
219 }
220
221 fn type_of_tag(cx: @crate_ctxt, sp: span, did: ast::def_id, t: ty::t)
222     -> TypeRef {
223     let degen = vec::len(*ty::tag_variants(cx.tcx, did)) == 1u;
224     if check type_has_static_size(cx, t) {
225         let size = static_size_of_tag(cx, sp, t);
226         if !degen { T_tag(cx, size) }
227         else if size == 0u { T_struct([T_tag_variant(cx)]) }
228         else { T_array(T_i8(), size) }
229     }
230     else {
231         if degen { T_struct([T_tag_variant(cx)]) }
232         else { T_opaque_tag(cx) }
233     }
234 }
235
236 fn type_of_ty_param_bounds_and_ty(lcx: @local_ctxt, sp: span,
237                                  tpt: ty::ty_param_bounds_and_ty) -> TypeRef {
238     let cx = lcx.ccx;
239     let t = tpt.ty;
240     alt ty::struct(cx.tcx, t) {
241       ty::ty_fn(_) | ty::ty_native_fn(_, _) {
242         ret type_of_fn_from_ty(cx, sp, t, *tpt.bounds);
243       }
244       _ {
245         // fall through
246       }
247     }
248     // FIXME: could have a precondition on tpt, but that
249     // doesn't work right now because one predicate can't imply
250     // another
251     check (type_has_static_size(cx, t));
252     type_of(cx, sp, t)
253 }
254
255 fn type_of_or_i8(bcx: @block_ctxt, typ: ty::t) -> TypeRef {
256     let ccx = bcx_ccx(bcx);
257     if check type_has_static_size(ccx, typ) {
258         let sp = bcx.sp;
259         type_of(ccx, sp, typ)
260     } else { T_i8() }
261 }
262
263
264 // Name sanitation. LLVM will happily accept identifiers with weird names, but
265 // gas doesn't!
266 fn sanitize(s: str) -> str {
267     let result = "";
268     for c: u8 in s {
269         if c == '@' as u8 {
270             result += "boxed_";
271         } else {
272             if c == ',' as u8 {
273                 result += "_";
274             } else {
275                 if c == '{' as u8 || c == '(' as u8 {
276                     result += "_of_";
277                 } else {
278                     if c != 10u8 && c != '}' as u8 && c != ')' as u8 &&
279                            c != ' ' as u8 && c != '\t' as u8 && c != ';' as u8
280                        {
281                         let v = [c];
282                         result += str::unsafe_from_bytes(v);
283                     }
284                 }
285             }
286         }
287     }
288     ret result;
289 }
290
291
292 fn log_fn_time(ccx: @crate_ctxt, name: str, start: time::timeval,
293                end: time::timeval) {
294     let elapsed =
295         1000 * (end.sec - start.sec as int) +
296             ((end.usec as int) - (start.usec as int)) / 1000;
297     *ccx.stats.fn_times += [{ident: name, time: elapsed}];
298 }
299
300
301 fn decl_fn(llmod: ModuleRef, name: str, cc: uint, llty: TypeRef) -> ValueRef {
302     let llfn: ValueRef =
303         str::as_buf(name, {|buf|
304             llvm::LLVMGetOrInsertFunction(llmod, buf, llty) });
305     llvm::LLVMSetFunctionCallConv(llfn, cc);
306     ret llfn;
307 }
308
309 fn decl_cdecl_fn(llmod: ModuleRef, name: str, llty: TypeRef) -> ValueRef {
310     ret decl_fn(llmod, name, lib::llvm::LLVMCCallConv, llty);
311 }
312
313
314 // Only use this if you are going to actually define the function. It's
315 // not valid to simply declare a function as internal.
316 fn decl_internal_cdecl_fn(llmod: ModuleRef, name: str, llty: TypeRef) ->
317    ValueRef {
318     let llfn = decl_cdecl_fn(llmod, name, llty);
319     llvm::LLVMSetLinkage(llfn,
320                          lib::llvm::LLVMInternalLinkage as llvm::Linkage);
321     ret llfn;
322 }
323
324 fn get_extern_fn(externs: hashmap<str, ValueRef>, llmod: ModuleRef, name: str,
325                  cc: uint, ty: TypeRef) -> ValueRef {
326     if externs.contains_key(name) { ret externs.get(name); }
327     let f = decl_fn(llmod, name, cc, ty);
328     externs.insert(name, f);
329     ret f;
330 }
331
332 fn get_extern_const(externs: hashmap<str, ValueRef>, llmod: ModuleRef,
333                     name: str, ty: TypeRef) -> ValueRef {
334     if externs.contains_key(name) { ret externs.get(name); }
335     let c = str::as_buf(name, {|buf| llvm::LLVMAddGlobal(llmod, ty, buf) });
336     externs.insert(name, c);
337     ret c;
338 }
339
340 fn get_simple_extern_fn(cx: @block_ctxt,
341                         externs: hashmap<str, ValueRef>,
342                         llmod: ModuleRef,
343                         name: str, n_args: int) -> ValueRef {
344     let ccx = cx.fcx.lcx.ccx;
345     let inputs = vec::init_elt::<TypeRef>(ccx.int_type, n_args as uint);
346     let output = ccx.int_type;
347     let t = T_fn(inputs, output);
348     ret get_extern_fn(externs, llmod, name, lib::llvm::LLVMCCallConv, t);
349 }
350
351 fn trans_native_call(cx: @block_ctxt, externs: hashmap<str, ValueRef>,
352                      llmod: ModuleRef, name: str, args: [ValueRef]) ->
353    ValueRef {
354     let n: int = vec::len::<ValueRef>(args) as int;
355     let llnative: ValueRef =
356         get_simple_extern_fn(cx, externs, llmod, name, n);
357     let call_args: [ValueRef] = [];
358     for a: ValueRef in args {
359         call_args += [ZExtOrBitCast(cx, a, bcx_ccx(cx).int_type)];
360     }
361     ret Call(cx, llnative, call_args);
362 }
363
364 fn trans_free_if_not_gc(cx: @block_ctxt, v: ValueRef) -> @block_ctxt {
365     let ccx = bcx_ccx(cx);
366     if !ccx.sess.get_opts().do_gc {
367         Call(cx, ccx.upcalls.free,
368              [PointerCast(cx, v, T_ptr(T_i8())),
369               C_int(bcx_ccx(cx), 0)]);
370     }
371     ret cx;
372 }
373
374 fn trans_shared_free(cx: @block_ctxt, v: ValueRef) -> @block_ctxt {
375     Call(cx, bcx_ccx(cx).upcalls.shared_free,
376          [PointerCast(cx, v, T_ptr(T_i8()))]);
377     ret cx;
378 }
379
380 fn umax(cx: @block_ctxt, a: ValueRef, b: ValueRef) -> ValueRef {
381     let cond = ICmp(cx, lib::llvm::LLVMIntULT, a, b);
382     ret Select(cx, cond, b, a);
383 }
384
385 fn umin(cx: @block_ctxt, a: ValueRef, b: ValueRef) -> ValueRef {
386     let cond = ICmp(cx, lib::llvm::LLVMIntULT, a, b);
387     ret Select(cx, cond, a, b);
388 }
389
390 fn align_to(cx: @block_ctxt, off: ValueRef, align: ValueRef) -> ValueRef {
391     let mask = Sub(cx, align, C_int(bcx_ccx(cx), 1));
392     let bumped = Add(cx, off, mask);
393     ret And(cx, bumped, Not(cx, mask));
394 }
395
396
397 // Returns the real size of the given type for the current target.
398 fn llsize_of_real(cx: @crate_ctxt, t: TypeRef) -> uint {
399     ret llvm::LLVMStoreSizeOfType(cx.td.lltd, t);
400 }
401
402 // Returns the real alignment of the given type for the current target.
403 fn llalign_of_real(cx: @crate_ctxt, t: TypeRef) -> uint {
404     ret llvm::LLVMPreferredAlignmentOfType(cx.td.lltd, t);
405 }
406
407 fn llsize_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
408     ret llvm::LLVMConstIntCast(lib::llvm::llvm::LLVMSizeOf(t), cx.int_type,
409                                False);
410 }
411
412 fn llalign_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
413     ret llvm::LLVMConstIntCast(lib::llvm::llvm::LLVMAlignOf(t), cx.int_type,
414                                False);
415 }
416
417 fn size_of(cx: @block_ctxt, t: ty::t) -> result {
418     size_of_(cx, t, align_total)
419 }
420
421 tag align_mode {
422     align_total;
423     align_next(ty::t);
424 }
425
426 fn size_of_(cx: @block_ctxt, t: ty::t, mode: align_mode) -> result {
427     let ccx = bcx_ccx(cx);
428     if check type_has_static_size(ccx, t) {
429         let sp = cx.sp;
430         rslt(cx, llsize_of(bcx_ccx(cx), type_of(ccx, sp, t)))
431     } else { dynamic_size_of(cx, t, mode) }
432 }
433
434 fn align_of(cx: @block_ctxt, t: ty::t) -> result {
435     let ccx = bcx_ccx(cx);
436     if check type_has_static_size(ccx, t) {
437         let sp = cx.sp;
438         rslt(cx, llalign_of(bcx_ccx(cx), type_of(ccx, sp, t)))
439     } else { dynamic_align_of(cx, t) }
440 }
441
442 fn alloca(cx: @block_ctxt, t: TypeRef) -> ValueRef {
443     if cx.unreachable { ret llvm::LLVMGetUndef(t); }
444     ret Alloca(new_raw_block_ctxt(cx.fcx, cx.fcx.llstaticallocas), t);
445 }
446
447 fn dynastack_alloca(cx: @block_ctxt, t: TypeRef, n: ValueRef, ty: ty::t) ->
448    ValueRef {
449     if cx.unreachable { ret llvm::LLVMGetUndef(t); }
450     let bcx = cx;
451     let dy_cx = new_raw_block_ctxt(cx.fcx, cx.fcx.lldynamicallocas);
452     alt bcx_fcx(cx).llobstacktoken {
453       none. {
454         bcx_fcx(cx).llobstacktoken =
455             some(mk_obstack_token(bcx_ccx(cx), cx.fcx));
456       }
457       some(_) {/* no-op */ }
458     }
459
460     let dynastack_alloc = bcx_ccx(bcx).upcalls.dynastack_alloc;
461     let llsz = Mul(dy_cx,
462                    C_uint(bcx_ccx(bcx), llsize_of_real(bcx_ccx(bcx), t)),
463                    n);
464
465     let ti = none;
466     let lltydesc = get_tydesc(cx, ty, false, tps_normal, ti).result.val;
467
468     let llresult = Call(dy_cx, dynastack_alloc, [llsz, lltydesc]);
469     ret PointerCast(dy_cx, llresult, T_ptr(t));
470 }
471
472 fn mk_obstack_token(ccx: @crate_ctxt, fcx: @fn_ctxt) ->
473    ValueRef {
474     let cx = new_raw_block_ctxt(fcx, fcx.lldynamicallocas);
475     ret Call(cx, ccx.upcalls.dynastack_mark, []);
476 }
477
478
479 // Creates a simpler, size-equivalent type. The resulting type is guaranteed
480 // to have (a) the same size as the type that was passed in; (b) to be non-
481 // recursive. This is done by replacing all boxes in a type with boxed unit
482 // types.
483 fn simplify_type(ccx: @crate_ctxt, typ: ty::t) -> ty::t {
484     fn simplifier(ccx: @crate_ctxt, typ: ty::t) -> ty::t {
485         alt ty::struct(ccx.tcx, typ) {
486           ty::ty_box(_) { ret ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)); }
487           ty::ty_uniq(_) {
488             ret ty::mk_imm_uniq(ccx.tcx, ty::mk_nil(ccx.tcx));
489           }
490           ty::ty_fn(_) {
491             ret ty::mk_tup(ccx.tcx,
492                            [ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)),
493                             ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx))]);
494           }
495           ty::ty_obj(_) {
496             ret ty::mk_tup(ccx.tcx,
497                            [ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)),
498                             ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx))]);
499           }
500           ty::ty_res(_, sub, tps) {
501             let sub1 = ty::substitute_type_params(ccx.tcx, tps, sub);
502             ret ty::mk_tup(ccx.tcx,
503                            [ty::mk_int(ccx.tcx), simplify_type(ccx, sub1)]);
504           }
505           _ { ret typ; }
506         }
507     }
508     ret ty::fold_ty(ccx.tcx, ty::fm_general(bind simplifier(ccx, _)), typ);
509 }
510
511
512 // Computes the size of the data part of a non-dynamically-sized tag.
513 fn static_size_of_tag(cx: @crate_ctxt, sp: span, t: ty::t)
514     : type_has_static_size(cx, t) -> uint {
515     if cx.tag_sizes.contains_key(t) { ret cx.tag_sizes.get(t); }
516     alt ty::struct(cx.tcx, t) {
517       ty::ty_tag(tid, subtys) {
518         // Compute max(variant sizes).
519
520         let max_size = 0u;
521         let variants = ty::tag_variants(cx.tcx, tid);
522         for variant: ty::variant_info in *variants {
523             let tup_ty = simplify_type(cx, ty::mk_tup(cx.tcx, variant.args));
524             // Perform any type parameter substitutions.
525
526             tup_ty = ty::substitute_type_params(cx.tcx, subtys, tup_ty);
527             // Here we possibly do a recursive call.
528
529             // FIXME: Avoid this check. Since the parent has static
530             // size, any field must as well. There should be a way to
531             // express that with constrained types.
532             check (type_has_static_size(cx, tup_ty));
533             let this_size = llsize_of_real(cx, type_of(cx, sp, tup_ty));
534             if max_size < this_size { max_size = this_size; }
535         }
536         cx.tag_sizes.insert(t, max_size);
537         ret max_size;
538       }
539       _ {
540         cx.tcx.sess.span_fatal(sp, "non-tag passed to static_size_of_tag()");
541       }
542     }
543 }
544
545 fn dynamic_size_of(cx: @block_ctxt, t: ty::t, mode: align_mode) -> result {
546     fn align_elements(cx: @block_ctxt, elts: [ty::t],
547                       mode: align_mode) -> result {
548         //
549         // C padding rules:
550         //
551         //
552         //   - Pad after each element so that next element is aligned.
553         //   - Pad after final structure member so that whole structure
554         //     is aligned to max alignment of interior.
555         //
556
557         let off = C_int(bcx_ccx(cx), 0);
558         let max_align = C_int(bcx_ccx(cx), 1);
559         let bcx = cx;
560         for e: ty::t in elts {
561             let elt_align = align_of(bcx, e);
562             bcx = elt_align.bcx;
563             let elt_size = size_of(bcx, e);
564             bcx = elt_size.bcx;
565             let aligned_off = align_to(bcx, off, elt_align.val);
566             off = Add(bcx, aligned_off, elt_size.val);
567             max_align = umax(bcx, max_align, elt_align.val);
568         }
569         off = alt mode {
570           align_total. {
571             align_to(bcx, off, max_align)
572           }
573           align_next(t) {
574             let {bcx, val: align} = align_of(bcx, t);
575             align_to(bcx, off, align)
576           }
577         };
578         ret rslt(bcx, off);
579     }
580     alt ty::struct(bcx_tcx(cx), t) {
581       ty::ty_param(p, _) {
582         let szptr = field_of_tydesc(cx, t, false, abi::tydesc_field_size);
583         ret rslt(szptr.bcx, Load(szptr.bcx, szptr.val));
584       }
585       ty::ty_rec(flds) {
586         let tys: [ty::t] = [];
587         for f: ty::field in flds { tys += [f.mt.ty]; }
588         ret align_elements(cx, tys, mode);
589       }
590       ty::ty_tup(elts) {
591         let tys = [];
592         for tp in elts { tys += [tp]; }
593         ret align_elements(cx, tys, mode);
594       }
595       ty::ty_tag(tid, tps) {
596         let bcx = cx;
597         let ccx = bcx_ccx(bcx);
598         // Compute max(variant sizes).
599
600         let max_size: ValueRef = alloca(bcx, ccx.int_type);
601         Store(bcx, C_int(ccx, 0), max_size);
602         let variants = ty::tag_variants(bcx_tcx(bcx), tid);
603         for variant: ty::variant_info in *variants {
604             // Perform type substitution on the raw argument types.
605
606             let raw_tys: [ty::t] = variant.args;
607             let tys: [ty::t] = [];
608             for raw_ty: ty::t in raw_tys {
609                 let t = ty::substitute_type_params(bcx_tcx(cx), tps, raw_ty);
610                 tys += [t];
611             }
612             let rslt = align_elements(bcx, tys, mode);
613             bcx = rslt.bcx;
614             let this_size = rslt.val;
615             let old_max_size = Load(bcx, max_size);
616             Store(bcx, umax(bcx, this_size, old_max_size), max_size);
617         }
618         let max_size_val = Load(bcx, max_size);
619         let total_size =
620             if vec::len(*variants) != 1u {
621                 Add(bcx, max_size_val, llsize_of(ccx, ccx.int_type))
622             } else { max_size_val };
623         ret rslt(bcx, total_size);
624       }
625     }
626 }
627
628 fn dynamic_align_of(cx: @block_ctxt, t: ty::t) -> result {
629 // FIXME: Typestate constraint that shows this alt is
630 // exhaustive
631     alt ty::struct(bcx_tcx(cx), t) {
632       ty::ty_param(p, _) {
633         let aptr = field_of_tydesc(cx, t, false, abi::tydesc_field_align);
634         ret rslt(aptr.bcx, Load(aptr.bcx, aptr.val));
635       }
636       ty::ty_rec(flds) {
637         let a = C_int(bcx_ccx(cx), 1);
638         let bcx = cx;
639         for f: ty::field in flds {
640             let align = align_of(bcx, f.mt.ty);
641             bcx = align.bcx;
642             a = umax(bcx, a, align.val);
643         }
644         ret rslt(bcx, a);
645       }
646       ty::ty_tag(_, _) {
647         ret rslt(cx, C_int(bcx_ccx(cx), 1)); // FIXME: stub
648       }
649       ty::ty_tup(elts) {
650         let a = C_int(bcx_ccx(cx), 1);
651         let bcx = cx;
652         for e in elts {
653             let align = align_of(bcx, e);
654             bcx = align.bcx;
655             a = umax(bcx, a, align.val);
656         }
657         ret rslt(bcx, a);
658       }
659     }
660 }
661
662 // Increment a pointer by a given amount and then cast it to be a pointer
663 // to a given type.
664 fn bump_ptr(bcx: @block_ctxt, t: ty::t, base: ValueRef, sz: ValueRef) ->
665    ValueRef {
666     let raw = PointerCast(bcx, base, T_ptr(T_i8()));
667     let bumped = GEP(bcx, raw, [sz]);
668     let ccx = bcx_ccx(bcx);
669     if check type_has_static_size(ccx, t) {
670         let sp = bcx.sp;
671         let typ = T_ptr(type_of(ccx, sp, t));
672         PointerCast(bcx, bumped, typ)
673     } else { bumped }
674 }
675
676 // GEP_tup_like is a pain to use if you always have to precede it with a
677 // check.
678 fn GEP_tup_like_1(cx: @block_ctxt, t: ty::t, base: ValueRef, ixs: [int])
679     -> result {
680     check type_is_tup_like(cx, t);
681     ret GEP_tup_like(cx, t, base, ixs);
682 }
683
684 // Replacement for the LLVM 'GEP' instruction when field-indexing into a
685 // tuple-like structure (tup, rec) with a static index. This one is driven off
686 // ty::struct and knows what to do when it runs into a ty_param stuck in the
687 // middle of the thing it's GEP'ing into. Much like size_of and align_of,
688 // above.
689 fn GEP_tup_like(cx: @block_ctxt, t: ty::t, base: ValueRef, ixs: [int])
690     : type_is_tup_like(cx, t) -> result {
691     // It might be a static-known type. Handle this.
692     if !ty::type_has_dynamic_size(bcx_tcx(cx), t) {
693         ret rslt(cx, GEPi(cx, base, ixs));
694     }
695     // It is a dynamic-containing type that, if we convert directly to an LLVM
696     // TypeRef, will be all wrong; there's no proper LLVM type to represent
697     // it, and the lowering function will stick in i8* values for each
698     // ty_param, which is not right; the ty_params are all of some dynamic
699     // size.
700     //
701     // What we must do instead is sadder. We must look through the indices
702     // manually and split the input type into a prefix and a target. We then
703     // measure the prefix size, bump the input pointer by that amount, and
704     // cast to a pointer-to-target type.
705
706     // Given a type, an index vector and an element number N in that vector,
707     // calculate index X and the type that results by taking the first X-1
708     // elements of the type and splitting the Xth off. Return the prefix as
709     // well as the innermost Xth type.
710
711     fn split_type(ccx: @crate_ctxt, t: ty::t, ixs: [int], n: uint) ->
712        {prefix: [ty::t], target: ty::t} {
713         let len: uint = vec::len::<int>(ixs);
714         // We don't support 0-index or 1-index GEPs: The former is nonsense
715         // and the latter would only be meaningful if we supported non-0
716         // values for the 0th index (we don't).
717
718         assert (len > 1u);
719         if n == 0u {
720             // Since we're starting from a value that's a pointer to a
721             // *single* structure, the first index (in GEP-ese) should just be
722             // 0, to yield the pointee.
723
724             assert (ixs[n] == 0);
725             ret split_type(ccx, t, ixs, n + 1u);
726         }
727         assert (n < len);
728         let ix: int = ixs[n];
729         let prefix: [ty::t] = [];
730         let i: int = 0;
731         while i < ix {
732             prefix += [ty::get_element_type(ccx.tcx, t, i as uint)];
733             i += 1;
734         }
735         let selected = ty::get_element_type(ccx.tcx, t, i as uint);
736         if n == len - 1u {
737             // We are at the innermost index.
738
739             ret {prefix: prefix, target: selected};
740         } else {
741             // Not the innermost index; call self recursively to dig deeper.
742             // Once we get an inner result, append it current prefix and
743             // return to caller.
744
745             let inner = split_type(ccx, selected, ixs, n + 1u);
746             prefix += inner.prefix;
747             ret {prefix: prefix with inner};
748         }
749     }
750     // We make a fake prefix tuple-type here; luckily for measuring sizes
751     // the tuple parens are associative so it doesn't matter that we've
752     // flattened the incoming structure.
753
754     let s = split_type(bcx_ccx(cx), t, ixs, 0u);
755
756     let args = [];
757     for typ: ty::t in s.prefix { args += [typ]; }
758     let prefix_ty = ty::mk_tup(bcx_tcx(cx), args);
759
760     let bcx = cx;
761     let sz = size_of_(bcx, prefix_ty, align_next(s.target));
762     ret rslt(sz.bcx, bump_ptr(sz.bcx, s.target, base, sz.val));
763 }
764
765
766 // Replacement for the LLVM 'GEP' instruction when field indexing into a tag.
767 // This function uses GEP_tup_like() above and automatically performs casts as
768 // appropriate. @llblobptr is the data part of a tag value; its actual type is
769 // meaningless, as it will be cast away.
770 fn GEP_tag(cx: @block_ctxt, llblobptr: ValueRef, tag_id: ast::def_id,
771            variant_id: ast::def_id, ty_substs: [ty::t],
772            ix: uint) : valid_variant_index(ix, cx, tag_id, variant_id) ->
773    result {
774     let variant = ty::tag_variant_with_id(bcx_tcx(cx), tag_id, variant_id);
775     // Synthesize a tuple type so that GEP_tup_like() can work its magic.
776     // Separately, store the type of the element we're interested in.
777
778     let arg_tys = variant.args;
779
780     let true_arg_tys: [ty::t] = [];
781     for aty: ty::t in arg_tys {
782         let arg_ty = ty::substitute_type_params(bcx_tcx(cx), ty_substs, aty);
783         true_arg_tys += [arg_ty];
784     }
785
786     // We know that ix < len(variant.args) -- so
787     // it's safe to do this. (Would be nice to have
788     // typestate guarantee that a dynamic bounds check
789     // error can't happen here, but that's in the future.)
790     let elem_ty = true_arg_tys[ix];
791
792     let tup_ty = ty::mk_tup(bcx_tcx(cx), true_arg_tys);
793     // Cast the blob pointer to the appropriate type, if we need to (i.e. if
794     // the blob pointer isn't dynamically sized).
795
796     let llunionptr: ValueRef;
797     let sp = cx.sp;
798     let ccx = bcx_ccx(cx);
799     if check type_has_static_size(ccx, tup_ty) {
800         let llty = type_of(ccx, sp, tup_ty);
801         llunionptr = TruncOrBitCast(cx, llblobptr, T_ptr(llty));
802     } else { llunionptr = llblobptr; }
803
804     // Do the GEP_tup_like().
805     // Silly check -- postcondition on mk_tup?
806     check type_is_tup_like(cx, tup_ty);
807     let rs = GEP_tup_like(cx, tup_ty, llunionptr, [0, ix as int]);
808     // Cast the result to the appropriate type, if necessary.
809
810     let rs_ccx = bcx_ccx(rs.bcx);
811     let val =
812         if check type_has_static_size(rs_ccx, elem_ty) {
813             let llelemty = type_of(rs_ccx, sp, elem_ty);
814             PointerCast(rs.bcx, rs.val, T_ptr(llelemty))
815         } else { rs.val };
816
817     ret rslt(rs.bcx, val);
818 }
819
820 // trans_shared_malloc: expects a type indicating which pointer type we want
821 // and a size indicating how much space we want malloc'd.
822 fn trans_shared_malloc(cx: @block_ctxt, llptr_ty: TypeRef, llsize: ValueRef)
823    -> result {
824     // FIXME: need a table to collect tydesc globals.
825
826     let tydesc = C_null(T_ptr(bcx_ccx(cx).tydesc_type));
827     let rval =
828         Call(cx, bcx_ccx(cx).upcalls.shared_malloc,
829              [llsize, tydesc]);
830     ret rslt(cx, PointerCast(cx, rval, llptr_ty));
831 }
832
833 // trans_malloc_boxed_raw: expects an unboxed type and returns a pointer to
834 // enough space for something of that type, along with space for a reference
835 // count; in other words, it allocates a box for something of that type.
836 fn trans_malloc_boxed_raw(cx: @block_ctxt, t: ty::t) -> result {
837     let bcx = cx;
838
839     // Synthesize a fake box type structurally so we have something
840     // to measure the size of.
841
842     // We synthesize two types here because we want both the type of the
843     // pointer and the pointee.  boxed_body is the type that we measure the
844     // size of; box_ptr is the type that's converted to a TypeRef and used as
845     // the pointer cast target in trans_raw_malloc.
846
847     // The mk_int here is the space being
848     // reserved for the refcount.
849     let boxed_body = ty::mk_tup(bcx_tcx(bcx), [ty::mk_int(bcx_tcx(cx)), t]);
850     let box_ptr = ty::mk_imm_box(bcx_tcx(bcx), t);
851     let r = size_of(cx, boxed_body);
852     let llsz = r.val; bcx = r.bcx;
853
854     // Grab the TypeRef type of box_ptr, because that's what trans_raw_malloc
855     // wants.
856     // FIXME: Could avoid this check with a postcondition on mk_imm_box?
857     // (requires Issue #586)
858     let ccx = bcx_ccx(bcx);
859     let sp = bcx.sp;
860     check (type_has_static_size(ccx, box_ptr));
861     let llty = type_of(ccx, sp, box_ptr);
862
863     let ti = none;
864     let tydesc_result = get_tydesc(bcx, t, true, tps_normal, ti);
865     let lltydesc = tydesc_result.result.val; bcx = tydesc_result.result.bcx;
866
867     let rval = Call(cx, ccx.upcalls.malloc,
868                     [llsz, lltydesc]);
869     ret rslt(cx, PointerCast(cx, rval, llty));
870 }
871
872 // trans_malloc_boxed: usefully wraps trans_malloc_box_raw; allocates a box,
873 // initializes the reference count to 1, and pulls out the body and rc
874 fn trans_malloc_boxed(cx: @block_ctxt, t: ty::t) ->
875    {bcx: @block_ctxt, box: ValueRef, body: ValueRef} {
876     let res = trans_malloc_boxed_raw(cx, t);
877     let box = res.val;
878     let rc = GEPi(res.bcx, box, [0, abi::box_rc_field_refcnt]);
879     Store(res.bcx, C_int(bcx_ccx(cx), 1), rc);
880     let body = GEPi(res.bcx, box, [0, abi::box_rc_field_body]);
881     ret {bcx: res.bcx, box: res.val, body: body};
882 }
883
884 // Type descriptor and type glue stuff
885
886 // Given a type and a field index into its corresponding type descriptor,
887 // returns an LLVM ValueRef of that field from the tydesc, generating the
888 // tydesc if necessary.
889 fn field_of_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool, field: int) ->
890    result {
891     let ti = none::<@tydesc_info>;
892     let tydesc = get_tydesc(cx, t, escapes, tps_normal, ti).result;
893     ret rslt(tydesc.bcx,
894              GEPi(tydesc.bcx, tydesc.val, [0, field]));
895 }
896
897
898 // Given a type containing ty params, build a vector containing a ValueRef for
899 // each of the ty params it uses (from the current frame) and a vector of the
900 // indices of the ty params present in the type. This is used solely for
901 // constructing derived tydescs.
902 fn linearize_ty_params(cx: @block_ctxt, t: ty::t) ->
903    {params: [uint], descs: [ValueRef]} {
904     let param_vals: [ValueRef] = [];
905     let param_defs: [uint] = [];
906     type rr =
907         {cx: @block_ctxt, mutable vals: [ValueRef], mutable defs: [uint]};
908
909     fn linearizer(r: @rr, t: ty::t) {
910         alt ty::struct(bcx_tcx(r.cx), t) {
911           ty::ty_param(pid, _) {
912             let seen: bool = false;
913             for d: uint in r.defs { if d == pid { seen = true; } }
914             if !seen {
915                 r.vals += [r.cx.fcx.lltyparams[pid].desc];
916                 r.defs += [pid];
917             }
918           }
919           _ { }
920         }
921     }
922     let x = @{cx: cx, mutable vals: param_vals, mutable defs: param_defs};
923     let f = bind linearizer(x, _);
924     ty::walk_ty(bcx_tcx(cx), f, t);
925     ret {params: x.defs, descs: x.vals};
926 }
927
928 fn trans_stack_local_derived_tydesc(cx: @block_ctxt, llsz: ValueRef,
929                                     llalign: ValueRef, llroottydesc: ValueRef,
930                                     llfirstparam: ValueRef, n_params: uint,
931                                     obj_params: uint) -> ValueRef {
932     let llmyroottydesc = alloca(cx, bcx_ccx(cx).tydesc_type);
933
934     // By convention, desc 0 is the root descriptor.
935     let llroottydesc = Load(cx, llroottydesc);
936     Store(cx, llroottydesc, llmyroottydesc);
937
938     // Store a pointer to the rest of the descriptors.
939     let ccx = bcx_ccx(cx);
940     store_inbounds(cx, llfirstparam, llmyroottydesc,
941                    [0, abi::tydesc_field_first_param]);
942     store_inbounds(cx, C_uint(ccx, n_params), llmyroottydesc,
943                    [0, abi::tydesc_field_n_params]);
944     store_inbounds(cx, llsz, llmyroottydesc,
945                    [0, abi::tydesc_field_size]);
946     store_inbounds(cx, llalign, llmyroottydesc,
947                    [0, abi::tydesc_field_align]);
948     store_inbounds(cx, C_uint(ccx, obj_params), llmyroottydesc,
949                    [0, abi::tydesc_field_obj_params]);
950     ret llmyroottydesc;
951 }
952
953 // Objects and closures store their type parameters differently (in the object
954 // or closure itself rather than in the type descriptor).
955 tag ty_param_storage { tps_normal; tps_obj(uint); tps_fn(uint); }
956
957 fn get_derived_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool,
958                       storage: ty_param_storage,
959                       &static_ti: option::t<@tydesc_info>) -> result {
960     alt cx.fcx.derived_tydescs.find(t) {
961       some(info) {
962         // If the tydesc escapes in this context, the cached derived
963         // tydesc also has to be one that was marked as escaping.
964         if !(escapes && !info.escapes) && storage == tps_normal {
965             ret rslt(cx, info.lltydesc);
966         }
967       }
968       none. {/* fall through */ }
969     }
970
971     let is_obj_body;
972     alt storage {
973         tps_normal. { is_obj_body = false; }
974         tps_obj(_) | tps_fn(_) { is_obj_body = true; }
975     }
976
977     bcx_ccx(cx).stats.n_derived_tydescs += 1u;
978     let bcx = new_raw_block_ctxt(cx.fcx, cx.fcx.llderivedtydescs);
979     let tys = linearize_ty_params(bcx, t);
980     let root_ti = get_static_tydesc(bcx, t, tys.params, is_obj_body);
981     static_ti = some::<@tydesc_info>(root_ti);
982     lazily_emit_all_tydesc_glue(cx, static_ti);
983     let root = root_ti.tydesc;
984     let sz = size_of(bcx, t);
985     bcx = sz.bcx;
986     let align = align_of(bcx, t);
987     bcx = align.bcx;
988
989     // Store the captured type descriptors in an alloca if the caller isn't
990     // promising to do so itself.
991     let n_params = ty::count_ty_params(bcx_tcx(bcx), t);
992
993     assert (n_params == vec::len::<uint>(tys.params));
994     assert (n_params == vec::len::<ValueRef>(tys.descs));
995
996     let llparamtydescs =
997         alloca(bcx, T_array(T_ptr(bcx_ccx(bcx).tydesc_type), n_params + 1u));
998     let i = 0;
999
1000     // If the type descriptor escapes, we need to add in the root as
1001     // the first parameter, because upcall_get_type_desc() expects it.
1002     if escapes {
1003         Store(bcx, root, GEPi(bcx, llparamtydescs, [0, 0]));
1004         i += 1;
1005     }
1006
1007     for td: ValueRef in tys.descs {
1008         Store(bcx, td, GEPi(bcx, llparamtydescs, [0, i]));
1009         i += 1;
1010     }
1011
1012     let llfirstparam =
1013         PointerCast(bcx, llparamtydescs,
1014                     T_ptr(T_ptr(bcx_ccx(bcx).tydesc_type)));
1015
1016     // The top bit indicates whether this type descriptor describes an object
1017     // (0) or a function (1).
1018     let obj_params;
1019     alt storage {
1020       tps_normal. { obj_params = 0u; }
1021       tps_obj(np) { obj_params = np; }
1022       tps_fn(np) { obj_params = 0x80000000u | np; }
1023     }
1024
1025     let v;
1026     if escapes {
1027         let ccx = bcx_ccx(bcx);
1028         let td_val =
1029             Call(bcx, ccx.upcalls.get_type_desc,
1030                  [C_null(T_ptr(T_nil())), sz.val,
1031                   align.val, C_uint(ccx, 1u + n_params), llfirstparam,
1032                   C_uint(ccx, obj_params)]);
1033         v = td_val;
1034     } else {
1035         v =
1036             trans_stack_local_derived_tydesc(bcx, sz.val, align.val, root,
1037                                              llfirstparam, n_params,
1038                                              obj_params);
1039     }
1040     bcx.fcx.derived_tydescs.insert(t, {lltydesc: v, escapes: escapes});
1041     ret rslt(cx, v);
1042 }
1043
1044 type get_tydesc_result = {kind: tydesc_kind, result: result};
1045
1046 fn get_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool,
1047               storage: ty_param_storage, &static_ti: option::t<@tydesc_info>)
1048    -> get_tydesc_result {
1049
1050     // Is the supplied type a type param? If so, return the passed-in tydesc.
1051     alt ty::type_param(bcx_tcx(cx), t) {
1052       some(id) {
1053         if id < vec::len(cx.fcx.lltyparams) {
1054             ret {kind: tk_param,
1055                  result: rslt(cx, cx.fcx.lltyparams[id].desc)};
1056         } else {
1057             bcx_tcx(cx).sess.span_bug(cx.sp,
1058                                       "Unbound typaram in get_tydesc: " +
1059                                           "t = " +
1060                                           ty_to_str(bcx_tcx(cx), t) +
1061                                           " ty_param = " +
1062                                           uint::str(id));
1063         }
1064       }
1065       none. {/* fall through */ }
1066     }
1067
1068     // Does it contain a type param? If so, generate a derived tydesc.
1069     if ty::type_contains_params(bcx_tcx(cx), t) {
1070         ret {kind: tk_derived,
1071              result: get_derived_tydesc(cx, t, escapes, storage, static_ti)};
1072     }
1073     // Otherwise, generate a tydesc if necessary, and return it.
1074     let info = get_static_tydesc(cx, t, [], false);
1075     static_ti = some::<@tydesc_info>(info);
1076     ret {kind: tk_static, result: rslt(cx, info.tydesc)};
1077 }
1078
1079 fn get_static_tydesc(cx: @block_ctxt, t: ty::t, ty_params: [uint],
1080                      is_obj_body: bool) -> @tydesc_info {
1081     alt bcx_ccx(cx).tydescs.find(t) {
1082       some(info) { ret info; }
1083       none. {
1084         bcx_ccx(cx).stats.n_static_tydescs += 1u;
1085         let info = declare_tydesc(cx.fcx.lcx, cx.sp, t, ty_params,
1086                                   is_obj_body);
1087         bcx_ccx(cx).tydescs.insert(t, info);
1088         ret info;
1089       }
1090     }
1091 }
1092
1093 fn set_no_inline(f: ValueRef) {
1094     llvm::LLVMAddFunctionAttr(f,
1095                               lib::llvm::LLVMNoInlineAttribute as
1096                                   lib::llvm::llvm::Attribute,
1097                               0u);
1098 }
1099
1100 // Tell LLVM to emit the information necessary to unwind the stack for the
1101 // function f.
1102 fn set_uwtable(f: ValueRef) {
1103     llvm::LLVMAddFunctionAttr(f,
1104                               lib::llvm::LLVMUWTableAttribute as
1105                                   lib::llvm::llvm::Attribute,
1106                               0u);
1107 }
1108
1109 fn set_always_inline(f: ValueRef) {
1110     llvm::LLVMAddFunctionAttr(f,
1111                               lib::llvm::LLVMAlwaysInlineAttribute as
1112                                   lib::llvm::llvm::Attribute,
1113                               0u);
1114 }
1115
1116 fn set_custom_stack_growth_fn(f: ValueRef) {
1117     // TODO: Remove this hack to work around the lack of u64 in the FFI.
1118     llvm::LLVMAddFunctionAttr(f, 0 as lib::llvm::llvm::Attribute, 1u);
1119 }
1120
1121 fn set_glue_inlining(cx: @local_ctxt, f: ValueRef, t: ty::t) {
1122     if ty::type_is_structural(cx.ccx.tcx, t) {
1123         set_no_inline(f);
1124     } else { set_always_inline(f); }
1125 }
1126
1127
1128 // Generates the declaration for (but doesn't emit) a type descriptor.
1129 fn declare_tydesc(cx: @local_ctxt, sp: span, t: ty::t, ty_params: [uint],
1130                   is_obj_body: bool) ->
1131    @tydesc_info {
1132     log(debug, "+++ declare_tydesc " + ty_to_str(cx.ccx.tcx, t));
1133     let ccx = cx.ccx;
1134     let llsize;
1135     let llalign;
1136     if check type_has_static_size(ccx, t) {
1137         let llty = type_of(ccx, sp, t);
1138         llsize = llsize_of(ccx, llty);
1139         llalign = llalign_of(ccx, llty);
1140     } else {
1141         // These will be overwritten as the derived tydesc is generated, so
1142         // we create placeholder values.
1143
1144         llsize = C_int(ccx, 0);
1145         llalign = C_int(ccx, 0);
1146     }
1147     let name;
1148     if cx.ccx.sess.get_opts().debuginfo {
1149         name = mangle_internal_name_by_type_only(cx.ccx, t, "tydesc");
1150         name = sanitize(name);
1151     } else { name = mangle_internal_name_by_seq(cx.ccx, "tydesc"); }
1152     let gvar =
1153         str::as_buf(name,
1154                     {|buf|
1155                         llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type, buf)
1156                     });
1157     let info =
1158         @{ty: t,
1159           tydesc: gvar,
1160           size: llsize,
1161           align: llalign,
1162           mutable take_glue: none::<ValueRef>,
1163           mutable drop_glue: none::<ValueRef>,
1164           mutable free_glue: none::<ValueRef>,
1165           mutable cmp_glue: none::<ValueRef>,
1166           ty_params: ty_params,
1167           is_obj_body: is_obj_body};
1168     log(debug, "--- declare_tydesc " + ty_to_str(cx.ccx.tcx, t));
1169     ret info;
1170 }
1171
1172 type glue_helper = fn(@block_ctxt, ValueRef, ty::t);
1173
1174 fn declare_generic_glue(cx: @local_ctxt, t: ty::t, llfnty: TypeRef, name: str)
1175    -> ValueRef {
1176     let name = name;
1177     let fn_nm;
1178     if cx.ccx.sess.get_opts().debuginfo {
1179         fn_nm = mangle_internal_name_by_type_only(cx.ccx, t, "glue_" + name);
1180         fn_nm = sanitize(fn_nm);
1181     } else { fn_nm = mangle_internal_name_by_seq(cx.ccx, "glue_" + name); }
1182     let llfn = decl_cdecl_fn(cx.ccx.llmod, fn_nm, llfnty);
1183     set_glue_inlining(cx, llfn, t);
1184     ret llfn;
1185 }
1186
1187 // FIXME: was this causing the leak?
1188 fn make_generic_glue_inner(cx: @local_ctxt, sp: span, t: ty::t,
1189                            llfn: ValueRef, helper: glue_helper,
1190                            ty_params: [uint]) -> ValueRef {
1191     let fcx = new_fn_ctxt(cx, sp, llfn);
1192     llvm::LLVMSetLinkage(llfn,
1193                          lib::llvm::LLVMInternalLinkage as llvm::Linkage);
1194     cx.ccx.stats.n_glues_created += 1u;
1195     // Any nontrivial glue is with values passed *by alias*; this is a
1196     // requirement since in many contexts glue is invoked indirectly and
1197     // the caller has no idea if it's dealing with something that can be
1198     // passed by value.
1199
1200     let ccx = cx.ccx;
1201     let llty =
1202         if check type_has_static_size(ccx, t) {
1203             T_ptr(type_of(ccx, sp, t))
1204         } else { T_ptr(T_i8()) };
1205
1206     let ty_param_count = vec::len::<uint>(ty_params);
1207     let lltyparams = llvm::LLVMGetParam(llfn, 2u);
1208     let load_env_bcx = new_raw_block_ctxt(fcx, fcx.llloadenv);
1209     let lltydescs = [mutable];
1210     let p = 0u;
1211     while p < ty_param_count {
1212         let llparam = GEPi(load_env_bcx, lltyparams, [p as int]);
1213         llparam = Load(load_env_bcx, llparam);
1214         vec::grow_set(lltydescs, ty_params[p], 0 as ValueRef, llparam);
1215         p += 1u;
1216     }
1217
1218     fcx.lltyparams = vec::map_mut(lltydescs, {|d| {desc: d, dicts: none}});
1219
1220     let bcx = new_top_block_ctxt(fcx);
1221     let lltop = bcx.llbb;
1222     let llrawptr0 = llvm::LLVMGetParam(llfn, 3u);
1223     let llval0 = BitCast(bcx, llrawptr0, llty);
1224     helper(bcx, llval0, t);
1225     finish_fn(fcx, lltop);
1226     ret llfn;
1227 }
1228
1229 fn make_generic_glue(cx: @local_ctxt, sp: span, t: ty::t, llfn: ValueRef,
1230                      helper: glue_helper, ty_params: [uint], name: str) ->
1231    ValueRef {
1232     if !cx.ccx.sess.get_opts().stats {
1233         ret make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
1234     }
1235
1236     let start = time::get_time();
1237     let llval = make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
1238     let end = time::get_time();
1239     log_fn_time(cx.ccx, "glue " + name + " " + ty_to_short_str(cx.ccx.tcx, t),
1240                 start, end);
1241     ret llval;
1242 }
1243
1244 fn emit_tydescs(ccx: @crate_ctxt) {
1245     ccx.tydescs.items {|key, val|
1246         let glue_fn_ty = T_ptr(T_glue_fn(ccx));
1247         let cmp_fn_ty = T_ptr(T_cmp_glue_fn(ccx));
1248         let ti = val;
1249         let take_glue =
1250             alt ti.take_glue {
1251               none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1252               some(v) { ccx.stats.n_real_glues += 1u; v }
1253             };
1254         let drop_glue =
1255             alt ti.drop_glue {
1256               none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1257               some(v) { ccx.stats.n_real_glues += 1u; v }
1258             };
1259         let free_glue =
1260             alt ti.free_glue {
1261               none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1262               some(v) { ccx.stats.n_real_glues += 1u; v }
1263             };
1264         let cmp_glue =
1265             alt ti.cmp_glue {
1266               none. { ccx.stats.n_null_glues += 1u; C_null(cmp_fn_ty) }
1267               some(v) { ccx.stats.n_real_glues += 1u; v }
1268             };
1269
1270         let shape = shape::shape_of(ccx, key, ti.ty_params,
1271                                     ti.is_obj_body);
1272         let shape_tables =
1273             llvm::LLVMConstPointerCast(ccx.shape_cx.llshapetables,
1274                                        T_ptr(T_i8()));
1275
1276         let tydesc =
1277             C_named_struct(ccx.tydesc_type,
1278                            [C_null(T_ptr(T_ptr(ccx.tydesc_type))),
1279                             ti.size, // size
1280                             ti.align, // align
1281                             take_glue, // take_glue
1282                             drop_glue, // drop_glue
1283                             free_glue, // free_glue
1284                             C_null(T_ptr(T_i8())), // unused
1285                             C_null(glue_fn_ty), // sever_glue
1286                             C_null(glue_fn_ty), // mark_glue
1287                             C_null(glue_fn_ty), // unused
1288                             cmp_glue, // cmp_glue
1289                             C_shape(ccx, shape), // shape
1290                             shape_tables, // shape_tables
1291                             C_int(ccx, 0), // n_params
1292                             C_int(ccx, 0)]); // n_obj_params
1293
1294         let gvar = ti.tydesc;
1295         llvm::LLVMSetInitializer(gvar, tydesc);
1296         llvm::LLVMSetGlobalConstant(gvar, True);
1297         llvm::LLVMSetLinkage(gvar,
1298                              lib::llvm::LLVMInternalLinkage as llvm::Linkage);
1299     };
1300 }
1301
1302 fn make_take_glue(cx: @block_ctxt, v: ValueRef, t: ty::t) {
1303
1304     let bcx = cx;
1305     let tcx = bcx_tcx(cx);
1306     // NB: v is an *alias* of type t here, not a direct value.
1307     bcx = alt ty::struct(tcx, t) {
1308       ty::ty_box(_) {
1309         incr_refcnt_of_boxed(bcx, Load(bcx, v))
1310       }
1311       ty::ty_uniq(_) {
1312         check trans_uniq::type_is_unique_box(bcx, t);
1313         let r = trans_uniq::duplicate(bcx, Load(bcx, v), t);
1314         Store(r.bcx, r.val, v);
1315         r.bcx
1316       }
1317       ty::ty_vec(_) | ty::ty_str. {
1318         let r = tvec::duplicate(bcx, Load(bcx, v), t);
1319         Store(r.bcx, r.val, v);
1320         r.bcx
1321       }
1322       ty::ty_send_type. {
1323         // sendable type descriptors are basically unique pointers,
1324         // they must be cloned when copied:
1325         let r = Load(bcx, v);
1326         let s = Call(bcx, bcx_ccx(bcx).upcalls.create_shared_type_desc, [r]);
1327         Store(bcx, s, v);
1328         bcx
1329       }
1330       ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1331         trans_closure::make_fn_glue(bcx, v, t, take_ty)
1332       }
1333       ty::ty_opaque_closure. {
1334         trans_closure::call_opaque_closure_glue(
1335             bcx, v, abi::tydesc_field_take_glue)
1336       }
1337       _ when ty::type_is_structural(bcx_tcx(bcx), t) {
1338         iter_structural_ty(bcx, v, t, take_ty)
1339       }
1340       _ { bcx }
1341     };
1342
1343     build_return(bcx);
1344 }
1345
1346 fn incr_refcnt_of_boxed(cx: @block_ctxt, box_ptr: ValueRef) -> @block_ctxt {
1347     let ccx = bcx_ccx(cx);
1348     let rc_ptr =
1349         GEPi(cx, box_ptr, [0, abi::box_rc_field_refcnt]);
1350     let rc = Load(cx, rc_ptr);
1351     rc = Add(cx, rc, C_int(ccx, 1));
1352     Store(cx, rc, rc_ptr);
1353     ret cx;
1354 }
1355
1356 fn free_box(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1357     ret alt ty::struct(bcx_tcx(bcx), t) {
1358       ty::ty_box(body_mt) {
1359         let v = PointerCast(bcx, v, type_of_1(bcx, t));
1360         let body = GEPi(bcx, v, [0, abi::box_rc_field_body]);
1361         let bcx = drop_ty(bcx, body, body_mt.ty);
1362         trans_free_if_not_gc(bcx, v)
1363       }
1364
1365       _ { fail "free_box invoked with non-box type"; }
1366     };
1367 }
1368
1369 fn make_free_glue(bcx: @block_ctxt, v: ValueRef, t: ty::t) {
1370     // v is a pointer to the actual box component of the type here. The
1371     // ValueRef will have the wrong type here (make_generic_glue is casting
1372     // everything to a pointer to the type that the glue acts on).
1373     let bcx = alt ty::struct(bcx_tcx(bcx), t) {
1374       ty::ty_box(body_mt) {
1375         free_box(bcx, v, t)
1376       }
1377       ty::ty_uniq(content_mt) {
1378         check trans_uniq::type_is_unique_box(bcx, t);
1379         let v = PointerCast(bcx, v, type_of_1(bcx, t));
1380         trans_uniq::make_free_glue(bcx, v, t)
1381       }
1382       ty::ty_vec(_) | ty::ty_str. {
1383         tvec::make_free_glue(bcx, PointerCast(bcx, v, type_of_1(bcx, t)), t)
1384       }
1385       ty::ty_obj(_) {
1386         // Call through the obj's own fields-drop glue first.
1387         // Then free the body.
1388         let ccx = bcx_ccx(bcx);
1389         let llbox_ty = T_opaque_obj_ptr(ccx);
1390         let b = PointerCast(bcx, v, llbox_ty);
1391         let body = GEPi(bcx, b, [0, abi::box_rc_field_body]);
1392         let tydescptr =
1393             GEPi(bcx, body, [0, abi::obj_body_elt_tydesc]);
1394         let tydesc = Load(bcx, tydescptr);
1395         let ti = none;
1396         call_tydesc_glue_full(bcx, body, tydesc,
1397                               abi::tydesc_field_drop_glue, ti);
1398         trans_free_if_not_gc(bcx, b)
1399       }
1400       ty::ty_send_type. {
1401         // sendable type descriptors are basically unique pointers,
1402         // they must be freed.
1403         trans_shared_free(bcx, v)
1404       }
1405       ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1406         trans_closure::make_fn_glue(bcx, v, t, free_ty)
1407       }
1408       ty::ty_opaque_closure. {
1409         trans_closure::call_opaque_closure_glue(
1410             bcx, v, abi::tydesc_field_free_glue)
1411       }
1412       _ { bcx }
1413     };
1414     build_return(bcx);
1415 }
1416
1417 fn make_drop_glue(bcx: @block_ctxt, v0: ValueRef, t: ty::t) {
1418     // NB: v0 is an *alias* of type t here, not a direct value.
1419     let ccx = bcx_ccx(bcx);
1420     let bcx =
1421         alt ty::struct(ccx.tcx, t) {
1422           ty::ty_box(_) { decr_refcnt_maybe_free(bcx, Load(bcx, v0), t) }
1423           ty::ty_uniq(_) | ty::ty_vec(_) | ty::ty_str. | ty::ty_send_type. {
1424             free_ty(bcx, Load(bcx, v0), t)
1425           }
1426           ty::ty_obj(_) {
1427             let box_cell =
1428                 GEPi(bcx, v0, [0, abi::obj_field_box]);
1429             decr_refcnt_maybe_free(bcx, Load(bcx, box_cell), t)
1430           }
1431           ty::ty_res(did, inner, tps) {
1432             trans_res_drop(bcx, v0, did, inner, tps)
1433           }
1434           ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1435             trans_closure::make_fn_glue(bcx, v0, t, drop_ty)
1436           }
1437           ty::ty_opaque_closure. {
1438             trans_closure::call_opaque_closure_glue(
1439                 bcx, v0, abi::tydesc_field_drop_glue)
1440           }
1441           _ {
1442             if ty::type_needs_drop(ccx.tcx, t) &&
1443                ty::type_is_structural(ccx.tcx, t) {
1444                 iter_structural_ty(bcx, v0, t, drop_ty)
1445             } else { bcx }
1446           }
1447         };
1448     build_return(bcx);
1449 }
1450
1451 fn trans_res_drop(cx: @block_ctxt, rs: ValueRef, did: ast::def_id,
1452                   inner_t: ty::t, tps: [ty::t]) -> @block_ctxt {
1453     let ccx = bcx_ccx(cx);
1454     let inner_t_s = ty::substitute_type_params(ccx.tcx, tps, inner_t);
1455     let tup_ty = ty::mk_tup(ccx.tcx, [ty::mk_int(ccx.tcx), inner_t_s]);
1456     let drop_cx = new_sub_block_ctxt(cx, "drop res");
1457     let next_cx = new_sub_block_ctxt(cx, "next");
1458
1459     // Silly check
1460     check type_is_tup_like(cx, tup_ty);
1461     let drop_flag = GEP_tup_like(cx, tup_ty, rs, [0, 0]);
1462     let cx = drop_flag.bcx;
1463     let null_test = IsNull(cx, Load(cx, drop_flag.val));
1464     CondBr(cx, null_test, next_cx.llbb, drop_cx.llbb);
1465     cx = drop_cx;
1466
1467     check type_is_tup_like(cx, tup_ty);
1468     let val = GEP_tup_like(cx, tup_ty, rs, [0, 1]);
1469     cx = val.bcx;
1470     // Find and call the actual destructor.
1471     let dtor_addr = trans_common::get_res_dtor(ccx, cx.sp, did, inner_t);
1472     let args = [cx.fcx.llretptr, null_env_ptr(cx)];
1473     for tp: ty::t in tps {
1474         let ti: option::t<@tydesc_info> = none;
1475         let td = get_tydesc(cx, tp, false, tps_normal, ti).result;
1476         args += [td.val];
1477         cx = td.bcx;
1478     }
1479     // Kludge to work around the fact that we know the precise type of the
1480     // value here, but the dtor expects a type that still has opaque pointers
1481     // for type variables.
1482     let val_llty = lib::llvm::fn_ty_param_tys
1483         (llvm::LLVMGetElementType
1484          (llvm::LLVMTypeOf(dtor_addr)))[vec::len(args)];
1485     let val_cast = BitCast(cx, val.val, val_llty);
1486     Call(cx, dtor_addr, args + [val_cast]);
1487
1488     cx = drop_ty(cx, val.val, inner_t_s);
1489     // FIXME #1184: Resource flag is larger than necessary
1490     Store(cx, C_int(ccx, 0), drop_flag.val);
1491     Br(cx, next_cx.llbb);
1492     ret next_cx;
1493 }
1494
1495 fn decr_refcnt_maybe_free(cx: @block_ctxt, box_ptr: ValueRef, t: ty::t)
1496     -> @block_ctxt {
1497     let ccx = bcx_ccx(cx);
1498     let rc_adj_cx = new_sub_block_ctxt(cx, "rc--");
1499     let free_cx = new_sub_block_ctxt(cx, "free");
1500     let next_cx = new_sub_block_ctxt(cx, "next");
1501     let llbox_ty = T_opaque_obj_ptr(ccx);
1502     let box_ptr = PointerCast(cx, box_ptr, llbox_ty);
1503     let null_test = IsNull(cx, box_ptr);
1504     CondBr(cx, null_test, next_cx.llbb, rc_adj_cx.llbb);
1505     let rc_ptr =
1506         GEPi(rc_adj_cx, box_ptr, [0, abi::box_rc_field_refcnt]);
1507     let rc = Load(rc_adj_cx, rc_ptr);
1508     rc = Sub(rc_adj_cx, rc, C_int(ccx, 1));
1509     Store(rc_adj_cx, rc, rc_ptr);
1510     let zero_test = ICmp(rc_adj_cx, lib::llvm::LLVMIntEQ, C_int(ccx, 0), rc);
1511     CondBr(rc_adj_cx, zero_test, free_cx.llbb, next_cx.llbb);
1512     let free_cx = free_ty(free_cx, box_ptr, t);
1513     Br(free_cx, next_cx.llbb);
1514     ret next_cx;
1515 }
1516
1517
1518 // Structural comparison: a rather involved form of glue.
1519 fn maybe_name_value(cx: @crate_ctxt, v: ValueRef, s: str) {
1520     if cx.sess.get_opts().save_temps {
1521         let _: () = str::as_buf(s, {|buf| llvm::LLVMSetValueName(v, buf) });
1522     }
1523 }
1524
1525
1526 // Used only for creating scalar comparison glue.
1527 tag scalar_type { nil_type; signed_int; unsigned_int; floating_point; }
1528
1529
1530 fn compare_scalar_types(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef,
1531                         t: ty::t, op: ast::binop) -> result {
1532     let f = bind compare_scalar_values(cx, lhs, rhs, _, op);
1533
1534     alt ty::struct(bcx_tcx(cx), t) {
1535       ty::ty_nil. { ret rslt(cx, f(nil_type)); }
1536       ty::ty_bool. | ty::ty_ptr(_) { ret rslt(cx, f(unsigned_int)); }
1537       ty::ty_int(_) { ret rslt(cx, f(signed_int)); }
1538       ty::ty_uint(_) { ret rslt(cx, f(unsigned_int)); }
1539       ty::ty_float(_) { ret rslt(cx, f(floating_point)); }
1540       ty::ty_type. {
1541         ret rslt(trans_fail(cx, none,
1542                             "attempt to compare values of type type"),
1543                  C_nil());
1544       }
1545       ty::ty_native(_) {
1546         let cx = trans_fail(cx, none::<span>,
1547                             "attempt to compare values of type native");
1548         ret rslt(cx, C_nil());
1549       }
1550       _ {
1551         // Should never get here, because t is scalar.
1552         bcx_ccx(cx).sess.bug("non-scalar type passed to \
1553                                  compare_scalar_types");
1554       }
1555     }
1556 }
1557
1558
1559 // A helper function to do the actual comparison of scalar values.
1560 fn compare_scalar_values(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef,
1561                          nt: scalar_type, op: ast::binop) -> ValueRef {
1562     alt nt {
1563       nil_type. {
1564         // We don't need to do actual comparisons for nil.
1565         // () == () holds but () < () does not.
1566         alt op {
1567           ast::eq. | ast::le. | ast::ge. { ret C_bool(true); }
1568           ast::ne. | ast::lt. | ast::gt. { ret C_bool(false); }
1569         }
1570       }
1571       floating_point. {
1572         let cmp = alt op {
1573           ast::eq. { lib::llvm::LLVMRealOEQ }
1574           ast::ne. { lib::llvm::LLVMRealUNE }
1575           ast::lt. { lib::llvm::LLVMRealOLT }
1576           ast::le. { lib::llvm::LLVMRealOLE }
1577           ast::gt. { lib::llvm::LLVMRealOGT }
1578           ast::ge. { lib::llvm::LLVMRealOGE }
1579         };
1580         ret FCmp(cx, cmp, lhs, rhs);
1581       }
1582       signed_int. {
1583         let cmp = alt op {
1584           ast::eq. { lib::llvm::LLVMIntEQ }
1585           ast::ne. { lib::llvm::LLVMIntNE }
1586           ast::lt. { lib::llvm::LLVMIntSLT }
1587           ast::le. { lib::llvm::LLVMIntSLE }
1588           ast::gt. { lib::llvm::LLVMIntSGT }
1589           ast::ge. { lib::llvm::LLVMIntSGE }
1590         };
1591         ret ICmp(cx, cmp, lhs, rhs);
1592       }
1593       unsigned_int. {
1594         let cmp = alt op {
1595           ast::eq. { lib::llvm::LLVMIntEQ }
1596           ast::ne. { lib::llvm::LLVMIntNE }
1597           ast::lt. { lib::llvm::LLVMIntULT }
1598           ast::le. { lib::llvm::LLVMIntULE }
1599           ast::gt. { lib::llvm::LLVMIntUGT }
1600           ast::ge. { lib::llvm::LLVMIntUGE }
1601         };
1602         ret ICmp(cx, cmp, lhs, rhs);
1603       }
1604     }
1605 }
1606
1607 type val_pair_fn = fn(@block_ctxt, ValueRef, ValueRef) -> @block_ctxt;
1608 type val_and_ty_fn = fn(@block_ctxt, ValueRef, ty::t) -> @block_ctxt;
1609
1610 fn load_inbounds(cx: @block_ctxt, p: ValueRef, idxs: [int]) -> ValueRef {
1611     ret Load(cx, GEPi(cx, p, idxs));
1612 }
1613
1614 fn store_inbounds(cx: @block_ctxt, v: ValueRef, p: ValueRef,
1615                   idxs: [int]) {
1616     Store(cx, v, GEPi(cx, p, idxs));
1617 }
1618
1619 // Iterates through the elements of a structural type.
1620 fn iter_structural_ty(cx: @block_ctxt, av: ValueRef, t: ty::t,
1621                       f: val_and_ty_fn) -> @block_ctxt {
1622     fn iter_boxpp(cx: @block_ctxt, box_cell: ValueRef, f: val_and_ty_fn) ->
1623        @block_ctxt {
1624         let box_ptr = Load(cx, box_cell);
1625         let tnil = ty::mk_nil(bcx_tcx(cx));
1626         let tbox = ty::mk_imm_box(bcx_tcx(cx), tnil);
1627         let inner_cx = new_sub_block_ctxt(cx, "iter box");
1628         let next_cx = new_sub_block_ctxt(cx, "next");
1629         let null_test = IsNull(cx, box_ptr);
1630         CondBr(cx, null_test, next_cx.llbb, inner_cx.llbb);
1631         let inner_cx = f(inner_cx, box_cell, tbox);
1632         Br(inner_cx, next_cx.llbb);
1633         ret next_cx;
1634     }
1635
1636     fn iter_variant(cx: @block_ctxt, a_tup: ValueRef,
1637                     variant: ty::variant_info, tps: [ty::t], tid: ast::def_id,
1638                     f: val_and_ty_fn) -> @block_ctxt {
1639         if vec::len::<ty::t>(variant.args) == 0u { ret cx; }
1640         let fn_ty = variant.ctor_ty;
1641         let ccx = bcx_ccx(cx);
1642         let cx = cx;
1643         alt ty::struct(ccx.tcx, fn_ty) {
1644           ty::ty_fn({inputs: args, _}) {
1645             let j = 0u;
1646             let v_id = variant.id;
1647             for a: ty::arg in args {
1648                 check (valid_variant_index(j, cx, tid, v_id));
1649                 let rslt = GEP_tag(cx, a_tup, tid, v_id, tps, j);
1650                 let llfldp_a = rslt.val;
1651                 cx = rslt.bcx;
1652                 let ty_subst = ty::substitute_type_params(ccx.tcx, tps, a.ty);
1653                 cx = f(cx, llfldp_a, ty_subst);
1654                 j += 1u;
1655             }
1656           }
1657         }
1658         ret cx;
1659     }
1660
1661     /*
1662     Typestate constraint that shows the unimpl case doesn't happen?
1663     */
1664     let cx = cx;
1665     alt ty::struct(bcx_tcx(cx), t) {
1666       ty::ty_rec(fields) {
1667         let i: int = 0;
1668         for fld: ty::field in fields {
1669             // Silly check
1670             check type_is_tup_like(cx, t);
1671             let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
1672             cx = f(bcx, llfld_a, fld.mt.ty);
1673             i += 1;
1674         }
1675       }
1676       ty::ty_tup(args) {
1677         let i = 0;
1678         for arg in args {
1679             // Silly check
1680             check type_is_tup_like(cx, t);
1681             let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
1682             cx = f(bcx, llfld_a, arg);
1683             i += 1;
1684         }
1685       }
1686       ty::ty_res(_, inner, tps) {
1687         let tcx = bcx_tcx(cx);
1688         let inner1 = ty::substitute_type_params(tcx, tps, inner);
1689         let inner_t_s = ty::substitute_type_params(tcx, tps, inner);
1690         let tup_t = ty::mk_tup(tcx, [ty::mk_int(tcx), inner_t_s]);
1691         // Silly check
1692         check type_is_tup_like(cx, tup_t);
1693         let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, tup_t, av, [0, 1]);
1694         ret f(bcx, llfld_a, inner1);
1695       }
1696       ty::ty_tag(tid, tps) {
1697         let variants = ty::tag_variants(bcx_tcx(cx), tid);
1698         let n_variants = vec::len(*variants);
1699
1700         // Cast the tags to types we can GEP into.
1701         if n_variants == 1u {
1702             ret iter_variant(cx, av, variants[0], tps, tid, f);
1703         }
1704
1705         let ccx = bcx_ccx(cx);
1706         let lltagty = T_opaque_tag_ptr(ccx);
1707         let av_tag = PointerCast(cx, av, lltagty);
1708         let lldiscrim_a_ptr = GEPi(cx, av_tag, [0, 0]);
1709         let llunion_a_ptr = GEPi(cx, av_tag, [0, 1]);
1710         let lldiscrim_a = Load(cx, lldiscrim_a_ptr);
1711
1712         // NB: we must hit the discriminant first so that structural
1713         // comparison know not to proceed when the discriminants differ.
1714         cx = f(cx, lldiscrim_a_ptr, ty::mk_int(bcx_tcx(cx)));
1715         let unr_cx = new_sub_block_ctxt(cx, "tag-iter-unr");
1716         Unreachable(unr_cx);
1717         let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb, n_variants);
1718         let next_cx = new_sub_block_ctxt(cx, "tag-iter-next");
1719         let i = 0u;
1720         for variant: ty::variant_info in *variants {
1721             let variant_cx =
1722                 new_sub_block_ctxt(cx,
1723                                    "tag-iter-variant-" +
1724                                        uint::to_str(i, 10u));
1725             AddCase(llswitch, C_int(ccx, i as int), variant_cx.llbb);
1726             variant_cx =
1727                 iter_variant(variant_cx, llunion_a_ptr, variant, tps, tid, f);
1728             Br(variant_cx, next_cx.llbb);
1729             i += 1u;
1730         }
1731         ret next_cx;
1732       }
1733       ty::ty_obj(_) {
1734         let box_cell_a = GEPi(cx, av, [0, abi::obj_field_box]);
1735         ret iter_boxpp(cx, box_cell_a, f);
1736       }
1737       _ { bcx_ccx(cx).sess.unimpl("type in iter_structural_ty"); }
1738     }
1739     ret cx;
1740 }
1741
1742 fn lazily_emit_all_tydesc_glue(cx: @block_ctxt,
1743                                static_ti: option::t<@tydesc_info>) {
1744     lazily_emit_tydesc_glue(cx, abi::tydesc_field_take_glue, static_ti);
1745     lazily_emit_tydesc_glue(cx, abi::tydesc_field_drop_glue, static_ti);
1746     lazily_emit_tydesc_glue(cx, abi::tydesc_field_free_glue, static_ti);
1747     lazily_emit_tydesc_glue(cx, abi::tydesc_field_cmp_glue, static_ti);
1748 }
1749
1750 fn lazily_emit_all_generic_info_tydesc_glues(cx: @block_ctxt,
1751                                              gi: generic_info) {
1752     for ti: option::t<@tydesc_info> in gi.static_tis {
1753         lazily_emit_all_tydesc_glue(cx, ti);
1754     }
1755 }
1756
1757 fn lazily_emit_tydesc_glue(cx: @block_ctxt, field: int,
1758                            static_ti: option::t<@tydesc_info>) {
1759     alt static_ti {
1760       none. { }
1761       some(ti) {
1762         if field == abi::tydesc_field_take_glue {
1763             alt ti.take_glue {
1764               some(_) { }
1765               none. {
1766                 #debug("+++ lazily_emit_tydesc_glue TAKE %s",
1767                        ty_to_str(bcx_tcx(cx), ti.ty));
1768                 let lcx = cx.fcx.lcx;
1769                 let glue_fn =
1770                     declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1771                                          "take");
1772                 ti.take_glue = some::<ValueRef>(glue_fn);
1773                 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1774                                   make_take_glue,
1775                                   ti.ty_params, "take");
1776                 #debug("--- lazily_emit_tydesc_glue TAKE %s",
1777                        ty_to_str(bcx_tcx(cx), ti.ty));
1778               }
1779             }
1780         } else if field == abi::tydesc_field_drop_glue {
1781             alt ti.drop_glue {
1782               some(_) { }
1783               none. {
1784                 #debug("+++ lazily_emit_tydesc_glue DROP %s",
1785                        ty_to_str(bcx_tcx(cx), ti.ty));
1786                 let lcx = cx.fcx.lcx;
1787                 let glue_fn =
1788                     declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1789                                          "drop");
1790                 ti.drop_glue = some::<ValueRef>(glue_fn);
1791                 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1792                                   make_drop_glue,
1793                                   ti.ty_params, "drop");
1794                 #debug("--- lazily_emit_tydesc_glue DROP %s",
1795                        ty_to_str(bcx_tcx(cx), ti.ty));
1796               }
1797             }
1798         } else if field == abi::tydesc_field_free_glue {
1799             alt ti.free_glue {
1800               some(_) { }
1801               none. {
1802                 #debug("+++ lazily_emit_tydesc_glue FREE %s",
1803                        ty_to_str(bcx_tcx(cx), ti.ty));
1804                 let lcx = cx.fcx.lcx;
1805                 let glue_fn =
1806                     declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1807                                          "free");
1808                 ti.free_glue = some::<ValueRef>(glue_fn);
1809                 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1810                                   make_free_glue,
1811                                   ti.ty_params, "free");
1812                 #debug("--- lazily_emit_tydesc_glue FREE %s",
1813                        ty_to_str(bcx_tcx(cx), ti.ty));
1814               }
1815             }
1816         } else if field == abi::tydesc_field_cmp_glue {
1817             alt ti.cmp_glue {
1818               some(_) { }
1819               none. {
1820                 #debug("+++ lazily_emit_tydesc_glue CMP %s",
1821                        ty_to_str(bcx_tcx(cx), ti.ty));
1822                 ti.cmp_glue = some(bcx_ccx(cx).upcalls.cmp_type);
1823                 #debug("--- lazily_emit_tydesc_glue CMP %s",
1824                        ty_to_str(bcx_tcx(cx), ti.ty));
1825               }
1826             }
1827         }
1828       }
1829     }
1830 }
1831
1832 fn call_tydesc_glue_full(cx: @block_ctxt, v: ValueRef, tydesc: ValueRef,
1833                          field: int, static_ti: option::t<@tydesc_info>) {
1834     lazily_emit_tydesc_glue(cx, field, static_ti);
1835
1836     let static_glue_fn = none;
1837     alt static_ti {
1838       none. {/* no-op */ }
1839       some(sti) {
1840         if field == abi::tydesc_field_take_glue {
1841             static_glue_fn = sti.take_glue;
1842         } else if field == abi::tydesc_field_drop_glue {
1843             static_glue_fn = sti.drop_glue;
1844         } else if field == abi::tydesc_field_free_glue {
1845             static_glue_fn = sti.free_glue;
1846         }
1847       }
1848     }
1849
1850     let llrawptr = PointerCast(cx, v, T_ptr(T_i8()));
1851     let lltydescs =
1852         GEPi(cx, tydesc, [0, abi::tydesc_field_first_param]);
1853     lltydescs = Load(cx, lltydescs);
1854
1855     let llfn;
1856     alt static_glue_fn {
1857       none. {
1858         let llfnptr = GEPi(cx, tydesc, [0, field]);
1859         llfn = Load(cx, llfnptr);
1860       }
1861       some(sgf) { llfn = sgf; }
1862     }
1863
1864     Call(cx, llfn, [C_null(T_ptr(T_nil())), C_null(T_ptr(T_nil())),
1865                     lltydescs, llrawptr]);
1866 }
1867
1868 fn call_tydesc_glue(cx: @block_ctxt, v: ValueRef, t: ty::t, field: int) ->
1869    @block_ctxt {
1870     let ti: option::t<@tydesc_info> = none::<@tydesc_info>;
1871     let {bcx: bcx, val: td} = get_tydesc(cx, t, false, tps_normal, ti).result;
1872     call_tydesc_glue_full(bcx, v, td, field, ti);
1873     ret bcx;
1874 }
1875
1876 fn call_cmp_glue(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef, t: ty::t,
1877                  llop: ValueRef) -> result {
1878     // We can't use call_tydesc_glue_full() and friends here because compare
1879     // glue has a special signature.
1880
1881     let bcx = cx;
1882
1883     let r = spill_if_immediate(bcx, lhs, t);
1884     let lllhs = r.val;
1885     bcx = r.bcx;
1886     r = spill_if_immediate(bcx, rhs, t);
1887     let llrhs = r.val;
1888     bcx = r.bcx;
1889
1890     let llrawlhsptr = BitCast(bcx, lllhs, T_ptr(T_i8()));
1891     let llrawrhsptr = BitCast(bcx, llrhs, T_ptr(T_i8()));
1892     let ti = none::<@tydesc_info>;
1893     r = get_tydesc(bcx, t, false, tps_normal, ti).result;
1894     let lltydesc = r.val;
1895     bcx = r.bcx;
1896     lazily_emit_tydesc_glue(bcx, abi::tydesc_field_cmp_glue, ti);
1897     let lltydescs =
1898         GEPi(bcx, lltydesc, [0, abi::tydesc_field_first_param]);
1899     lltydescs = Load(bcx, lltydescs);
1900
1901     let llfn;
1902     alt ti {
1903       none. {
1904         let llfnptr =
1905             GEPi(bcx, lltydesc, [0, abi::tydesc_field_cmp_glue]);
1906         llfn = Load(bcx, llfnptr);
1907       }
1908       some(sti) { llfn = option::get(sti.cmp_glue); }
1909     }
1910
1911     let llcmpresultptr = alloca(bcx, T_i1());
1912     Call(bcx, llfn, [llcmpresultptr, lltydesc, lltydescs,
1913                      llrawlhsptr, llrawrhsptr, llop]);
1914     ret rslt(bcx, Load(bcx, llcmpresultptr));
1915 }
1916
1917 fn take_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1918     if ty::type_needs_drop(bcx_tcx(cx), t) {
1919         ret call_tydesc_glue(cx, v, t, abi::tydesc_field_take_glue);
1920     }
1921     ret cx;
1922 }
1923
1924 fn drop_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1925     if ty::type_needs_drop(bcx_tcx(cx), t) {
1926         ret call_tydesc_glue(cx, v, t, abi::tydesc_field_drop_glue);
1927     }
1928     ret cx;
1929 }
1930
1931 fn drop_ty_immediate(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1932     alt ty::struct(bcx_tcx(bcx), t) {
1933       ty::ty_uniq(_) | ty::ty_vec(_) | ty::ty_str. {
1934         ret free_ty(bcx, v, t);
1935       }
1936       ty::ty_box(_) { ret decr_refcnt_maybe_free(bcx, v, t); }
1937     }
1938 }
1939
1940 fn take_ty_immediate(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
1941     alt ty::struct(bcx_tcx(bcx), t) {
1942       ty::ty_box(_) { ret rslt(incr_refcnt_of_boxed(bcx, v), v); }
1943       ty::ty_uniq(_) {
1944         check trans_uniq::type_is_unique_box(bcx, t);
1945         ret trans_uniq::duplicate(bcx, v, t);
1946       }
1947       ty::ty_str. | ty::ty_vec(_) { ret tvec::duplicate(bcx, v, t); }
1948       _ { ret rslt(bcx, v); }
1949     }
1950 }
1951
1952 fn free_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1953     if ty::type_needs_drop(bcx_tcx(cx), t) {
1954         ret call_tydesc_glue(cx, v, t, abi::tydesc_field_free_glue);
1955     }
1956     ret cx;
1957 }
1958
1959 fn call_memmove(cx: @block_ctxt, dst: ValueRef, src: ValueRef,
1960                 n_bytes: ValueRef) -> result {
1961     // TODO: Provide LLVM with better alignment information when the alignment
1962     // is statically known (it must be nothing more than a constant int, or
1963     // LLVM complains -- not even a constant element of a tydesc works).
1964
1965     let ccx = bcx_ccx(cx);
1966     let key = alt ccx.sess.get_targ_cfg().arch {
1967       session::arch_x86. | session::arch_arm. { "llvm.memmove.p0i8.p0i8.i32" }
1968       session::arch_x86_64. { "llvm.memmove.p0i8.p0i8.i64" }
1969     };
1970     let i = ccx.intrinsics;
1971     assert (i.contains_key(key));
1972     let memmove = i.get(key);
1973     let src_ptr = PointerCast(cx, src, T_ptr(T_i8()));
1974     let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
1975     // FIXME #1184: Resource flag is larger than necessary
1976     let size = IntCast(cx, n_bytes, ccx.int_type);
1977     let align = C_i32(1i32);
1978     let volatile = C_bool(false);
1979     let ret_val = Call(cx, memmove, [dst_ptr, src_ptr, size,
1980                                      align, volatile]);
1981     ret rslt(cx, ret_val);
1982 }
1983
1984 fn call_bzero(cx: @block_ctxt, dst: ValueRef, n_bytes: ValueRef,
1985               align_bytes: ValueRef) -> result {
1986     // FIXME: switch to the 64-bit variant when on such a platform.
1987     let ccx = bcx_ccx(cx);
1988     let i = ccx.intrinsics;
1989     assert (i.contains_key("llvm.memset.p0i8.i32"));
1990     let memset = i.get("llvm.memset.p0i8.i32");
1991     let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
1992     let size = IntCast(cx, n_bytes, T_i32());
1993     let align =
1994         if lib::llvm::llvm::LLVMIsConstant(align_bytes) == True {
1995             IntCast(cx, align_bytes, T_i32())
1996         } else { IntCast(cx, C_int(ccx, 0), T_i32()) };
1997     let volatile = C_bool(false);
1998     ret rslt(cx,
1999              Call(cx, memset, [dst_ptr, C_u8(0u), size, align, volatile]));
2000 }
2001
2002 fn memmove_ty(cx: @block_ctxt, dst: ValueRef, src: ValueRef, t: ty::t) ->
2003     @block_ctxt {
2004     let ccx = bcx_ccx(cx);
2005     if check type_has_static_size(ccx, t) {
2006         if ty::type_is_structural(bcx_tcx(cx), t) {
2007             let sp = cx.sp;
2008             let llsz = llsize_of(ccx, type_of(ccx, sp, t));
2009             ret call_memmove(cx, dst, src, llsz).bcx;
2010         }
2011         Store(cx, Load(cx, src), dst);
2012         ret cx;
2013     }
2014
2015     let llsz = size_of(cx, t);
2016     ret call_memmove(llsz.bcx, dst, src, llsz.val).bcx;
2017 }
2018
2019 tag copy_action { INIT; DROP_EXISTING; }
2020
2021 // These are the types that are passed by pointer.
2022 fn type_is_structural_or_param(tcx: ty::ctxt, t: ty::t) -> bool {
2023     if ty::type_is_structural(tcx, t) { ret true; }
2024     alt ty::struct(tcx, t) {
2025       ty::ty_param(_, _) { ret true; }
2026       _ { ret false; }
2027     }
2028 }
2029
2030 fn copy_val(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2031             src: ValueRef, t: ty::t) -> @block_ctxt {
2032     if action == DROP_EXISTING &&
2033         (type_is_structural_or_param(bcx_tcx(cx), t) ||
2034          ty::type_is_unique(bcx_tcx(cx), t)) {
2035         let do_copy_cx = new_sub_block_ctxt(cx, "do_copy");
2036         let next_cx = new_sub_block_ctxt(cx, "next");
2037         let dstcmp = load_if_immediate(cx, dst, t);
2038         let self_assigning =
2039             ICmp(cx, lib::llvm::LLVMIntNE,
2040                  PointerCast(cx, dstcmp, val_ty(src)), src);
2041         CondBr(cx, self_assigning, do_copy_cx.llbb, next_cx.llbb);
2042         do_copy_cx = copy_val_no_check(do_copy_cx, action, dst, src, t);
2043         Br(do_copy_cx, next_cx.llbb);
2044         ret next_cx;
2045     }
2046     ret copy_val_no_check(cx, action, dst, src, t);
2047 }
2048
2049 fn copy_val_no_check(bcx: @block_ctxt, action: copy_action, dst: ValueRef,
2050                      src: ValueRef, t: ty::t) -> @block_ctxt {
2051     let ccx = bcx_ccx(bcx), bcx = bcx;
2052     if ty::type_is_scalar(ccx.tcx, t) || ty::type_is_native(ccx.tcx, t) {
2053         Store(bcx, src, dst);
2054         ret bcx;
2055     }
2056     if ty::type_is_nil(ccx.tcx, t) || ty::type_is_bot(ccx.tcx, t) { ret bcx; }
2057     if ty::type_is_boxed(ccx.tcx, t) || ty::type_is_vec(ccx.tcx, t) ||
2058        ty::type_is_unique_box(ccx.tcx, t) {
2059         if action == DROP_EXISTING { bcx = drop_ty(bcx, dst, t); }
2060         Store(bcx, src, dst);
2061         ret take_ty(bcx, dst, t);
2062     }
2063     if type_is_structural_or_param(ccx.tcx, t) {
2064         if action == DROP_EXISTING { bcx = drop_ty(bcx, dst, t); }
2065         bcx = memmove_ty(bcx, dst, src, t);
2066         ret take_ty(bcx, dst, t);
2067     }
2068     ccx.sess.bug("unexpected type in trans::copy_val_no_check: " +
2069                      ty_to_str(ccx.tcx, t));
2070 }
2071
2072
2073 // This works like copy_val, except that it deinitializes the source.
2074 // Since it needs to zero out the source, src also needs to be an lval.
2075 // FIXME: We always zero out the source. Ideally we would detect the
2076 // case where a variable is always deinitialized by block exit and thus
2077 // doesn't need to be dropped.
2078 fn move_val(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2079             src: lval_result, t: ty::t) -> @block_ctxt {
2080     let src_val = src.val;
2081     let tcx = bcx_tcx(cx), cx = cx;
2082     if ty::type_is_scalar(tcx, t) || ty::type_is_native(tcx, t) {
2083         if src.kind == owned { src_val = Load(cx, src_val); }
2084         Store(cx, src_val, dst);
2085         ret cx;
2086     } else if ty::type_is_nil(tcx, t) || ty::type_is_bot(tcx, t) {
2087         ret cx;
2088     } else if ty::type_is_boxed(tcx, t) || ty::type_is_unique(tcx, t) {
2089         if src.kind == owned { src_val = Load(cx, src_val); }
2090         if action == DROP_EXISTING { cx = drop_ty(cx, dst, t); }
2091         Store(cx, src_val, dst);
2092         if src.kind == owned { ret zero_alloca(cx, src.val, t); }
2093         // If we're here, it must be a temporary.
2094         revoke_clean(cx, src_val);
2095         ret cx;
2096     } else if type_is_structural_or_param(tcx, t) {
2097         if action == DROP_EXISTING { cx = drop_ty(cx, dst, t); }
2098         cx = memmove_ty(cx, dst, src_val, t);
2099         if src.kind == owned { ret zero_alloca(cx, src_val, t); }
2100         // If we're here, it must be a temporary.
2101         revoke_clean(cx, src_val);
2102         ret cx;
2103     }
2104     /* FIXME: suggests a type constraint */
2105     bcx_ccx(cx).sess.bug("unexpected type in trans::move_val: " +
2106                              ty_to_str(tcx, t));
2107 }
2108
2109 fn store_temp_expr(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2110                    src: lval_result, t: ty::t, last_use: bool)
2111     -> @block_ctxt {
2112     // Lvals in memory are not temporaries. Copy them.
2113     if src.kind != temporary && !last_use {
2114         let v = src.kind == owned ? load_if_immediate(cx, src.val, t)
2115                                   : src.val;
2116         ret copy_val(cx, action, dst, v, t);
2117     }
2118     ret move_val(cx, action, dst, src, t);
2119 }
2120
2121 fn trans_crate_lit(cx: @crate_ctxt, lit: ast::lit) -> ValueRef {
2122     alt lit.node {
2123       ast::lit_int(i, t) { C_integral(T_int_ty(cx, t), i as u64, True) }
2124       ast::lit_uint(u, t) { C_integral(T_uint_ty(cx, t), u, False) }
2125       ast::lit_float(fs, t) { C_floating(fs, T_float_ty(cx, t)) }
2126       ast::lit_bool(b) { C_bool(b) }
2127       ast::lit_nil. { C_nil() }
2128       ast::lit_str(s) {
2129         cx.sess.span_unimpl(lit.span, "unique string in this context");
2130       }
2131     }
2132 }
2133
2134 fn trans_lit(cx: @block_ctxt, lit: ast::lit, dest: dest) -> @block_ctxt {
2135     if dest == ignore { ret cx; }
2136     alt lit.node {
2137       ast::lit_str(s) { ret tvec::trans_str(cx, s, dest); }
2138       _ {
2139         ret store_in_dest(cx, trans_crate_lit(bcx_ccx(cx), lit), dest);
2140       }
2141     }
2142 }
2143
2144
2145 // Converts an annotation to a type
2146 fn node_id_type(cx: @crate_ctxt, id: ast::node_id) -> ty::t {
2147     ret ty::node_id_to_monotype(cx.tcx, id);
2148 }
2149
2150 fn node_type(cx: @crate_ctxt, sp: span, id: ast::node_id) -> TypeRef {
2151     let ty = node_id_type(cx, id);
2152     // How to make this a precondition?
2153     // FIXME (again, would require a predicate that implies
2154     // another predicate)
2155     check (type_has_static_size(cx, ty));
2156     type_of(cx, sp, ty)
2157 }
2158
2159 fn trans_unary(bcx: @block_ctxt, op: ast::unop, e: @ast::expr,
2160                id: ast::node_id, dest: dest) -> @block_ctxt {
2161     if dest == ignore { ret trans_expr(bcx, e, ignore); }
2162     let e_ty = ty::expr_ty(bcx_tcx(bcx), e);
2163     alt op {
2164       ast::not. {
2165         let {bcx, val} = trans_temp_expr(bcx, e);
2166         ret store_in_dest(bcx, Not(bcx, val), dest);
2167       }
2168       ast::neg. {
2169         let {bcx, val} = trans_temp_expr(bcx, e);
2170         let neg = if ty::type_is_fp(bcx_tcx(bcx), e_ty) {
2171             FNeg(bcx, val)
2172         } else { Neg(bcx, val) };
2173         ret store_in_dest(bcx, neg, dest);
2174       }
2175       ast::box(_) {
2176         let {bcx, box, body} = trans_malloc_boxed(bcx, e_ty);
2177         add_clean_free(bcx, box, false);
2178         // Cast the body type to the type of the value. This is needed to
2179         // make tags work, since tags have a different LLVM type depending
2180         // on whether they're boxed or not.
2181         let ccx = bcx_ccx(bcx);
2182         if check type_has_static_size(ccx, e_ty) {
2183             let e_sp = e.span;
2184             let llety = T_ptr(type_of(ccx, e_sp, e_ty));
2185             body = PointerCast(bcx, body, llety);
2186         }
2187         bcx = trans_expr_save_in(bcx, e, body);
2188         revoke_clean(bcx, box);
2189         ret store_in_dest(bcx, box, dest);
2190       }
2191       ast::uniq(_) {
2192         ret trans_uniq::trans_uniq(bcx, e, id, dest);
2193       }
2194       ast::deref. {
2195         bcx_ccx(bcx).sess.bug("deref expressions should have been \
2196                                translated using trans_lval(), not \
2197                                trans_unary()");
2198       }
2199     }
2200 }
2201
2202 fn trans_compare(cx: @block_ctxt, op: ast::binop, lhs: ValueRef,
2203                  _lhs_t: ty::t, rhs: ValueRef, rhs_t: ty::t) -> result {
2204     if ty::type_is_scalar(bcx_tcx(cx), rhs_t) {
2205       let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, op);
2206       ret rslt(rs.bcx, rs.val);
2207     }
2208
2209     // Determine the operation we need.
2210     let llop;
2211     alt op {
2212       ast::eq. | ast::ne. { llop = C_u8(abi::cmp_glue_op_eq); }
2213       ast::lt. | ast::ge. { llop = C_u8(abi::cmp_glue_op_lt); }
2214       ast::le. | ast::gt. { llop = C_u8(abi::cmp_glue_op_le); }
2215     }
2216
2217     let rs = call_cmp_glue(cx, lhs, rhs, rhs_t, llop);
2218
2219     // Invert the result if necessary.
2220     alt op {
2221       ast::eq. | ast::lt. | ast::le. { ret rslt(rs.bcx, rs.val); }
2222       ast::ne. | ast::ge. | ast::gt. {
2223         ret rslt(rs.bcx, Not(rs.bcx, rs.val));
2224       }
2225     }
2226 }
2227
2228 // Important to get types for both lhs and rhs, because one might be _|_
2229 // and the other not.
2230 fn trans_eager_binop(cx: @block_ctxt, op: ast::binop, lhs: ValueRef,
2231                      lhs_t: ty::t, rhs: ValueRef, rhs_t: ty::t, dest: dest)
2232     -> @block_ctxt {
2233     if dest == ignore { ret cx; }
2234     let intype = lhs_t;
2235     if ty::type_is_bot(bcx_tcx(cx), intype) { intype = rhs_t; }
2236     let is_float = ty::type_is_fp(bcx_tcx(cx), intype);
2237
2238     if op == ast::add && ty::type_is_sequence(bcx_tcx(cx), intype) {
2239         ret tvec::trans_add(cx, intype, lhs, rhs, dest);
2240     }
2241     let cx = cx, val = alt op {
2242       ast::add. {
2243         if is_float { FAdd(cx, lhs, rhs) }
2244         else { Add(cx, lhs, rhs) }
2245       }
2246       ast::sub. {
2247         if is_float { FSub(cx, lhs, rhs) }
2248         else { Sub(cx, lhs, rhs) }
2249       }
2250       ast::mul. {
2251         if is_float { FMul(cx, lhs, rhs) }
2252         else { Mul(cx, lhs, rhs) }
2253       }
2254       ast::div. {
2255         if is_float { FDiv(cx, lhs, rhs) }
2256         else if ty::type_is_signed(bcx_tcx(cx), intype) {
2257             SDiv(cx, lhs, rhs)
2258         } else { UDiv(cx, lhs, rhs) }
2259       }
2260       ast::rem. {
2261         if is_float { FRem(cx, lhs, rhs) }
2262         else if ty::type_is_signed(bcx_tcx(cx), intype) {
2263             SRem(cx, lhs, rhs)
2264         } else { URem(cx, lhs, rhs) }
2265       }
2266       ast::bitor. { Or(cx, lhs, rhs) }
2267       ast::bitand. { And(cx, lhs, rhs) }
2268       ast::bitxor. { Xor(cx, lhs, rhs) }
2269       ast::lsl. { Shl(cx, lhs, rhs) }
2270       ast::lsr. { LShr(cx, lhs, rhs) }
2271       ast::asr. { AShr(cx, lhs, rhs) }
2272       _ {
2273         let cmpr = trans_compare(cx, op, lhs, lhs_t, rhs, rhs_t);
2274         cx = cmpr.bcx;
2275         cmpr.val
2276       }
2277     };
2278     ret store_in_dest(cx, val, dest);
2279 }
2280
2281 fn trans_assign_op(bcx: @block_ctxt, op: ast::binop, dst: @ast::expr,
2282                    src: @ast::expr) -> @block_ctxt {
2283     let tcx = bcx_tcx(bcx);
2284     let t = ty::expr_ty(tcx, src);
2285     let lhs_res = trans_lval(bcx, dst);
2286     assert (lhs_res.kind == owned);
2287     // Special case for `+= [x]`
2288     alt ty::struct(tcx, t) {
2289       ty::ty_vec(_) {
2290         alt src.node {
2291           ast::expr_vec(args, _) {
2292             ret tvec::trans_append_literal(lhs_res.bcx,
2293                                            lhs_res.val, t, args);
2294           }
2295           _ { }
2296         }
2297       }
2298       _ { }
2299     }
2300     let {bcx, val: rhs_val} = trans_temp_expr(lhs_res.bcx, src);
2301     if ty::type_is_sequence(tcx, t) {
2302         alt op {
2303           ast::add. {
2304             ret tvec::trans_append(bcx, t, lhs_res.val, rhs_val);
2305           }
2306           _ { }
2307         }
2308     }
2309     ret trans_eager_binop(bcx, op, Load(bcx, lhs_res.val), t, rhs_val, t,
2310                           save_in(lhs_res.val));
2311 }
2312
2313 fn autoderef(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result_t {
2314     let v1: ValueRef = v;
2315     let t1: ty::t = t;
2316     let ccx = bcx_ccx(cx);
2317     let sp = cx.sp;
2318     while true {
2319         alt ty::struct(ccx.tcx, t1) {
2320           ty::ty_box(mt) {
2321             let body = GEPi(cx, v1, [0, abi::box_rc_field_body]);
2322             t1 = mt.ty;
2323
2324             // Since we're changing levels of box indirection, we may have
2325             // to cast this pointer, since statically-sized tag types have
2326             // different types depending on whether they're behind a box
2327             // or not.
2328             if check type_has_static_size(ccx, t1) {
2329                 let llty = type_of(ccx, sp, t1);
2330                 v1 = PointerCast(cx, body, T_ptr(llty));
2331             } else { v1 = body; }
2332           }
2333           ty::ty_uniq(_) {
2334             check trans_uniq::type_is_unique_box(cx, t1);
2335             let derefed = trans_uniq::autoderef(cx, v1, t1);
2336             t1 = derefed.t;
2337             v1 = derefed.v;
2338           }
2339           ty::ty_res(did, inner, tps) {
2340             t1 = ty::substitute_type_params(ccx.tcx, tps, inner);
2341             v1 = GEPi(cx, v1, [0, 1]);
2342           }
2343           ty::ty_tag(did, tps) {
2344             let variants = ty::tag_variants(ccx.tcx, did);
2345             if vec::len(*variants) != 1u ||
2346                    vec::len(variants[0].args) != 1u {
2347                 break;
2348             }
2349             t1 =
2350                 ty::substitute_type_params(ccx.tcx, tps, variants[0].args[0]);
2351             if check type_has_static_size(ccx, t1) {
2352                 v1 = PointerCast(cx, v1, T_ptr(type_of(ccx, sp, t1)));
2353             } else { } // FIXME: typestate hack
2354           }
2355           _ { break; }
2356         }
2357         v1 = load_if_immediate(cx, v1, t1);
2358     }
2359     ret {bcx: cx, val: v1, ty: t1};
2360 }
2361
2362 fn trans_lazy_binop(bcx: @block_ctxt, op: ast::binop, a: @ast::expr,
2363                     b: @ast::expr, dest: dest) -> @block_ctxt {
2364     let is_and = alt op { ast::and. { true } ast::or. { false } };
2365     let lhs_res = trans_temp_expr(bcx, a);
2366     if lhs_res.bcx.unreachable { ret lhs_res.bcx; }
2367     let rhs_cx = new_scope_block_ctxt(lhs_res.bcx, "rhs");
2368     let rhs_res = trans_temp_expr(rhs_cx, b);
2369
2370     let lhs_past_cx = new_scope_block_ctxt(lhs_res.bcx, "lhs");
2371     // The following line ensures that any cleanups for rhs
2372     // are done within the block for rhs. This is necessary
2373     // because and/or are lazy. So the rhs may never execute,
2374     // and the cleanups can't be pushed into later code.
2375     let rhs_bcx = trans_block_cleanups(rhs_res.bcx, rhs_cx);
2376     if is_and {
2377         CondBr(lhs_res.bcx, lhs_res.val, rhs_cx.llbb, lhs_past_cx.llbb);
2378     } else {
2379         CondBr(lhs_res.bcx, lhs_res.val, lhs_past_cx.llbb, rhs_cx.llbb);
2380     }
2381
2382     let join_cx = new_sub_block_ctxt(bcx, "join");
2383     Br(lhs_past_cx, join_cx.llbb);
2384     if rhs_bcx.unreachable {
2385         ret store_in_dest(join_cx, C_bool(!is_and), dest);
2386     }
2387     Br(rhs_bcx, join_cx.llbb);
2388     let phi = Phi(join_cx, T_bool(), [C_bool(!is_and), rhs_res.val],
2389                   [lhs_past_cx.llbb, rhs_bcx.llbb]);
2390     ret store_in_dest(join_cx, phi, dest);
2391 }
2392
2393 fn trans_binary(cx: @block_ctxt, op: ast::binop, a: @ast::expr, b: @ast::expr,
2394                 dest: dest) -> @block_ctxt {
2395     // First couple cases are lazy:
2396     alt op {
2397       ast::and. | ast::or. {
2398         ret trans_lazy_binop(cx, op, a, b, dest);
2399       }
2400       _ {
2401         // Remaining cases are eager:
2402         let lhs = trans_temp_expr(cx, a);
2403         let rhs = trans_temp_expr(lhs.bcx, b);
2404         ret trans_eager_binop(rhs.bcx, op, lhs.val,
2405                               ty::expr_ty(bcx_tcx(cx), a), rhs.val,
2406                               ty::expr_ty(bcx_tcx(cx), b), dest);
2407       }
2408     }
2409 }
2410
2411 tag dest {
2412     by_val(@mutable ValueRef);
2413     save_in(ValueRef);
2414     ignore;
2415 }
2416
2417 fn empty_dest_cell() -> @mutable ValueRef {
2418     ret @mutable llvm::LLVMGetUndef(T_nil());
2419 }
2420
2421 fn dup_for_join(dest: dest) -> dest {
2422     alt dest {
2423       by_val(_) { by_val(empty_dest_cell()) }
2424       _ { dest }
2425     }
2426 }
2427
2428 fn join_returns(parent_cx: @block_ctxt, in_cxs: [@block_ctxt],
2429                 in_ds: [dest], out_dest: dest) -> @block_ctxt {
2430     let out = new_sub_block_ctxt(parent_cx, "join");
2431     let reachable = false, i = 0u, phi = none;
2432     for cx in in_cxs {
2433         if !cx.unreachable {
2434             Br(cx, out.llbb);
2435             reachable = true;
2436             alt in_ds[i] {
2437               by_val(cell) {
2438                 if option::is_none(phi) {
2439                     phi = some(EmptyPhi(out, val_ty(*cell)));
2440                 }
2441                 AddIncomingToPhi(option::get(phi), *cell, cx.llbb);
2442               }
2443               _ {}
2444             }
2445         }
2446         i += 1u;
2447     }
2448     if !reachable {
2449         Unreachable(out);
2450     } else {
2451         alt out_dest {
2452           by_val(cell) { *cell = option::get(phi); }
2453           _ {}
2454         }
2455     }
2456     ret out;
2457 }
2458
2459 // Used to put an immediate value in a dest.
2460 fn store_in_dest(bcx: @block_ctxt, val: ValueRef, dest: dest) -> @block_ctxt {
2461     alt dest {
2462       ignore. {}
2463       by_val(cell) { *cell = val; }
2464       save_in(addr) { Store(bcx, val, addr); }
2465     }
2466     ret bcx;
2467 }
2468
2469 fn get_dest_addr(dest: dest) -> ValueRef {
2470     alt dest { save_in(a) { a } }
2471 }
2472
2473 fn trans_if(cx: @block_ctxt, cond: @ast::expr, thn: ast::blk,
2474             els: option::t<@ast::expr>, dest: dest)
2475     -> @block_ctxt {
2476     let {bcx, val: cond_val} = trans_temp_expr(cx, cond);
2477
2478     let then_dest = dup_for_join(dest);
2479     let else_dest = dup_for_join(dest);
2480     let then_cx = new_scope_block_ctxt(bcx, "then");
2481     let else_cx = new_scope_block_ctxt(bcx, "else");
2482     CondBr(bcx, cond_val, then_cx.llbb, else_cx.llbb);
2483     then_cx = trans_block_dps(then_cx, thn, then_dest);
2484     // Calling trans_block directly instead of trans_expr
2485     // because trans_expr will create another scope block
2486     // context for the block, but we've already got the
2487     // 'else' context
2488     alt els {
2489       some(elexpr) {
2490         alt elexpr.node {
2491           ast::expr_if(_, _, _) {
2492             let elseif_blk = ast_util::block_from_expr(elexpr);
2493             else_cx = trans_block_dps(else_cx, elseif_blk, else_dest);
2494           }
2495           ast::expr_block(blk) {
2496             else_cx = trans_block_dps(else_cx, blk, else_dest);
2497           }
2498         }
2499       }
2500       _ {}
2501     }
2502     ret join_returns(cx, [then_cx, else_cx], [then_dest, else_dest], dest);
2503 }
2504
2505 fn trans_for(cx: @block_ctxt, local: @ast::local, seq: @ast::expr,
2506              body: ast::blk) -> @block_ctxt {
2507     fn inner(bcx: @block_ctxt, local: @ast::local, curr: ValueRef, t: ty::t,
2508              body: ast::blk, outer_next_cx: @block_ctxt) -> @block_ctxt {
2509         let next_cx = new_sub_block_ctxt(bcx, "next");
2510         let scope_cx =
2511             new_loop_scope_block_ctxt(bcx, option::some(next_cx),
2512                                       outer_next_cx, "for loop scope");
2513         Br(bcx, scope_cx.llbb);
2514         let curr = PointerCast(bcx, curr, T_ptr(type_of_or_i8(bcx, t)));
2515         let bcx = trans_alt::bind_irrefutable_pat(scope_cx, local.node.pat,
2516                                                   curr, false);
2517         bcx = trans_block_dps(bcx, body, ignore);
2518         Br(bcx, next_cx.llbb);
2519         ret next_cx;
2520     }
2521     let ccx = bcx_ccx(cx);
2522     let next_cx = new_sub_block_ctxt(cx, "next");
2523     let seq_ty = ty::expr_ty(bcx_tcx(cx), seq);
2524     let {bcx: bcx, val: seq} = trans_temp_expr(cx, seq);
2525     let seq = PointerCast(bcx, seq, T_ptr(ccx.opaque_vec_type));
2526     let fill = tvec::get_fill(bcx, seq);
2527     if ty::type_is_str(bcx_tcx(bcx), seq_ty) {
2528         fill = Sub(bcx, fill, C_int(ccx, 1));
2529     }
2530     let bcx = tvec::iter_vec_raw(bcx, seq, seq_ty, fill,
2531                                  bind inner(_, local, _, _, body, next_cx));
2532     Br(bcx, next_cx.llbb);
2533     ret next_cx;
2534 }
2535
2536 fn trans_while(cx: @block_ctxt, cond: @ast::expr, body: ast::blk)
2537     -> @block_ctxt {
2538     let next_cx = new_sub_block_ctxt(cx, "while next");
2539     let cond_cx =
2540         new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
2541                                   "while cond");
2542     let body_cx = new_scope_block_ctxt(cond_cx, "while loop body");
2543     let body_end = trans_block(body_cx, body);
2544     let cond_res = trans_temp_expr(cond_cx, cond);
2545     Br(body_end, cond_cx.llbb);
2546     let cond_bcx = trans_block_cleanups(cond_res.bcx, cond_cx);
2547     CondBr(cond_bcx, cond_res.val, body_cx.llbb, next_cx.llbb);
2548     Br(cx, cond_cx.llbb);
2549     ret next_cx;
2550 }
2551
2552 fn trans_do_while(cx: @block_ctxt, body: ast::blk, cond: @ast::expr) ->
2553     @block_ctxt {
2554     let next_cx = new_sub_block_ctxt(cx, "next");
2555     let body_cx =
2556         new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
2557                                   "do-while loop body");
2558     let body_end = trans_block(body_cx, body);
2559     let cond_cx = new_scope_block_ctxt(body_cx, "do-while cond");
2560     Br(body_end, cond_cx.llbb);
2561     let cond_res = trans_temp_expr(cond_cx, cond);
2562     let cond_bcx = trans_block_cleanups(cond_res.bcx, cond_cx);
2563     CondBr(cond_bcx, cond_res.val, body_cx.llbb, next_cx.llbb);
2564     Br(cx, body_cx.llbb);
2565     ret next_cx;
2566 }
2567
2568 type generic_info = {
2569     item_type: ty::t,
2570     static_tis: [option::t<@tydesc_info>],
2571     tydescs: [ValueRef],
2572     param_bounds: @[ty::param_bounds],
2573     origins: option::t<typeck::dict_res>
2574 };
2575
2576 tag lval_kind {
2577     temporary; //< Temporary value passed by value if of immediate type
2578     owned;     //< Non-temporary value passed by pointer
2579     owned_imm; //< Non-temporary value passed by value
2580 }
2581 type local_var_result = {val: ValueRef, kind: lval_kind};
2582 type lval_result = {bcx: @block_ctxt, val: ValueRef, kind: lval_kind};
2583 tag callee_env {
2584     null_env;
2585     is_closure;
2586     obj_env(ValueRef);
2587     dict_env(ValueRef, ValueRef);
2588 }
2589 type lval_maybe_callee = {bcx: @block_ctxt,
2590                           val: ValueRef,
2591                           kind: lval_kind,
2592                           env: callee_env,
2593                           generic: option::t<generic_info>};
2594
2595 fn null_env_ptr(bcx: @block_ctxt) -> ValueRef {
2596     C_null(T_opaque_boxed_closure_ptr(bcx_ccx(bcx)))
2597 }
2598
2599 fn lval_from_local_var(bcx: @block_ctxt, r: local_var_result) -> lval_result {
2600     ret { bcx: bcx, val: r.val, kind: r.kind };
2601 }
2602
2603 fn lval_owned(bcx: @block_ctxt, val: ValueRef) -> lval_result {
2604     ret {bcx: bcx, val: val, kind: owned};
2605 }
2606 fn lval_temp(bcx: @block_ctxt, val: ValueRef) -> lval_result {
2607     ret {bcx: bcx, val: val, kind: temporary};
2608 }
2609
2610 fn lval_no_env(bcx: @block_ctxt, val: ValueRef, kind: lval_kind)
2611     -> lval_maybe_callee {
2612     ret {bcx: bcx, val: val, kind: kind, env: is_closure, generic: none};
2613 }
2614
2615 fn trans_external_path(cx: @block_ctxt, did: ast::def_id,
2616                        tpt: ty::ty_param_bounds_and_ty) -> ValueRef {
2617     let lcx = cx.fcx.lcx;
2618     let name = csearch::get_symbol(lcx.ccx.sess.get_cstore(), did);
2619     ret get_extern_const(lcx.ccx.externs, lcx.ccx.llmod, name,
2620                          type_of_ty_param_bounds_and_ty(lcx, cx.sp, tpt));
2621 }
2622
2623 fn lval_static_fn(bcx: @block_ctxt, fn_id: ast::def_id, id: ast::node_id)
2624     -> lval_maybe_callee {
2625     let ccx = bcx_ccx(bcx);
2626     let tpt = ty::lookup_item_type(ccx.tcx, fn_id);
2627     let val = if fn_id.crate == ast::local_crate {
2628         // Internal reference.
2629         assert (ccx.item_ids.contains_key(fn_id.node));
2630         ccx.item_ids.get(fn_id.node)
2631     } else {
2632         // External reference.
2633         trans_external_path(bcx, fn_id, tpt)
2634     };
2635     let tys = ty::node_id_to_type_params(ccx.tcx, id);
2636     let gen = none, bcx = bcx;
2637     if vec::len(tys) != 0u {
2638         let tydescs = [], tis = [];
2639         for t in tys {
2640             // TODO: Doesn't always escape.
2641             let ti = none;
2642             let td = get_tydesc(bcx, t, true, tps_normal, ti).result;
2643             tis += [ti];
2644             bcx = td.bcx;
2645             tydescs += [td.val];
2646         }
2647         gen = some({item_type: tpt.ty,
2648                     static_tis: tis,
2649                     tydescs: tydescs,
2650                     param_bounds: tpt.bounds,
2651                     origins: ccx.dict_map.find(id)});
2652     }
2653     ret {bcx: bcx, val: val, kind: owned, env: null_env, generic: gen};
2654 }
2655
2656 fn lookup_discriminant(lcx: @local_ctxt, vid: ast::def_id) -> ValueRef {
2657     let ccx = lcx.ccx;
2658     alt ccx.discrims.find(vid) {
2659       none. {
2660         // It's an external discriminant that we haven't seen yet.
2661         assert (vid.crate != ast::local_crate);
2662         let sym = csearch::get_symbol(lcx.ccx.sess.get_cstore(), vid);
2663         let gvar =
2664             str::as_buf(sym,
2665                         {|buf|
2666                             llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
2667                         });
2668         llvm::LLVMSetLinkage(gvar,
2669                              lib::llvm::LLVMExternalLinkage as llvm::Linkage);
2670         llvm::LLVMSetGlobalConstant(gvar, True);
2671         lcx.ccx.discrims.insert(vid, gvar);
2672         ret gvar;
2673       }
2674       some(llval) { ret llval; }
2675     }
2676 }
2677
2678 fn trans_local_var(cx: @block_ctxt, def: ast::def) -> local_var_result {
2679     fn take_local(table: hashmap<ast::node_id, local_val>,
2680                   id: ast::node_id) -> local_var_result {
2681         alt table.find(id) {
2682           some(local_mem(v)) { {val: v, kind: owned} }
2683           some(local_imm(v)) { {val: v, kind: owned_imm} }
2684         }
2685     }
2686     alt def {
2687       ast::def_upvar(did, _, _) {
2688         assert (cx.fcx.llupvars.contains_key(did.node));
2689         ret { val: cx.fcx.llupvars.get(did.node), kind: owned };
2690       }
2691       ast::def_arg(did, _) {
2692         ret take_local(cx.fcx.llargs, did.node);
2693       }
2694       ast::def_local(did, _) | ast::def_binding(did) {
2695         ret take_local(cx.fcx.lllocals, did.node);
2696       }
2697       ast::def_obj_field(did, _) {
2698         assert (cx.fcx.llobjfields.contains_key(did.node));
2699         ret { val: cx.fcx.llobjfields.get(did.node), kind: owned };
2700       }
2701       ast::def_self(did) {
2702         let slf = option::get(cx.fcx.llself);
2703         let ptr = PointerCast(cx, slf.v, T_ptr(type_of_or_i8(cx, slf.t)));
2704         ret {val: ptr, kind: owned};
2705       }
2706       _ {
2707         bcx_ccx(cx).sess.span_unimpl
2708             (cx.sp, "unsupported def type in trans_local_def");
2709       }
2710     }
2711 }
2712
2713 fn trans_path(cx: @block_ctxt, p: @ast::path, id: ast::node_id)
2714     -> lval_maybe_callee {
2715     ret trans_var(cx, p.span, bcx_tcx(cx).def_map.get(id), id);
2716 }
2717
2718 fn trans_var(cx: @block_ctxt, sp: span, def: ast::def, id: ast::node_id)
2719     -> lval_maybe_callee {
2720     let ccx = bcx_ccx(cx);
2721     alt def {
2722       ast::def_fn(did, _) | ast::def_native_fn(did, _) {
2723         ret lval_static_fn(cx, did, id);
2724       }
2725       ast::def_variant(tid, vid) {
2726         if vec::len(ty::tag_variant_with_id(ccx.tcx, tid, vid).args) > 0u {
2727             // N-ary variant.
2728             ret lval_static_fn(cx, vid, id);
2729         } else {
2730             // Nullary variant.
2731             let tag_ty = node_id_type(ccx, id);
2732             let alloc_result = alloc_ty(cx, tag_ty);
2733             let lltagblob = alloc_result.val;
2734             let lltagty = type_of_tag(ccx, sp, tid, tag_ty);
2735             let bcx = alloc_result.bcx;
2736             let lltagptr = PointerCast(bcx, lltagblob, T_ptr(lltagty));
2737             let lldiscrimptr = GEPi(bcx, lltagptr, [0, 0]);
2738             let d = if vec::len(*ty::tag_variants(ccx.tcx, tid)) != 1u {
2739                 let lldiscrim_gv = lookup_discriminant(bcx.fcx.lcx, vid);
2740                 let lldiscrim = Load(bcx, lldiscrim_gv);
2741                 lldiscrim
2742             } else { C_int(ccx, 0) };
2743             Store(bcx, d, lldiscrimptr);
2744             ret lval_no_env(bcx, lltagptr, temporary);
2745         }
2746       }
2747       ast::def_const(did) {
2748         if did.crate == ast::local_crate {
2749             assert (ccx.consts.contains_key(did.node));
2750             ret lval_no_env(cx, ccx.consts.get(did.node), owned);
2751         } else {
2752             let tp = ty::node_id_to_monotype(ccx.tcx, id);
2753             let val = trans_external_path(cx, did, {bounds: @[], ty: tp});
2754             ret lval_no_env(cx, load_if_immediate(cx, val, tp), owned_imm);
2755         }
2756       }
2757       _ {
2758         let loc = trans_local_var(cx, def);
2759         ret lval_no_env(cx, loc.val, loc.kind);
2760       }
2761     }
2762 }
2763
2764 fn trans_object_field(bcx: @block_ctxt, o: @ast::expr, field: ast::ident)
2765     -> {bcx: @block_ctxt, mthptr: ValueRef, objptr: ValueRef} {
2766     let {bcx, val} = trans_temp_expr(bcx, o);
2767     let {bcx, val, ty} = autoderef(bcx, val, ty::expr_ty(bcx_tcx(bcx), o));
2768     ret trans_object_field_inner(bcx, val, field, ty);
2769 }
2770
2771 fn trans_object_field_inner(bcx: @block_ctxt, o: ValueRef,
2772                             field: ast::ident, o_ty: ty::t)
2773     -> {bcx: @block_ctxt, mthptr: ValueRef, objptr: ValueRef} {
2774     let ccx = bcx_ccx(bcx), tcx = ccx.tcx;
2775     let mths = alt ty::struct(tcx, o_ty) { ty::ty_obj(ms) { ms } };
2776
2777     let ix = option::get(ty::method_idx(field, mths));
2778     let vtbl = Load(bcx, GEPi(bcx, o, [0, abi::obj_field_vtbl]));
2779     let vtbl_type = T_ptr(T_array(T_ptr(T_nil()), ix + 1u));
2780     vtbl = PointerCast(bcx, vtbl, vtbl_type);
2781
2782     let v = GEPi(bcx, vtbl, [0, ix as int]);
2783     let fn_ty: ty::t = ty::mk_fn(tcx, mths[ix].fty);
2784     let ret_ty = ty::ty_fn_ret(tcx, fn_ty);
2785     // FIXME: constrain ty_obj?
2786     let ll_fn_ty = type_of_fn(ccx, bcx.sp, true,
2787                               ty::ty_fn_args(tcx, fn_ty), ret_ty, []);
2788     v = Load(bcx, PointerCast(bcx, v, T_ptr(T_ptr(ll_fn_ty))));
2789     ret {bcx: bcx, mthptr: v, objptr: o};
2790 }
2791
2792
2793 fn trans_rec_field(bcx: @block_ctxt, base: @ast::expr,
2794                    field: ast::ident) -> lval_result {
2795     let {bcx, val} = trans_temp_expr(bcx, base);
2796     let {bcx, val, ty} = autoderef(bcx, val, ty::expr_ty(bcx_tcx(bcx), base));
2797     let fields = alt ty::struct(bcx_tcx(bcx), ty) { ty::ty_rec(fs) { fs } };
2798     let ix = option::get(ty::field_idx(field, fields));
2799     // Silly check
2800     check type_is_tup_like(bcx, ty);
2801     let {bcx, val} = GEP_tup_like(bcx, ty, val, [0, ix as int]);
2802     ret {bcx: bcx, val: val, kind: owned};
2803 }
2804
2805 fn trans_index(cx: @block_ctxt, sp: span, base: @ast::expr, idx: @ast::expr,
2806                id: ast::node_id) -> lval_result {
2807     // Is this an interior vector?
2808     let base_ty = ty::expr_ty(bcx_tcx(cx), base);
2809     let exp = trans_temp_expr(cx, base);
2810     let lv = autoderef(exp.bcx, exp.val, base_ty);
2811     let ix = trans_temp_expr(lv.bcx, idx);
2812     let v = lv.val;
2813     let bcx = ix.bcx;
2814     let ccx = bcx_ccx(cx);
2815
2816     // Cast to an LLVM integer. Rust is less strict than LLVM in this regard.
2817     let ix_val;
2818     let ix_size = llsize_of_real(bcx_ccx(cx), val_ty(ix.val));
2819     let int_size = llsize_of_real(bcx_ccx(cx), ccx.int_type);
2820     if ix_size < int_size {
2821         ix_val = ZExt(bcx, ix.val, ccx.int_type);
2822     } else if ix_size > int_size {
2823         ix_val = Trunc(bcx, ix.val, ccx.int_type);
2824     } else { ix_val = ix.val; }
2825
2826     let unit_ty = node_id_type(bcx_ccx(cx), id);
2827     let unit_sz = size_of(bcx, unit_ty);
2828     bcx = unit_sz.bcx;
2829     maybe_name_value(bcx_ccx(cx), unit_sz.val, "unit_sz");
2830     let scaled_ix = Mul(bcx, ix_val, unit_sz.val);
2831     maybe_name_value(bcx_ccx(cx), scaled_ix, "scaled_ix");
2832     let lim = tvec::get_fill(bcx, v);
2833     let body = tvec::get_dataptr(bcx, v, type_of_or_i8(bcx, unit_ty));
2834     let bounds_check = ICmp(bcx, lib::llvm::LLVMIntULT, scaled_ix, lim);
2835     let fail_cx = new_sub_block_ctxt(bcx, "fail");
2836     let next_cx = new_sub_block_ctxt(bcx, "next");
2837     let ncx = bcx_ccx(next_cx);
2838     CondBr(bcx, bounds_check, next_cx.llbb, fail_cx.llbb);
2839     // fail: bad bounds check.
2840
2841     trans_fail(fail_cx, some::<span>(sp), "bounds check");
2842     let elt =
2843         if check type_has_static_size(ncx, unit_ty) {
2844             let elt_1 = GEP(next_cx, body, [ix_val]);
2845             let llunitty = type_of(ncx, sp, unit_ty);
2846             PointerCast(next_cx, elt_1, T_ptr(llunitty))
2847         } else {
2848             body = PointerCast(next_cx, body, T_ptr(T_i8()));
2849             GEP(next_cx, body, [scaled_ix])
2850         };
2851
2852     ret lval_owned(next_cx, elt);
2853 }
2854
2855 fn expr_is_lval(bcx: @block_ctxt, e: @ast::expr) -> bool {
2856     let ccx = bcx_ccx(bcx);
2857     ty::expr_is_lval(ccx.method_map, ccx.tcx, e)
2858 }
2859
2860 fn trans_callee(bcx: @block_ctxt, e: @ast::expr) -> lval_maybe_callee {
2861     alt e.node {
2862       ast::expr_path(p) { ret trans_path(bcx, p, e.id); }
2863       ast::expr_field(base, ident, _) {
2864         // Lval means this is a record field, so not a method
2865         if !expr_is_lval(bcx, e) {
2866             alt bcx_ccx(bcx).method_map.find(e.id) {
2867               some(typeck::method_static(did)) { // An impl method
2868                 ret trans_impl::trans_static_callee(bcx, e, base, did);
2869               }
2870               some(typeck::method_param(iid, off, p, b)) {
2871                 ret trans_impl::trans_dict_callee(
2872                     bcx, e, base, iid, off, p, b);
2873               }
2874               none. { // An object method
2875                 let of = trans_object_field(bcx, base, ident);
2876                 ret {bcx: of.bcx, val: of.mthptr, kind: owned,
2877                      env: obj_env(of.objptr), generic: none};
2878               }
2879             }
2880         }
2881       }
2882       _ {}
2883     }
2884     let lv = trans_temp_lval(bcx, e);
2885     ret lval_no_env(lv.bcx, lv.val, lv.kind);
2886 }
2887
2888 // Use this when you know you are compiling an lval.
2889 // The additional bool returned indicates whether it's mem (that is
2890 // represented as an alloca or heap, hence needs a 'load' to be used as an
2891 // immediate).
2892 fn trans_lval(cx: @block_ctxt, e: @ast::expr) -> lval_result {
2893     alt e.node {
2894       ast::expr_path(p) {
2895         let v = trans_path(cx, p, e.id);
2896         ret lval_maybe_callee_to_lval(v, ty::expr_ty(bcx_tcx(cx), e));
2897       }
2898       ast::expr_field(base, ident, _) {
2899         ret trans_rec_field(cx, base, ident);
2900       }
2901       ast::expr_index(base, idx) {
2902         ret trans_index(cx, e.span, base, idx, e.id);
2903       }
2904       ast::expr_unary(ast::deref., base) {
2905         let ccx = bcx_ccx(cx);
2906         let sub = trans_temp_expr(cx, base);
2907         let t = ty::expr_ty(ccx.tcx, base);
2908         let val =
2909             alt ty::struct(ccx.tcx, t) {
2910               ty::ty_box(_) {
2911                 GEPi(sub.bcx, sub.val, [0, abi::box_rc_field_body])
2912               }
2913               ty::ty_res(_, _, _) {
2914                 GEPi(sub.bcx, sub.val, [0, 1])
2915               }
2916               ty::ty_tag(_, _) {
2917                 let ety = ty::expr_ty(ccx.tcx, e);
2918                 let sp = e.span;
2919                 let ellty =
2920                     if check type_has_static_size(ccx, ety) {
2921                         T_ptr(type_of(ccx, sp, ety))
2922                     } else { T_typaram_ptr(ccx.tn) };
2923                 PointerCast(sub.bcx, sub.val, ellty)
2924               }
2925               ty::ty_ptr(_) | ty::ty_uniq(_) { sub.val }
2926             };
2927         ret lval_owned(sub.bcx, val);
2928       }
2929       // This is a by-ref returning call. Regular calls are not lval
2930       ast::expr_call(f, args, _) {
2931         let cell = empty_dest_cell();
2932         let bcx = trans_call(cx, f, args, e.id, by_val(cell));
2933         ret lval_owned(bcx, *cell);
2934       }
2935       _ { bcx_ccx(cx).sess.span_bug(e.span, "non-lval in trans_lval"); }
2936     }
2937 }
2938
2939 fn maybe_add_env(bcx: @block_ctxt, c: lval_maybe_callee)
2940     -> (lval_kind, ValueRef) {
2941     alt c.env {
2942       is_closure. { (c.kind, c.val) }
2943       obj_env(_) | dict_env(_, _) {
2944         fail "Taking the value of a method does not work yet (issue #435)";
2945       }
2946       null_env. {
2947         let llfnty = llvm::LLVMGetElementType(val_ty(c.val));
2948         (temporary, create_real_fn_pair(bcx, llfnty, c.val,
2949                                         null_env_ptr(bcx)))
2950       }
2951     }
2952 }
2953
2954 fn lval_maybe_callee_to_lval(c: lval_maybe_callee, ty: ty::t) -> lval_result {
2955     alt c.generic {
2956       some(gi) {
2957         let n_args = vec::len(ty::ty_fn_args(bcx_tcx(c.bcx), ty));
2958         let args = vec::init_elt(none::<@ast::expr>, n_args);
2959         let space = alloc_ty(c.bcx, ty);
2960         let bcx = trans_closure::trans_bind_1(space.bcx, ty, c, args, ty,
2961                                               save_in(space.val));
2962         add_clean_temp(bcx, space.val, ty);
2963         ret {bcx: bcx, val: space.val, kind: temporary};
2964       }
2965       none. {
2966         let (kind, val) = maybe_add_env(c.bcx, c);
2967         ret {bcx: c.bcx, val: val, kind: kind};
2968       }
2969     }
2970 }
2971
2972 fn int_cast(bcx: @block_ctxt, lldsttype: TypeRef, llsrctype: TypeRef,
2973             llsrc: ValueRef, signed: bool) -> ValueRef {
2974     let srcsz = llvm::LLVMGetIntTypeWidth(llsrctype);
2975     let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype);
2976     ret if dstsz == srcsz {
2977             BitCast(bcx, llsrc, lldsttype)
2978         } else if srcsz > dstsz {
2979             TruncOrBitCast(bcx, llsrc, lldsttype)
2980         } else if signed {
2981             SExtOrBitCast(bcx, llsrc, lldsttype)
2982         } else { ZExtOrBitCast(bcx, llsrc, lldsttype) };
2983 }
2984
2985 fn float_cast(bcx: @block_ctxt, lldsttype: TypeRef, llsrctype: TypeRef,
2986               llsrc: ValueRef) -> ValueRef {
2987     let srcsz = lib::llvm::float_width(llsrctype);
2988     let dstsz = lib::llvm::float_width(lldsttype);
2989     ret if dstsz > srcsz {
2990             FPExt(bcx, llsrc, lldsttype)
2991         } else if srcsz > dstsz {
2992             FPTrunc(bcx, llsrc, lldsttype)
2993         } else { llsrc };
2994 }
2995
2996 fn trans_cast(cx: @block_ctxt, e: @ast::expr, id: ast::node_id,
2997               dest: dest) -> @block_ctxt {
2998     let ccx = bcx_ccx(cx);
2999     let e_res = trans_temp_expr(cx, e);
3000     let ll_t_in = val_ty(e_res.val);
3001     let t_in = ty::expr_ty(ccx.tcx, e);
3002     let t_out = node_id_type(ccx, id);
3003     // Check should be avoidable because it's a cast.
3004     // FIXME: Constrain types so as to avoid this check.
3005     check (type_has_static_size(ccx, t_out));
3006     let ll_t_out = type_of(ccx, e.span, t_out);
3007
3008     tag kind { pointer; integral; float; other; }
3009     fn t_kind(tcx: ty::ctxt, t: ty::t) -> kind {
3010         ret if ty::type_is_fp(tcx, t) {
3011                 float
3012             } else if ty::type_is_native(tcx, t) ||
3013                       ty::type_is_unsafe_ptr(tcx, t) {
3014                 pointer
3015             } else if ty::type_is_integral(tcx, t) {
3016                 integral
3017             } else { other };
3018     }
3019     let k_in = t_kind(ccx.tcx, t_in);
3020     let k_out = t_kind(ccx.tcx, t_out);
3021     let s_in = k_in == integral && ty::type_is_signed(ccx.tcx, t_in);
3022
3023     let newval =
3024         alt {in: k_in, out: k_out} {
3025           {in: integral., out: integral.} {
3026             int_cast(e_res.bcx, ll_t_out, ll_t_in, e_res.val, s_in)
3027           }
3028           {in: float., out: float.} {
3029             float_cast(e_res.bcx, ll_t_out, ll_t_in, e_res.val)
3030           }
3031           {in: integral., out: float.} {
3032             if s_in {
3033                 SIToFP(e_res.bcx, e_res.val, ll_t_out)
3034             } else { UIToFP(e_res.bcx, e_res.val, ll_t_out) }
3035           }
3036           {in: float., out: integral.} {
3037             if ty::type_is_signed(ccx.tcx, t_out) {
3038                 FPToSI(e_res.bcx, e_res.val, ll_t_out)
3039             } else { FPToUI(e_res.bcx, e_res.val, ll_t_out) }
3040           }
3041           {in: integral., out: pointer.} {
3042             IntToPtr(e_res.bcx, e_res.val, ll_t_out)
3043           }
3044           {in: pointer., out: integral.} {
3045             PtrToInt(e_res.bcx, e_res.val, ll_t_out)
3046           }
3047           {in: pointer., out: pointer.} {
3048             PointerCast(e_res.bcx, e_res.val, ll_t_out)
3049           }
3050           _ { ccx.sess.bug("Translating unsupported cast.") }
3051         };
3052     ret store_in_dest(e_res.bcx, newval, dest);
3053 }
3054
3055 fn trans_arg_expr(cx: @block_ctxt, arg: ty::arg, lldestty0: TypeRef,
3056                   &to_zero: [{v: ValueRef, t: ty::t}],
3057                   &to_revoke: [{v: ValueRef, t: ty::t}], e: @ast::expr) ->
3058    result {
3059     let ccx = bcx_ccx(cx);
3060     let e_ty = ty::expr_ty(ccx.tcx, e);
3061     let is_bot = ty::type_is_bot(ccx.tcx, e_ty);
3062     let lv = trans_temp_lval(cx, e);
3063     let bcx = lv.bcx;
3064     let val = lv.val;
3065     if is_bot {
3066         // For values of type _|_, we generate an
3067         // "undef" value, as such a value should never
3068         // be inspected. It's important for the value
3069         // to have type lldestty0 (the callee's expected type).
3070         val = llvm::LLVMGetUndef(lldestty0);
3071     } else if arg.mode == ast::by_ref || arg.mode == ast::by_val {
3072         let copied = false, imm = ty::type_is_immediate(ccx.tcx, e_ty);
3073         if arg.mode == ast::by_ref && lv.kind != owned && imm {
3074             val = do_spill_noroot(bcx, val);
3075             copied = true;
3076         }
3077         if ccx.copy_map.contains_key(e.id) && lv.kind != temporary {
3078             if !copied {
3079                 let alloc = alloc_ty(bcx, e_ty);
3080                 bcx = copy_val(alloc.bcx, INIT, alloc.val,
3081                                load_if_immediate(alloc.bcx, val, e_ty), e_ty);
3082                 val = alloc.val;
3083             } else { bcx = take_ty(bcx, val, e_ty); }
3084             add_clean(bcx, val, e_ty);
3085         }
3086         if arg.mode == ast::by_val && (lv.kind == owned || !imm) {
3087             val = Load(bcx, val);
3088         }
3089     } else if arg.mode == ast::by_copy {
3090         let {bcx: cx, val: alloc} = alloc_ty(bcx, e_ty);
3091         let last_use = ccx.last_uses.contains_key(e.id);
3092         bcx = cx;
3093         if lv.kind == temporary { revoke_clean(bcx, val); }
3094         if lv.kind == owned || !ty::type_is_immediate(ccx.tcx, e_ty) {
3095             bcx = memmove_ty(bcx, alloc, val, e_ty);
3096             if last_use && ty::type_needs_drop(ccx.tcx, e_ty) {
3097                 bcx = zero_alloca(bcx, val, e_ty);
3098             }
3099         } else { Store(bcx, val, alloc); }
3100         val = alloc;
3101         if lv.kind != temporary && !last_use {
3102             bcx = take_ty(bcx, val, e_ty);
3103         }
3104     } else if ty::type_is_immediate(ccx.tcx, e_ty) && lv.kind != owned {
3105         let r = do_spill(bcx, val, e_ty);
3106         val = r.val;
3107         bcx = r.bcx;
3108     }
3109
3110     if !is_bot && ty::type_contains_params(ccx.tcx, arg.ty) {
3111         let lldestty = lldestty0;
3112         val = PointerCast(bcx, val, lldestty);
3113     }
3114
3115     // Collect arg for later if it happens to be one we've moving out.
3116     if arg.mode == ast::by_move {
3117         if lv.kind == owned {
3118             // Use actual ty, not declared ty -- anything else doesn't make
3119             // sense if declared ty is a ty param
3120             to_zero += [{v: lv.val, t: e_ty}];
3121         } else { to_revoke += [{v: lv.val, t: e_ty}]; }
3122     }
3123     ret rslt(bcx, val);
3124 }
3125
3126
3127 // NB: must keep 4 fns in sync:
3128 //
3129 //  - type_of_fn
3130 //  - create_llargs_for_fn_args.
3131 //  - new_fn_ctxt
3132 //  - trans_args
3133 fn trans_args(cx: @block_ctxt, llenv: ValueRef,
3134               gen: option::t<generic_info>, es: [@ast::expr], fn_ty: ty::t,
3135               dest: dest)
3136    -> {bcx: @block_ctxt,
3137        args: [ValueRef],
3138        retslot: ValueRef,
3139        to_zero: [{v: ValueRef, t: ty::t}],
3140        to_revoke: [{v: ValueRef, t: ty::t}]} {
3141
3142     let args: [ty::arg] = ty::ty_fn_args(bcx_tcx(cx), fn_ty);
3143     let llargs: [ValueRef] = [];
3144     let lltydescs: [ValueRef] = [];
3145     let to_zero = [];
3146     let to_revoke = [];
3147
3148     let ccx = bcx_ccx(cx);
3149     let tcx = ccx.tcx;
3150     let bcx = cx;
3151
3152     let retty = ty::ty_fn_ret(tcx, fn_ty), full_retty = retty;
3153     alt gen {
3154       some(g) {
3155         lazily_emit_all_generic_info_tydesc_glues(cx, g);
3156         let i = 0u, n_orig = 0u;
3157         for param in *g.param_bounds {
3158             lltydescs += [g.tydescs[i]];
3159             for bound in *param {
3160                 alt bound {
3161                   ty::bound_iface(_) {
3162                     let res = trans_impl::get_dict(
3163                         bcx, option::get(g.origins)[n_orig]);
3164                     lltydescs += [res.val];
3165                     bcx = res.bcx;
3166                     n_orig += 1u;
3167                   }
3168                   _ {}
3169                 }
3170             }
3171             i += 1u;
3172         }
3173         args = ty::ty_fn_args(tcx, g.item_type);
3174         retty = ty::ty_fn_ret(tcx, g.item_type);
3175       }
3176       _ { }
3177     }
3178     // Arg 0: Output pointer.
3179     let llretslot = alt dest {
3180       ignore. {
3181         if ty::type_is_nil(tcx, retty) {
3182             llvm::LLVMGetUndef(T_ptr(T_nil()))
3183         } else {
3184             let {bcx: cx, val} = alloc_ty(bcx, full_retty);
3185             bcx = cx;
3186             val
3187         }
3188       }
3189       save_in(dst) { dst }
3190       by_val(_) {
3191           let {bcx: cx, val} = alloc_ty(bcx, full_retty);
3192           bcx = cx;
3193           val
3194       }
3195     };
3196
3197     if ty::type_contains_params(tcx, retty) {
3198         // It's possible that the callee has some generic-ness somewhere in
3199         // its return value -- say a method signature within an obj or a fn
3200         // type deep in a structure -- which the caller has a concrete view
3201         // of. If so, cast the caller's view of the restlot to the callee's
3202         // view, for the sake of making a type-compatible call.
3203         check non_ty_var(ccx, retty);
3204         let llretty = T_ptr(type_of_inner(ccx, bcx.sp, retty));
3205         llargs += [PointerCast(cx, llretslot, llretty)];
3206     } else { llargs += [llretslot]; }
3207
3208     // Arg 1: Env (closure-bindings / self-obj)
3209     llargs += [llenv];
3210
3211     // Args >2: ty_params ...
3212     llargs += lltydescs;
3213
3214     // ... then explicit args.
3215
3216     // First we figure out the caller's view of the types of the arguments.
3217     // This will be needed if this is a generic call, because the callee has
3218     // to cast her view of the arguments to the caller's view.
3219     let arg_tys = type_of_explicit_args(ccx, cx.sp, args);
3220     let i = 0u;
3221     for e: @ast::expr in es {
3222         let r = trans_arg_expr(bcx, args[i], arg_tys[i], to_zero, to_revoke,
3223                                e);
3224         bcx = r.bcx;
3225         llargs += [r.val];
3226         i += 1u;
3227     }
3228     ret {bcx: bcx,
3229          args: llargs,
3230          retslot: llretslot,
3231          to_zero: to_zero,
3232          to_revoke: to_revoke};
3233 }
3234
3235 fn trans_call(in_cx: @block_ctxt, f: @ast::expr,
3236               args: [@ast::expr], id: ast::node_id, dest: dest)
3237     -> @block_ctxt {
3238     // NB: 'f' isn't necessarily a function; it might be an entire self-call
3239     // expression because of the hack that allows us to process self-calls
3240     // with trans_call.
3241     let tcx = bcx_tcx(in_cx);
3242     let fn_expr_ty = ty::expr_ty(tcx, f);
3243
3244     let cx = new_scope_block_ctxt(in_cx, "call");
3245     Br(in_cx, cx.llbb);
3246     let f_res = trans_callee(cx, f);
3247     let bcx = f_res.bcx;
3248
3249     let faddr = f_res.val;
3250     let llenv, dict_param = none;
3251     alt f_res.env {
3252       null_env. {
3253         llenv = llvm::LLVMGetUndef(T_opaque_boxed_closure_ptr(bcx_ccx(cx)));
3254       }
3255       obj_env(e) { llenv = e; }
3256       dict_env(dict, e) { llenv = e; dict_param = some(dict); }
3257       is_closure. {
3258         // It's a closure. Have to fetch the elements
3259         if f_res.kind == owned {
3260             faddr = load_if_immediate(bcx, faddr, fn_expr_ty);
3261         }
3262         let pair = faddr;
3263         faddr = GEPi(bcx, pair, [0, abi::fn_field_code]);
3264         faddr = Load(bcx, faddr);
3265         let llclosure = GEPi(bcx, pair, [0, abi::fn_field_box]);
3266         llenv = Load(bcx, llclosure);
3267       }
3268     }
3269
3270     let ret_ty = ty::node_id_to_type(tcx, id);
3271     let args_res =
3272         trans_args(bcx, llenv, f_res.generic, args, fn_expr_ty, dest);
3273     bcx = args_res.bcx;
3274     let llargs = args_res.args;
3275     option::may(dict_param) {|dict| llargs = [dict] + llargs}
3276     let llretslot = args_res.retslot;
3277
3278     /* If the block is terminated,
3279        then one or more of the args has
3280        type _|_. Since that means it diverges, the code
3281        for the call itself is unreachable. */
3282     bcx = invoke_full(bcx, faddr, llargs, args_res.to_zero,
3283                       args_res.to_revoke);
3284     alt dest {
3285       ignore. {
3286         if llvm::LLVMIsUndef(llretslot) != lib::llvm::True {
3287             bcx = drop_ty(bcx, llretslot, ret_ty);
3288         }
3289       }
3290       save_in(_) { } // Already saved by callee
3291       by_val(cell) {
3292         *cell = Load(bcx, llretslot);
3293       }
3294     }
3295     // Forget about anything we moved out.
3296     bcx = zero_and_revoke(bcx, args_res.to_zero, args_res.to_revoke);
3297
3298     bcx = trans_block_cleanups(bcx, cx);
3299     let next_cx = new_sub_block_ctxt(in_cx, "next");
3300     if bcx.unreachable || ty::type_is_bot(tcx, ret_ty) {
3301         Unreachable(next_cx);
3302     }
3303     Br(bcx, next_cx.llbb);
3304     ret next_cx;
3305 }
3306
3307 fn zero_and_revoke(bcx: @block_ctxt,
3308                    to_zero: [{v: ValueRef, t: ty::t}],
3309                    to_revoke: [{v: ValueRef, t: ty::t}]) -> @block_ctxt {
3310     let bcx = bcx;
3311     for {v, t} in to_zero {
3312         bcx = zero_alloca(bcx, v, t);
3313     }
3314     for {v, _} in to_revoke { revoke_clean(bcx, v); }
3315     ret bcx;
3316 }
3317
3318 fn invoke(bcx: @block_ctxt, llfn: ValueRef,
3319           llargs: [ValueRef]) -> @block_ctxt {
3320     ret invoke_(bcx, llfn, llargs, [], [], Invoke);
3321 }
3322
3323 fn invoke_full(bcx: @block_ctxt, llfn: ValueRef, llargs: [ValueRef],
3324                to_zero: [{v: ValueRef, t: ty::t}],
3325                to_revoke: [{v: ValueRef, t: ty::t}]) -> @block_ctxt {
3326     ret invoke_(bcx, llfn, llargs, to_zero, to_revoke, Invoke);
3327 }
3328
3329 fn invoke_(bcx: @block_ctxt, llfn: ValueRef, llargs: [ValueRef],
3330            to_zero: [{v: ValueRef, t: ty::t}],
3331            to_revoke: [{v: ValueRef, t: ty::t}],
3332            invoker: fn(@block_ctxt, ValueRef, [ValueRef],
3333                        BasicBlockRef, BasicBlockRef)) -> @block_ctxt {
3334     // FIXME: May be worth turning this into a plain call when there are no
3335     // cleanups to run
3336     if bcx.unreachable { ret bcx; }
3337     let normal_bcx = new_sub_block_ctxt(bcx, "normal return");
3338     invoker(bcx, llfn, llargs, normal_bcx.llbb,
3339             get_landing_pad(bcx, to_zero, to_revoke));
3340     ret normal_bcx;
3341 }
3342
3343 fn get_landing_pad(bcx: @block_ctxt,
3344                    to_zero: [{v: ValueRef, t: ty::t}],
3345                    to_revoke: [{v: ValueRef, t: ty::t}]
3346                   ) -> BasicBlockRef {
3347     let have_zero_or_revoke = vec::is_not_empty(to_zero)
3348         || vec::is_not_empty(to_revoke);
3349     let scope_bcx = find_scope_for_lpad(bcx, have_zero_or_revoke);
3350     if scope_bcx.lpad_dirty || have_zero_or_revoke {
3351         let unwind_bcx = new_sub_block_ctxt(bcx, "unwind");
3352         trans_landing_pad(unwind_bcx, to_zero, to_revoke);
3353         scope_bcx.lpad = some(unwind_bcx.llbb);
3354         scope_bcx.lpad_dirty = have_zero_or_revoke;
3355     }
3356     assert option::is_some(scope_bcx.lpad);
3357     ret option::get(scope_bcx.lpad);
3358
3359     fn find_scope_for_lpad(bcx: @block_ctxt,
3360                            have_zero_or_revoke: bool) -> @block_ctxt {
3361         let scope_bcx = bcx;
3362         while true {
3363             scope_bcx = find_scope_cx(scope_bcx);
3364             if vec::is_not_empty(scope_bcx.cleanups)
3365                 || have_zero_or_revoke {
3366                 ret scope_bcx;
3367             } else {
3368                 scope_bcx = alt scope_bcx.parent {
3369                   parent_some(b) { b }
3370                   parent_none. {
3371                     ret scope_bcx;
3372                   }
3373                 };
3374             }
3375         }
3376         fail;
3377     }
3378 }
3379
3380 fn trans_landing_pad(bcx: @block_ctxt,
3381                      to_zero: [{v: ValueRef, t: ty::t}],
3382                      to_revoke: [{v: ValueRef, t: ty::t}]) -> BasicBlockRef {
3383     // The landing pad return type (the type being propagated). Not sure what
3384     // this represents but it's determined by the personality function and
3385     // this is what the EH proposal example uses.
3386     let llretty = T_struct([T_ptr(T_i8()), T_i32()]);
3387     // The exception handling personality function. This is the C++
3388     // personality function __gxx_personality_v0, wrapped in our naming
3389     // convention.
3390     let personality = bcx_ccx(bcx).upcalls.rust_personality;
3391     // The only landing pad clause will be 'cleanup'
3392     let clauses = 1u;
3393     let llpad = LandingPad(bcx, llretty, personality, clauses);
3394     // The landing pad result is used both for modifying the landing pad
3395     // in the C API and as the exception value
3396     let llretval = llpad;
3397     // The landing pad block is a cleanup
3398     SetCleanup(bcx, llpad);
3399
3400     // Because we may have unwound across a stack boundary, we must call into
3401     // the runtime to figure out which stack segment we are on and place the
3402     // stack limit back into the TLS.
3403     Call(bcx, bcx_ccx(bcx).upcalls.reset_stack_limit, []);
3404
3405     // FIXME: This seems like a very naive and redundant way to generate the
3406     // landing pads, as we're re-generating all in-scope cleanups for each
3407     // function call. Probably good optimization opportunities here.
3408     let bcx = zero_and_revoke(bcx, to_zero, to_revoke);
3409     let scope_cx = bcx;
3410     while true {
3411         scope_cx = find_scope_cx(scope_cx);
3412         bcx = trans_block_cleanups(bcx, scope_cx);
3413         scope_cx = alt scope_cx.parent {
3414           parent_some(b) { b }
3415           parent_none. { break; }
3416         };
3417     }
3418
3419     // Continue unwinding
3420     Resume(bcx, llretval);
3421     ret bcx.llbb;
3422 }
3423
3424 fn trans_tup(bcx: @block_ctxt, elts: [@ast::expr], id: ast::node_id,
3425              dest: dest) -> @block_ctxt {
3426     let t = node_id_type(bcx.fcx.lcx.ccx, id);
3427     let bcx = bcx;
3428     let addr = alt dest {
3429       ignore. {
3430         for ex in elts { bcx = trans_expr(bcx, ex, ignore); }
3431         ret bcx;
3432       }
3433       save_in(pos) { pos }
3434     };
3435     let temp_cleanups = [], i = 0;
3436     for e in elts {
3437         let dst = GEP_tup_like_1(bcx, t, addr, [0, i]);
3438         let e_ty = ty::expr_ty(bcx_tcx(bcx), e);
3439         bcx = trans_expr_save_in(dst.bcx, e, dst.val);
3440         add_clean_temp_mem(bcx, dst.val, e_ty);
3441         temp_cleanups += [dst.val];
3442         i += 1;
3443     }
3444     for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
3445     ret bcx;
3446 }
3447
3448 fn trans_rec(bcx: @block_ctxt, fields: [ast::field],
3449              base: option::t<@ast::expr>, id: ast::node_id,
3450              dest: dest) -> @block_ctxt {
3451     let t = node_id_type(bcx_ccx(bcx), id);
3452     let bcx = bcx;
3453     let addr = alt dest {
3454       ignore. {
3455         for fld in fields {
3456             bcx = trans_expr(bcx, fld.node.expr, ignore);
3457         }
3458         ret bcx;
3459       }
3460       save_in(pos) { pos }
3461     };
3462
3463     let ty_fields = alt ty::struct(bcx_tcx(bcx), t) { ty::ty_rec(f) { f } };
3464     let temp_cleanups = [];
3465     for fld in fields {
3466         let ix = option::get(vec::position_pred(ty_fields, {|ft|
3467             str::eq(fld.node.ident, ft.ident)
3468         }));
3469         let dst = GEP_tup_like_1(bcx, t, addr, [0, ix as int]);
3470         bcx = trans_expr_save_in(dst.bcx, fld.node.expr, dst.val);
3471         add_clean_temp_mem(bcx, dst.val, ty_fields[ix].mt.ty);
3472         temp_cleanups += [dst.val];
3473     }
3474     alt base {
3475       some(bexp) {
3476         let {bcx: cx, val: base_val} = trans_temp_expr(bcx, bexp), i = 0;
3477         bcx = cx;
3478         // Copy over inherited fields
3479         for tf in ty_fields {
3480             if !vec::any(fields, {|f| str::eq(f.node.ident, tf.ident)}) {
3481                 let dst = GEP_tup_like_1(bcx, t, addr, [0, i]);
3482                 let base = GEP_tup_like_1(bcx, t, base_val, [0, i]);
3483                 let val = load_if_immediate(base.bcx, base.val, tf.mt.ty);
3484                 bcx = copy_val(base.bcx, INIT, dst.val, val, tf.mt.ty);
3485             }
3486             i += 1;
3487         }
3488       }
3489       none. {}
3490     };
3491
3492     // Now revoke the cleanups as we pass responsibility for the data
3493     // structure on to the caller
3494     for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
3495     ret bcx;
3496 }
3497
3498 // Store the result of an expression in the given memory location, ensuring
3499 // that nil or bot expressions get ignore rather than save_in as destination.
3500 fn trans_expr_save_in(bcx: @block_ctxt, e: @ast::expr, dest: ValueRef)
3501     -> @block_ctxt {
3502     let tcx = bcx_tcx(bcx), t = ty::expr_ty(tcx, e);
3503     let do_ignore = ty::type_is_bot(tcx, t) || ty::type_is_nil(tcx, t);
3504     ret trans_expr(bcx, e, do_ignore ? ignore : save_in(dest));
3505 }
3506
3507 // Call this to compile an expression that you need as an intermediate value,
3508 // and you want to know whether you're dealing with an lval or not (the kind
3509 // field in the returned struct). For non-intermediates, use trans_expr or
3510 // trans_expr_save_in. For intermediates where you don't care about lval-ness,
3511 // use trans_temp_expr.
3512 fn trans_temp_lval(bcx: @block_ctxt, e: @ast::expr) -> lval_result {
3513     let bcx = bcx;
3514     if expr_is_lval(bcx, e) {
3515         ret trans_lval(bcx, e);
3516     } else {
3517         let tcx = bcx_tcx(bcx);
3518         let ty = ty::expr_ty(tcx, e);
3519         if ty::type_is_nil(tcx, ty) || ty::type_is_bot(tcx, ty) {
3520             bcx = trans_expr(bcx, e, ignore);
3521             ret {bcx: bcx, val: C_nil(), kind: temporary};
3522         } else if ty::type_is_immediate(bcx_tcx(bcx), ty) {
3523             let cell = empty_dest_cell();
3524             bcx = trans_expr(bcx, e, by_val(cell));
3525             add_clean_temp(bcx, *cell, ty);
3526             ret {bcx: bcx, val: *cell, kind: temporary};
3527         } else {
3528             let {bcx, val: scratch} = alloc_ty(bcx, ty);
3529             bcx = trans_expr_save_in(bcx, e, scratch);
3530             add_clean_temp(bcx, scratch, ty);
3531             ret {bcx: bcx, val: scratch, kind: temporary};
3532         }
3533     }
3534 }
3535
3536 // Use only for intermediate values. See trans_expr and trans_expr_save_in for
3537 // expressions that must 'end up somewhere' (or get ignored).
3538 fn trans_temp_expr(bcx: @block_ctxt, e: @ast::expr) -> result {
3539     let {bcx, val, kind} = trans_temp_lval(bcx, e);
3540     if kind == owned {
3541         val = load_if_immediate(bcx, val, ty::expr_ty(bcx_tcx(bcx), e));
3542     }
3543     ret {bcx: bcx, val: val};
3544 }
3545
3546 // Translate an expression, with the dest argument deciding what happens with
3547 // the result. Invariants:
3548 // - exprs returning nil or bot always get dest=ignore
3549 // - exprs with non-immediate type never get dest=by_val
3550 fn trans_expr(bcx: @block_ctxt, e: @ast::expr, dest: dest) -> @block_ctxt {
3551     let tcx = bcx_tcx(bcx);
3552     debuginfo::update_source_pos(bcx, e.span);
3553
3554     if expr_is_lval(bcx, e) {
3555         ret lval_to_dps(bcx, e, dest);
3556     }
3557
3558     alt e.node {
3559       ast::expr_if(cond, thn, els) | ast::expr_if_check(cond, thn, els) {
3560         ret trans_if(bcx, cond, thn, els, dest);
3561       }
3562       ast::expr_ternary(_, _, _) {
3563         ret trans_expr(bcx, ast_util::ternary_to_if(e), dest);
3564       }
3565       ast::expr_alt(expr, arms) {
3566         ret trans_alt::trans_alt(bcx, expr, arms, dest);
3567       }
3568       ast::expr_block(blk) {
3569         let sub_cx = new_scope_block_ctxt(bcx, "block-expr body");
3570         Br(bcx, sub_cx.llbb);
3571         sub_cx = trans_block_dps(sub_cx, blk, dest);
3572         let next_cx = new_sub_block_ctxt(bcx, "next");
3573         Br(sub_cx, next_cx.llbb);
3574         if sub_cx.unreachable { Unreachable(next_cx); }
3575         ret next_cx;
3576       }
3577       ast::expr_rec(args, base) {
3578         ret trans_rec(bcx, args, base, e.id, dest);
3579       }
3580       ast::expr_tup(args) { ret trans_tup(bcx, args, e.id, dest); }
3581       ast::expr_lit(lit) { ret trans_lit(bcx, *lit, dest); }
3582       ast::expr_vec(args, _) { ret tvec::trans_vec(bcx, args, e.id, dest); }
3583       ast::expr_binary(op, x, y) { ret trans_binary(bcx, op, x, y, dest); }
3584       ast::expr_unary(op, x) {
3585         assert op != ast::deref; // lvals are handled above
3586         ret trans_unary(bcx, op, x, e.id, dest);
3587       }
3588       ast::expr_fn(proto, decl, body, cap_clause) {
3589         ret trans_closure::trans_expr_fn(
3590             bcx, proto, decl, body, e.span, e.id, *cap_clause, dest);
3591       }
3592       ast::expr_fn_block(decl, body) {
3593         alt ty::struct(tcx, ty::expr_ty(tcx, e)) {
3594           ty::ty_fn({proto, _}) {
3595             #debug("translating fn_block %s with type %s",
3596                    expr_to_str(e), ty_to_str(tcx, ty::expr_ty(tcx, e)));
3597             let cap_clause = { copies: [], moves: [] };
3598             ret trans_closure::trans_expr_fn(
3599                 bcx, proto, decl, body, e.span, e.id, cap_clause, dest);
3600           }
3601           _ {
3602             fail "Type of fn block is not a function!";
3603           }
3604         }
3605       }
3606       ast::expr_bind(f, args) {
3607         ret trans_closure::trans_bind(
3608             bcx, f, args, e.id, dest);
3609       }
3610       ast::expr_copy(a) {
3611         if !expr_is_lval(bcx, a) {
3612             ret trans_expr(bcx, a, dest);
3613         }
3614         else { ret lval_to_dps(bcx, a, dest); }
3615       }
3616       ast::expr_cast(val, _) { ret trans_cast(bcx, val, e.id, dest); }
3617       ast::expr_anon_obj(anon_obj) {
3618         ret trans_anon_obj(bcx, e.span, anon_obj, e.id, dest);
3619       }
3620       ast::expr_call(f, args, _) {
3621         ret trans_call(bcx, f, args, e.id, dest);
3622       }
3623       ast::expr_field(_, _, _) {
3624         fail "Taking the value of a method does not work yet (issue #435)";
3625       }
3626
3627       // These return nothing
3628       ast::expr_break. {
3629         assert dest == ignore;
3630         ret trans_break(e.span, bcx);
3631       }
3632       ast::expr_cont. {
3633         assert dest == ignore;
3634         ret trans_cont(e.span, bcx);
3635       }
3636       ast::expr_ret(ex) {
3637         assert dest == ignore;
3638         ret trans_ret(bcx, ex);
3639       }
3640       ast::expr_be(ex) {
3641         // Ideally, the expr_be tag would have a precondition
3642         // that is_call_expr(ex) -- but we don't support that
3643         // yet
3644         // FIXME
3645         check (ast_util::is_call_expr(ex));
3646         ret trans_be(bcx, ex);
3647       }
3648       ast::expr_fail(expr) {
3649         assert dest == ignore;
3650         ret trans_fail_expr(bcx, some(e.span), expr);
3651       }
3652       ast::expr_log(_, lvl, a) {
3653         assert dest == ignore;
3654         ret trans_log(lvl, bcx, a);
3655       }
3656       ast::expr_assert(a) {
3657         assert dest == ignore;
3658         ret trans_check_expr(bcx, a, "Assertion");
3659       }
3660       ast::expr_check(ast::checked_expr., a) {
3661         assert dest == ignore;
3662         ret trans_check_expr(bcx, a, "Predicate");
3663       }
3664       ast::expr_check(ast::claimed_expr., a) {
3665         assert dest == ignore;
3666         /* Claims are turned on and off by a global variable
3667            that the RTS sets. This case generates code to
3668            check the value of that variable, doing nothing
3669            if it's set to false and acting like a check
3670            otherwise. */
3671         let c =
3672             get_extern_const(bcx_ccx(bcx).externs, bcx_ccx(bcx).llmod,
3673                              "check_claims", T_bool());
3674         let cond = Load(bcx, c);
3675
3676         let then_cx = new_scope_block_ctxt(bcx, "claim_then");
3677         let check_cx = trans_check_expr(then_cx, a, "Claim");
3678         let next_cx = new_sub_block_ctxt(bcx, "join");
3679
3680         CondBr(bcx, cond, then_cx.llbb, next_cx.llbb);
3681         Br(check_cx, next_cx.llbb);
3682         ret next_cx;
3683       }
3684       ast::expr_for(decl, seq, body) {
3685         assert dest == ignore;
3686         ret trans_for(bcx, decl, seq, body);
3687       }
3688       ast::expr_while(cond, body) {
3689         assert dest == ignore;
3690         ret trans_while(bcx, cond, body);
3691       }
3692       ast::expr_do_while(body, cond) {
3693         assert dest == ignore;
3694         ret trans_do_while(bcx, body, cond);
3695       }
3696       ast::expr_assign(dst, src) {
3697         assert dest == ignore;
3698         let src_r = trans_temp_lval(bcx, src);
3699         let {bcx, val: addr, kind} = trans_lval(src_r.bcx, dst);
3700         assert kind == owned;
3701         ret store_temp_expr(bcx, DROP_EXISTING, addr, src_r,
3702                             ty::expr_ty(bcx_tcx(bcx), src),
3703                             bcx_ccx(bcx).last_uses.contains_key(src.id));
3704       }
3705       ast::expr_move(dst, src) {
3706         // FIXME: calculate copy init-ness in typestate.
3707         assert dest == ignore;
3708         let src_r = trans_temp_lval(bcx, src);
3709         let {bcx, val: addr, kind} = trans_lval(src_r.bcx, dst);
3710         assert kind == owned;
3711         ret move_val(bcx, DROP_EXISTING, addr, src_r,
3712                      ty::expr_ty(bcx_tcx(bcx), src));
3713       }
3714       ast::expr_swap(dst, src) {
3715         assert dest == ignore;
3716         let lhs_res = trans_lval(bcx, dst);
3717         assert lhs_res.kind == owned;
3718         let rhs_res = trans_lval(lhs_res.bcx, src);
3719         let t = ty::expr_ty(tcx, src);
3720         let {bcx: bcx, val: tmp_alloc} = alloc_ty(rhs_res.bcx, t);
3721         // Swap through a temporary.
3722         bcx = move_val(bcx, INIT, tmp_alloc, lhs_res, t);
3723         bcx = move_val(bcx, INIT, lhs_res.val, rhs_res, t);
3724         ret move_val(bcx, INIT, rhs_res.val, lval_owned(bcx, tmp_alloc), t);
3725       }
3726       ast::expr_assign_op(op, dst, src) {
3727         assert dest == ignore;
3728         ret trans_assign_op(bcx, op, dst, src);
3729       }
3730     }
3731 }
3732
3733 fn lval_to_dps(bcx: @block_ctxt, e: @ast::expr, dest: dest) -> @block_ctxt {
3734     let lv = trans_lval(bcx, e), ccx = bcx_ccx(bcx);
3735     let {bcx, val, kind} = lv;
3736     let last_use = kind == owned && ccx.last_uses.contains_key(e.id);
3737     let ty = ty::expr_ty(ccx.tcx, e);
3738     alt dest {
3739       by_val(cell) {
3740         if kind == temporary {
3741             revoke_clean(bcx, val);
3742             *cell = val;
3743         } else if last_use {
3744             *cell = Load(bcx, val);
3745             if ty::type_needs_drop(ccx.tcx, ty) {
3746                 bcx = zero_alloca(bcx, val, ty);
3747             }
3748         } else {
3749             if kind == owned { val = Load(bcx, val); }
3750             let {bcx: cx, val} = take_ty_immediate(bcx, val, ty);
3751             *cell = val;
3752             bcx = cx;
3753         }
3754       }
3755       save_in(loc) {
3756         bcx = store_temp_expr(bcx, INIT, loc, lv, ty, last_use);
3757       }
3758       ignore. {}
3759     }
3760     ret bcx;
3761 }
3762
3763 fn do_spill(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
3764     // We have a value but we have to spill it, and root it, to pass by alias.
3765     let bcx = cx;
3766
3767     if ty::type_is_bot(bcx_tcx(bcx), t) {
3768         ret rslt(bcx, C_null(T_ptr(T_i8())));
3769     }
3770
3771     let r = alloc_ty(bcx, t);
3772     bcx = r.bcx;
3773     let llptr = r.val;
3774
3775     Store(bcx, v, llptr);
3776
3777     ret rslt(bcx, llptr);
3778 }
3779
3780 // Since this function does *not* root, it is the caller's responsibility to
3781 // ensure that the referent is pointed to by a root.
3782 fn do_spill_noroot(cx: @block_ctxt, v: ValueRef) -> ValueRef {
3783     let llptr = alloca(cx, val_ty(v));
3784     Store(cx, v, llptr);
3785     ret llptr;
3786 }
3787
3788 fn spill_if_immediate(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
3789     if ty::type_is_immediate(bcx_tcx(cx), t) { ret do_spill(cx, v, t); }
3790     ret rslt(cx, v);
3791 }
3792
3793 fn load_if_immediate(cx: @block_ctxt, v: ValueRef, t: ty::t) -> ValueRef {
3794     if ty::type_is_immediate(bcx_tcx(cx), t) { ret Load(cx, v); }
3795     ret v;
3796 }
3797
3798 fn trans_log(lvl: @ast::expr, cx: @block_ctxt, e: @ast::expr) -> @block_ctxt {
3799     let ccx = bcx_ccx(cx);
3800     let lcx = cx.fcx.lcx;
3801     let modname = str::connect(lcx.module_path, "::");
3802     let global = if lcx.ccx.module_data.contains_key(modname) {
3803         lcx.ccx.module_data.get(modname)
3804     } else {
3805         let s = link::mangle_internal_name_by_path_and_seq(
3806             lcx.ccx, lcx.module_path, "loglevel");
3807         let global = str::as_buf(s, {|buf|
3808             llvm::LLVMAddGlobal(lcx.ccx.llmod, T_i32(), buf)
3809         });
3810         llvm::LLVMSetGlobalConstant(global, False);
3811         llvm::LLVMSetInitializer(global, C_null(T_i32()));
3812         llvm::LLVMSetLinkage(global,
3813                              lib::llvm::LLVMInternalLinkage as llvm::Linkage);
3814         lcx.ccx.module_data.insert(modname, global);
3815         global
3816     };
3817     let level_cx = new_scope_block_ctxt(cx, "level");
3818     let log_cx = new_scope_block_ctxt(cx, "log");
3819     let after_cx = new_sub_block_ctxt(cx, "after");
3820     let load = Load(cx, global);
3821
3822     Br(cx, level_cx.llbb);
3823     let level_res = trans_temp_expr(level_cx, lvl);
3824     let test = ICmp(level_res.bcx, lib::llvm::LLVMIntUGE,
3825                     load, level_res.val);
3826
3827     CondBr(level_res.bcx, test, log_cx.llbb, after_cx.llbb);
3828     let sub = trans_temp_expr(log_cx, e);
3829     let e_ty = ty::expr_ty(bcx_tcx(cx), e);
3830     let log_bcx = sub.bcx;
3831
3832     let ti = none::<@tydesc_info>;
3833     let r = get_tydesc(log_bcx, e_ty, false, tps_normal, ti).result;
3834     log_bcx = r.bcx;
3835     let lltydesc = r.val;
3836
3837     // Call the polymorphic log function.
3838     r = spill_if_immediate(log_bcx, sub.val, e_ty);
3839     log_bcx = r.bcx;
3840     let llvalptr = r.val;
3841     let llval_i8 = PointerCast(log_bcx, llvalptr, T_ptr(T_i8()));
3842
3843     Call(log_bcx, ccx.upcalls.log_type,
3844          [lltydesc, llval_i8, level_res.val]);
3845
3846     log_bcx = trans_block_cleanups(log_bcx, log_cx);
3847     Br(log_bcx, after_cx.llbb);
3848     ret trans_block_cleanups(after_cx, level_cx);
3849 }
3850
3851 fn trans_check_expr(cx: @block_ctxt, e: @ast::expr, s: str) -> @block_ctxt {
3852     let cond_res = trans_temp_expr(cx, e);
3853     let expr_str = s + " " + expr_to_str(e) + " failed";
3854     let fail_cx = new_sub_block_ctxt(cx, "fail");
3855     trans_fail(fail_cx, some::<span>(e.span), expr_str);
3856     let next_cx = new_sub_block_ctxt(cx, "next");
3857     CondBr(cond_res.bcx, cond_res.val, next_cx.llbb, fail_cx.llbb);
3858     ret next_cx;
3859 }
3860
3861 fn trans_fail_expr(bcx: @block_ctxt, sp_opt: option::t<span>,
3862                    fail_expr: option::t<@ast::expr>) -> @block_ctxt {
3863     let bcx = bcx;
3864     alt fail_expr {
3865       some(expr) {
3866         let tcx = bcx_tcx(bcx);
3867         let expr_res = trans_temp_expr(bcx, expr);
3868         let e_ty = ty::expr_ty(tcx, expr);
3869         bcx = expr_res.bcx;
3870
3871         if ty::type_is_str(tcx, e_ty) {
3872             let data = tvec::get_dataptr(
3873                 bcx, expr_res.val, type_of_or_i8(
3874                     bcx, ty::mk_mach_uint(tcx, ast::ty_u8)));
3875             ret trans_fail_value(bcx, sp_opt, data);
3876         } else if bcx.unreachable {
3877             ret bcx;
3878         } else {
3879             bcx_ccx(bcx).sess.span_bug(
3880                 expr.span, "fail called with unsupported type " +
3881                 ty_to_str(tcx, e_ty));
3882         }
3883       }
3884       _ { ret trans_fail(bcx, sp_opt, "explicit failure"); }
3885     }
3886 }
3887
3888 fn trans_fail(bcx: @block_ctxt, sp_opt: option::t<span>, fail_str: str) ->
3889     @block_ctxt {
3890     let V_fail_str = C_cstr(bcx_ccx(bcx), fail_str);
3891     ret trans_fail_value(bcx, sp_opt, V_fail_str);
3892 }
3893
3894 fn trans_fail_value(bcx: @block_ctxt, sp_opt: option::t<span>,
3895                     V_fail_str: ValueRef) -> @block_ctxt {
3896     let ccx = bcx_ccx(bcx);
3897     let V_filename;
3898     let V_line;
3899     alt sp_opt {
3900       some(sp) {
3901         let loc = bcx_ccx(bcx).sess.lookup_pos(sp.lo);
3902         V_filename = C_cstr(bcx_ccx(bcx), loc.filename);
3903         V_line = loc.line as int;
3904       }
3905       none. { V_filename = C_cstr(bcx_ccx(bcx), "<runtime>"); V_line = 0; }
3906     }
3907     let V_str = PointerCast(bcx, V_fail_str, T_ptr(T_i8()));
3908     V_filename = PointerCast(bcx, V_filename, T_ptr(T_i8()));
3909     let args = [V_str, V_filename, C_int(ccx, V_line)];
3910     let bcx = invoke(bcx, bcx_ccx(bcx).upcalls._fail, args);
3911     Unreachable(bcx);
3912     ret bcx;
3913 }
3914
3915 fn trans_break_cont(sp: span, bcx: @block_ctxt, to_end: bool)
3916     -> @block_ctxt {
3917     // Locate closest loop block, outputting cleanup as we go.
3918     let cleanup_cx = bcx, bcx = bcx;
3919     while true {
3920         bcx = trans_block_cleanups(bcx, cleanup_cx);
3921         alt copy cleanup_cx.kind {
3922           LOOP_SCOPE_BLOCK(_cont, _break) {
3923             if to_end {
3924                 Br(bcx, _break.llbb);
3925             } else {
3926                 alt _cont {
3927                   option::some(_cont) { Br(bcx, _cont.llbb); }
3928                   _ { Br(bcx, cleanup_cx.llbb); }
3929                 }
3930             }
3931             Unreachable(bcx);
3932             ret bcx;
3933           }
3934           _ {
3935             alt cleanup_cx.parent {
3936               parent_some(cx) { cleanup_cx = cx; }
3937               parent_none. {
3938                 bcx_ccx(bcx).sess.span_fatal
3939                     (sp, if to_end { "Break" } else { "Cont" } +
3940                      " outside a loop");
3941               }
3942             }
3943           }
3944         }
3945     }
3946     // If we get here without returning, it's a bug
3947     bcx_ccx(bcx).sess.bug("in trans::trans_break_cont()");
3948 }
3949
3950 fn trans_break(sp: span, cx: @block_ctxt) -> @block_ctxt {
3951     ret trans_break_cont(sp, cx, true);
3952 }
3953
3954 fn trans_cont(sp: span, cx: @block_ctxt) -> @block_ctxt {
3955     ret trans_break_cont(sp, cx, false);
3956 }
3957
3958 fn trans_ret(bcx: @block_ctxt, e: option::t<@ast::expr>) -> @block_ctxt {
3959     let cleanup_cx = bcx, bcx = bcx;
3960     alt e {
3961       some(x) { bcx = trans_expr_save_in(bcx, x, bcx.fcx.llretptr); }
3962       _ {}
3963     }
3964     // run all cleanups and back out.
3965
3966     let more_cleanups: bool = true;
3967     while more_cleanups {
3968         bcx = trans_block_cleanups(bcx, cleanup_cx);
3969         alt cleanup_cx.parent {
3970           parent_some(b) { cleanup_cx = b; }
3971           parent_none. { more_cleanups = false; }
3972         }
3973     }
3974     build_return(bcx);
3975     Unreachable(bcx);
3976     ret bcx;
3977 }
3978
3979 fn build_return(bcx: @block_ctxt) { Br(bcx, bcx_fcx(bcx).llreturn); }
3980
3981 // fn trans_be(cx: &@block_ctxt, e: &@ast::expr) -> result {
3982 fn trans_be(cx: @block_ctxt, e: @ast::expr) : ast_util::is_call_expr(e) ->
3983    @block_ctxt {
3984     // FIXME: Turn this into a real tail call once
3985     // calling convention issues are settled
3986     ret trans_ret(cx, some(e));
3987 }
3988
3989 fn init_local(bcx: @block_ctxt, local: @ast::local) -> @block_ctxt {
3990     let ty = node_id_type(bcx_ccx(bcx), local.node.id);
3991     let llptr = alt bcx.fcx.lllocals.find(local.node.id) {
3992       some(local_mem(v)) { v }
3993       // This is a local that is kept immediate
3994       none. {
3995         let initexpr = alt local.node.init { some({expr, _}) { expr } };
3996         let {bcx, val, kind} = trans_temp_lval(bcx, initexpr);
3997         if kind != temporary {
3998             if kind == owned { val = Load(bcx, val); }
3999             let rs = take_ty_immediate(bcx, val, ty);
4000             bcx = rs.bcx; val = rs.val;
4001             add_clean_temp(bcx, val, ty);
4002         }
4003         bcx.fcx.lllocals.insert(local.node.pat.id, local_imm(val));
4004         ret bcx;
4005       }
4006     };
4007
4008     let bcx = bcx;
4009     alt local.node.init {
4010       some(init) {
4011         if init.op == ast::init_assign || !expr_is_lval(bcx, init.expr) {
4012             bcx = trans_expr_save_in(bcx, init.expr, llptr);
4013         } else { // This is a move from an lval, must perform an actual move
4014             let sub = trans_lval(bcx, init.expr);
4015             bcx = move_val(sub.bcx, INIT, llptr, sub, ty);
4016         }
4017       }
4018       _ { bcx = zero_alloca(bcx, llptr, ty); }
4019     }
4020     // Make a note to drop this slot on the way out.
4021     add_clean(bcx, llptr, ty);
4022     ret trans_alt::bind_irrefutable_pat(bcx, local.node.pat, llptr, false);
4023 }
4024
4025 fn init_ref_local(bcx: @block_ctxt, local: @ast::local) -> @block_ctxt {
4026     let init_expr = option::get(local.node.init).expr;
4027     let {bcx, val, kind} = trans_lval(bcx, init_expr);
4028     alt kind {
4029       owned_imm. { val = do_spill_noroot(bcx, val); }
4030       owned. {}
4031     }
4032     ret trans_alt::bind_irrefutable_pat(bcx, local.node.pat, val, false);
4033 }
4034
4035 fn zero_alloca(cx: @block_ctxt, llptr: ValueRef, t: ty::t)
4036     -> @block_ctxt {
4037     let bcx = cx;
4038     let ccx = bcx_ccx(cx);
4039     if check type_has_static_size(ccx, t) {
4040         let sp = cx.sp;
4041         let llty = type_of(ccx, sp, t);
4042         Store(bcx, C_null(llty), llptr);
4043     } else {
4044         let llsz = size_of(bcx, t);
4045         // FIXME passing in the align here is correct, but causes issue #843
4046         // let llalign = align_of(llsz.bcx, t);
4047         bcx = call_bzero(llsz.bcx, llptr, llsz.val, C_int(ccx, 0)).bcx;
4048     }
4049     ret bcx;
4050 }
4051
4052 fn trans_stmt(cx: @block_ctxt, s: ast::stmt) -> @block_ctxt {
4053     // FIXME Fill in cx.sp
4054
4055     if (!bcx_ccx(cx).sess.get_opts().no_asm_comments) {
4056         add_span_comment(cx, s.span, stmt_to_str(s));
4057     }
4058
4059     let bcx = cx;
4060     debuginfo::update_source_pos(cx, s.span);
4061
4062     alt s.node {
4063       ast::stmt_expr(e, _) | ast::stmt_semi(e, _) {
4064         bcx = trans_expr(cx, e, ignore);
4065       }
4066       ast::stmt_decl(d, _) {
4067         alt d.node {
4068           ast::decl_local(locals) {
4069             for (style, local) in locals {
4070                 if style == ast::let_copy {
4071                     bcx = init_local(bcx, local);
4072                 } else {
4073                     bcx = init_ref_local(bcx, local);
4074                 }
4075                 if bcx_ccx(cx).sess.get_opts().extra_debuginfo {
4076                     debuginfo::create_local_var(bcx, local);
4077                 }
4078             }
4079           }
4080           ast::decl_item(i) { trans_item(cx.fcx.lcx, *i); }
4081         }
4082       }
4083       _ { bcx_ccx(cx).sess.unimpl("stmt variant"); }
4084     }
4085
4086     ret bcx;
4087 }
4088
4089 // You probably don't want to use this one. See the
4090 // next three functions instead.
4091 fn new_block_ctxt(cx: @fn_ctxt, parent: block_parent, kind: block_kind,
4092                   name: str) -> @block_ctxt {
4093     let s = "";
4094     if cx.lcx.ccx.sess.get_opts().save_temps ||
4095            cx.lcx.ccx.sess.get_opts().debuginfo {
4096         s = cx.lcx.ccx.names.next(name);
4097     }
4098     let llbb: BasicBlockRef =
4099         str::as_buf(s, {|buf| llvm::LLVMAppendBasicBlock(cx.llfn, buf) });
4100     let bcx = @{llbb: llbb,
4101                 mutable terminated: false,
4102                 mutable unreachable: false,
4103                 parent: parent,
4104                 kind: kind,
4105                 mutable cleanups: [],
4106                 mutable lpad_dirty: true,
4107                 mutable lpad: option::none,
4108                 sp: cx.sp,
4109                 fcx: cx};
4110     alt parent {
4111       parent_some(cx) {
4112         if cx.unreachable { Unreachable(bcx); }
4113       }
4114       _ {}
4115     }
4116     ret bcx;
4117 }
4118
4119
4120 // Use this when you're at the top block of a function or the like.
4121 fn new_top_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4122     ret new_block_ctxt(fcx, parent_none, SCOPE_BLOCK, "function top level");
4123 }
4124
4125
4126 // Use this when you're at a curly-brace or similar lexical scope.
4127 fn new_scope_block_ctxt(bcx: @block_ctxt, n: str) -> @block_ctxt {
4128     ret new_block_ctxt(bcx.fcx, parent_some(bcx), SCOPE_BLOCK, n);
4129 }
4130
4131 fn new_loop_scope_block_ctxt(bcx: @block_ctxt, _cont: option::t<@block_ctxt>,
4132                              _break: @block_ctxt, n: str) -> @block_ctxt {
4133     ret new_block_ctxt(bcx.fcx, parent_some(bcx),
4134                        LOOP_SCOPE_BLOCK(_cont, _break), n);
4135 }
4136
4137
4138 // Use this when you're making a general CFG BB within a scope.
4139 fn new_sub_block_ctxt(bcx: @block_ctxt, n: str) -> @block_ctxt {
4140     ret new_block_ctxt(bcx.fcx, parent_some(bcx), NON_SCOPE_BLOCK, n);
4141 }
4142
4143 fn new_raw_block_ctxt(fcx: @fn_ctxt, llbb: BasicBlockRef) -> @block_ctxt {
4144     ret @{llbb: llbb,
4145           mutable terminated: false,
4146           mutable unreachable: false,
4147           parent: parent_none,
4148           kind: NON_SCOPE_BLOCK,
4149           mutable cleanups: [],
4150           mutable lpad_dirty: true,
4151           mutable lpad: option::none,
4152           sp: fcx.sp,
4153           fcx: fcx};
4154 }
4155
4156
4157 // trans_block_cleanups: Go through all the cleanups attached to this
4158 // block_ctxt and execute them.
4159 //
4160 // When translating a block that introdces new variables during its scope, we
4161 // need to make sure those variables go out of scope when the block ends.  We
4162 // do that by running a 'cleanup' function for each variable.
4163 // trans_block_cleanups runs all the cleanup functions for the block.
4164 fn trans_block_cleanups(bcx: @block_ctxt, cleanup_cx: @block_ctxt) ->
4165    @block_ctxt {
4166     if bcx.unreachable { ret bcx; }
4167     if cleanup_cx.kind == NON_SCOPE_BLOCK {
4168         assert (vec::len::<cleanup>(cleanup_cx.cleanups) == 0u);
4169     }
4170     let i = vec::len::<cleanup>(cleanup_cx.cleanups), bcx = bcx;
4171     while i > 0u {
4172         i -= 1u;
4173         let c = cleanup_cx.cleanups[i];
4174         alt c {
4175           clean(cfn) { bcx = cfn(bcx); }
4176           clean_temp(_, cfn) { bcx = cfn(bcx); }
4177         }
4178     }
4179     ret bcx;
4180 }
4181
4182 fn trans_fn_cleanups(fcx: @fn_ctxt, cx: @block_ctxt) {
4183     alt fcx.llobstacktoken {
4184       some(lltoken_) {
4185         let lltoken = lltoken_; // satisfy alias checker
4186         Call(cx, fcx_ccx(fcx).upcalls.dynastack_free, [lltoken]);
4187       }
4188       none. {/* nothing to do */ }
4189     }
4190 }
4191
4192 fn block_locals(b: ast::blk, it: block(@ast::local)) {
4193     for s: @ast::stmt in b.node.stmts {
4194         alt s.node {
4195           ast::stmt_decl(d, _) {
4196             alt d.node {
4197               ast::decl_local(locals) {
4198                 for (style, local) in locals {
4199                     if style == ast::let_copy { it(local); }
4200                 }
4201               }
4202               _ {/* fall through */ }
4203             }
4204           }
4205           _ {/* fall through */ }
4206         }
4207     }
4208 }
4209
4210 fn llstaticallocas_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4211     ret @{llbb: fcx.llstaticallocas,
4212           mutable terminated: false,
4213           mutable unreachable: false,
4214           parent: parent_none,
4215           kind: SCOPE_BLOCK,
4216           mutable cleanups: [],
4217           mutable lpad_dirty: true,
4218           mutable lpad: option::none,
4219           sp: fcx.sp,
4220           fcx: fcx};
4221 }
4222
4223 fn llderivedtydescs_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4224     ret @{llbb: fcx.llderivedtydescs,
4225           mutable terminated: false,
4226           mutable unreachable: false,
4227           parent: parent_none,
4228           kind: SCOPE_BLOCK,
4229           mutable cleanups: [],
4230           mutable lpad_dirty: true,
4231           mutable lpad: option::none,
4232           sp: fcx.sp,
4233           fcx: fcx};
4234 }
4235
4236
4237 fn alloc_ty(cx: @block_ctxt, t: ty::t) -> result {
4238     let bcx = cx;
4239     let ccx = bcx_ccx(cx);
4240     let val =
4241         if check type_has_static_size(ccx, t) {
4242             let sp = cx.sp;
4243             alloca(bcx, type_of(ccx, sp, t))
4244         } else {
4245             // NB: we have to run this particular 'size_of' in a
4246             // block_ctxt built on the llderivedtydescs block for the fn,
4247             // so that the size dominates the array_alloca that
4248             // comes next.
4249
4250             let n = size_of(llderivedtydescs_block_ctxt(bcx.fcx), t);
4251             bcx.fcx.llderivedtydescs = n.bcx.llbb;
4252             dynastack_alloca(bcx, T_i8(), n.val, t)
4253         };
4254
4255     // NB: since we've pushed all size calculations in this
4256     // function up to the alloca block, we actually return the
4257     // block passed into us unmodified; it doesn't really
4258     // have to be passed-and-returned here, but it fits
4259     // past caller conventions and may well make sense again,
4260     // so we leave it as-is.
4261
4262     if bcx_tcx(cx).sess.get_opts().do_gc {
4263         bcx = gc::add_gc_root(bcx, val, t);
4264     }
4265
4266     ret rslt(cx, val);
4267 }
4268
4269 fn alloc_local(cx: @block_ctxt, local: @ast::local) -> @block_ctxt {
4270     let t = node_id_type(bcx_ccx(cx), local.node.id);
4271     let is_simple = alt local.node.pat.node {
4272       ast::pat_bind(_, none.) { true } _ { false }
4273     };
4274     // Do not allocate space for locals that can be kept immediate.
4275     let ccx = bcx_ccx(cx);
4276     if is_simple && !ccx.mut_map.contains_key(local.node.pat.id) &&
4277        !ccx.last_uses.contains_key(local.node.pat.id) &&
4278        ty::type_is_immediate(ccx.tcx, t) {
4279         alt local.node.init {
4280           some({op: ast::init_assign., _}) { ret cx; }
4281           _ {}
4282         }
4283     }
4284     let r = alloc_ty(cx, t);
4285     alt local.node.pat.node {
4286       ast::pat_bind(ident, none.) {
4287         if bcx_ccx(cx).sess.get_opts().debuginfo {
4288             let _: () = str::as_buf(ident, {|buf|
4289                 llvm::LLVMSetValueName(r.val, buf)
4290             });
4291         }
4292       }
4293       _ { }
4294     }
4295     cx.fcx.lllocals.insert(local.node.id, local_mem(r.val));
4296     ret r.bcx;
4297 }
4298
4299 fn trans_block(bcx: @block_ctxt, b: ast::blk) -> @block_ctxt {
4300     trans_block_dps(bcx, b, ignore)
4301 }
4302
4303 fn trans_block_dps(bcx: @block_ctxt, b: ast::blk, dest: dest)
4304     -> @block_ctxt {
4305     let bcx = bcx;
4306     block_locals(b) {|local| bcx = alloc_local(bcx, local); };
4307     for s: @ast::stmt in b.node.stmts {
4308         debuginfo::update_source_pos(bcx, b.span);
4309         bcx = trans_stmt(bcx, *s);
4310     }
4311     alt b.node.expr {
4312       some(e) {
4313         let bt = ty::type_is_bot(bcx_tcx(bcx), ty::expr_ty(bcx_tcx(bcx), e));
4314         debuginfo::update_source_pos(bcx, e.span);
4315         bcx = trans_expr(bcx, e, bt ? ignore : dest);
4316       }
4317       _ { assert dest == ignore || bcx.unreachable; }
4318     }
4319     let rv = trans_block_cleanups(bcx, find_scope_cx(bcx));
4320     ret rv;
4321 }
4322
4323 fn new_local_ctxt(ccx: @crate_ctxt) -> @local_ctxt {
4324     let pth: [str] = [];
4325     ret @{path: pth,
4326           module_path: [ccx.link_meta.name],
4327           obj_typarams: [],
4328           obj_fields: [],
4329           ccx: ccx};
4330 }
4331
4332
4333 // Creates the standard quartet of basic blocks: static allocas, copy args,
4334 // derived tydescs, and dynamic allocas.
4335 fn mk_standard_basic_blocks(llfn: ValueRef) ->
4336    {sa: BasicBlockRef,
4337     ca: BasicBlockRef,
4338     dt: BasicBlockRef,
4339     da: BasicBlockRef,
4340     rt: BasicBlockRef} {
4341     ret {sa:
4342              str::as_buf("static_allocas",
4343                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4344          ca:
4345              str::as_buf("load_env",
4346                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4347          dt:
4348              str::as_buf("derived_tydescs",
4349                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4350          da:
4351              str::as_buf("dynamic_allocas",
4352                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4353          rt:
4354              str::as_buf("return",
4355                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) })};
4356 }
4357
4358
4359 // NB: must keep 4 fns in sync:
4360 //
4361 //  - type_of_fn
4362 //  - create_llargs_for_fn_args.
4363 //  - new_fn_ctxt
4364 //  - trans_args
4365 fn new_fn_ctxt_w_id(cx: @local_ctxt, sp: span, llfndecl: ValueRef,
4366                     id: ast::node_id, rstyle: ast::ret_style)
4367     -> @fn_ctxt {
4368     let llbbs = mk_standard_basic_blocks(llfndecl);
4369     ret @{llfn: llfndecl,
4370           llenv: llvm::LLVMGetParam(llfndecl, 1u),
4371           llretptr: llvm::LLVMGetParam(llfndecl, 0u),
4372           mutable llstaticallocas: llbbs.sa,
4373           mutable llloadenv: llbbs.ca,
4374           mutable llderivedtydescs_first: llbbs.dt,
4375           mutable llderivedtydescs: llbbs.dt,
4376           mutable lldynamicallocas: llbbs.da,
4377           mutable llreturn: llbbs.rt,
4378           mutable llobstacktoken: none::<ValueRef>,
4379           mutable llself: none::<val_self_pair>,
4380           llargs: new_int_hash::<local_val>(),
4381           llobjfields: new_int_hash::<ValueRef>(),
4382           lllocals: new_int_hash::<local_val>(),
4383           llupvars: new_int_hash::<ValueRef>(),
4384           mutable lltyparams: [],
4385           derived_tydescs: ty::new_ty_hash(),
4386           id: id,
4387           ret_style: rstyle,
4388           sp: sp,
4389           lcx: cx};
4390 }
4391
4392 fn new_fn_ctxt(cx: @local_ctxt, sp: span, llfndecl: ValueRef) -> @fn_ctxt {
4393     ret new_fn_ctxt_w_id(cx, sp, llfndecl, -1, ast::return_val);
4394 }
4395
4396 // NB: must keep 4 fns in sync:
4397 //
4398 //  - type_of_fn
4399 //  - create_llargs_for_fn_args.
4400 //  - new_fn_ctxt
4401 //  - trans_args
4402
4403 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
4404 // allocas created for them.
4405 //
4406 // When we translate a function, we need to map its incoming arguments to the
4407 // spaces that have been created for them (by code in the llallocas field of
4408 // the function's fn_ctxt).  create_llargs_for_fn_args populates the llargs
4409 // field of the fn_ctxt with
4410 fn create_llargs_for_fn_args(cx: @fn_ctxt, ty_self: self_arg,
4411                              args: [ast::arg], ty_params: [ast::ty_param]) {
4412     // Skip the implicit arguments 0, and 1.  TODO: Pull out 2u and define
4413     // it as a constant, since we're using it in several places in trans this
4414     // way.
4415     let arg_n = 2u;
4416     alt ty_self {
4417       obj_self(tt) | impl_self(tt) {
4418         cx.llself = some({v: cx.llenv, t: tt});
4419       }
4420       no_self. {}
4421     }
4422     alt ty_self {
4423       obj_self(_) {}
4424       _ {
4425         for tp in ty_params {
4426             let lltydesc = llvm::LLVMGetParam(cx.llfn, arg_n), dicts = none;
4427             arg_n += 1u;
4428             for bound in *fcx_tcx(cx).ty_param_bounds.get(tp.id) {
4429                 alt bound {
4430                   ty::bound_iface(_) {
4431                     let dict = llvm::LLVMGetParam(cx.llfn, arg_n);
4432                     arg_n += 1u;
4433                     dicts = some(alt dicts {
4434                       none. { [dict] }
4435                       some(ds) { ds + [dict] }
4436                     });
4437                   }
4438                   _ {}
4439                 }
4440             }
4441             cx.lltyparams += [{desc: lltydesc, dicts: dicts}];
4442         }
4443       }
4444     }
4445
4446     // Populate the llargs field of the function context with the ValueRefs
4447     // that we get from llvm::LLVMGetParam for each argument.
4448     for arg: ast::arg in args {
4449         let llarg = llvm::LLVMGetParam(cx.llfn, arg_n);
4450         assert (llarg as int != 0);
4451         // Note that this uses local_mem even for things passed by value.
4452         // copy_args_to_allocas will overwrite the table entry with local_imm
4453         // before it's actually used.
4454         cx.llargs.insert(arg.id, local_mem(llarg));
4455         arg_n += 1u;
4456     }
4457 }
4458
4459 fn copy_args_to_allocas(fcx: @fn_ctxt, bcx: @block_ctxt, args: [ast::arg],
4460                         arg_tys: [ty::arg]) -> @block_ctxt {
4461     if fcx_ccx(fcx).sess.get_opts().extra_debuginfo {
4462         llvm::LLVMAddAttribute(llvm::LLVMGetFirstParam(fcx.llfn),
4463                                lib::llvm::LLVMStructRetAttribute as
4464                                    lib::llvm::llvm::Attribute);
4465     }
4466     let arg_n: uint = 0u, bcx = bcx;
4467     for arg in arg_tys {
4468         let id = args[arg_n].id;
4469         let argval = alt fcx.llargs.get(id) { local_mem(v) { v } };
4470         alt arg.mode {
4471           ast::by_mut_ref. { }
4472           ast::by_move. | ast::by_copy. { add_clean(bcx, argval, arg.ty); }
4473           ast::by_val. {
4474             if !ty::type_is_immediate(bcx_tcx(bcx), arg.ty) {
4475                 let {bcx: cx, val: alloc} = alloc_ty(bcx, arg.ty);
4476                 bcx = cx;
4477                 Store(bcx, argval, alloc);
4478                 fcx.llargs.insert(id, local_mem(alloc));
4479             } else {
4480                 fcx.llargs.insert(id, local_imm(argval));
4481             }
4482           }
4483           ast::by_ref. {}
4484         }
4485         if fcx_ccx(fcx).sess.get_opts().extra_debuginfo {
4486             debuginfo::create_arg(bcx, args[arg_n]);
4487         }
4488         arg_n += 1u;
4489     }
4490     ret bcx;
4491 }
4492
4493 fn arg_tys_of_fn(ccx: @crate_ctxt, id: ast::node_id) -> [ty::arg] {
4494     alt ty::struct(ccx.tcx, ty::node_id_to_type(ccx.tcx, id)) {
4495       ty::ty_fn({inputs, _}) { inputs }
4496     }
4497 }
4498
4499 fn populate_fn_ctxt_from_llself(fcx: @fn_ctxt, llself: val_self_pair) {
4500     let ccx = fcx_ccx(fcx);
4501     let bcx = llstaticallocas_block_ctxt(fcx);
4502     let field_tys: [ty::t] = [];
4503     for f: ast::obj_field in bcx.fcx.lcx.obj_fields {
4504         field_tys += [node_id_type(ccx, f.id)];
4505     }
4506     // Synthesize a tuple type for the fields so that GEP_tup_like() can work
4507     // its magic.
4508
4509     let fields_tup_ty = ty::mk_tup(fcx.lcx.ccx.tcx, field_tys);
4510     let n_typarams = vec::len::<ast::ty_param>(bcx.fcx.lcx.obj_typarams);
4511     let llobj_box_ty: TypeRef = T_obj_ptr(ccx, n_typarams);
4512     let box_cell = GEPi(bcx, llself.v, [0, abi::obj_field_box]);
4513     let box_ptr = Load(bcx, box_cell);
4514     box_ptr = PointerCast(bcx, box_ptr, llobj_box_ty);
4515     let obj_typarams =
4516         GEPi(bcx, box_ptr, [0, abi::box_rc_field_body,
4517                             abi::obj_body_elt_typarams]);
4518
4519     // The object fields immediately follow the type parameters, so we skip
4520     // over them to get the pointer.
4521     let obj_fields =
4522         PointerCast(bcx, GEPi(bcx, obj_typarams, [1]),
4523                     T_ptr(type_of_or_i8(bcx, fields_tup_ty)));
4524
4525     let i: int = 0;
4526     for p: ast::ty_param in fcx.lcx.obj_typarams {
4527         let lltyparam: ValueRef =
4528             GEPi(bcx, obj_typarams, [0, i]);
4529         lltyparam = Load(bcx, lltyparam);
4530         fcx.lltyparams += [{desc: lltyparam, dicts: none}];
4531         i += 1;
4532     }
4533     i = 0;
4534     for f: ast::obj_field in fcx.lcx.obj_fields {
4535         // FIXME: silly check
4536         check type_is_tup_like(bcx, fields_tup_ty);
4537         let rslt = GEP_tup_like(bcx, fields_tup_ty, obj_fields, [0, i]);
4538         bcx = llstaticallocas_block_ctxt(fcx);
4539         let llfield = rslt.val;
4540         fcx.llobjfields.insert(f.id, llfield);
4541         i += 1;
4542     }
4543     fcx.llstaticallocas = bcx.llbb;
4544 }
4545
4546
4547 // Ties up the llstaticallocas -> llloadenv -> llderivedtydescs ->
4548 // lldynamicallocas -> lltop edges, and builds the return block.
4549 fn finish_fn(fcx: @fn_ctxt, lltop: BasicBlockRef) {
4550     Br(new_raw_block_ctxt(fcx, fcx.llstaticallocas), fcx.llloadenv);
4551     Br(new_raw_block_ctxt(fcx, fcx.llloadenv), fcx.llderivedtydescs_first);
4552     Br(new_raw_block_ctxt(fcx, fcx.llderivedtydescs), fcx.lldynamicallocas);
4553     Br(new_raw_block_ctxt(fcx, fcx.lldynamicallocas), lltop);
4554
4555     let ret_cx = new_raw_block_ctxt(fcx, fcx.llreturn);
4556     trans_fn_cleanups(fcx, ret_cx);
4557     RetVoid(ret_cx);
4558 }
4559
4560 tag self_arg { obj_self(ty::t); impl_self(ty::t); no_self; }
4561
4562 // trans_closure: Builds an LLVM function out of a source function.
4563 // If the function closes over its environment a closure will be
4564 // returned.
4565 fn trans_closure(cx: @local_ctxt, sp: span, decl: ast::fn_decl,
4566                  body: ast::blk, llfndecl: ValueRef,
4567                  ty_self: self_arg, ty_params: [ast::ty_param],
4568                  id: ast::node_id, maybe_load_env: block(@fn_ctxt)) {
4569     set_uwtable(llfndecl);
4570
4571     // Set up arguments to the function.
4572     let fcx = new_fn_ctxt_w_id(cx, sp, llfndecl, id, decl.cf);
4573     create_llargs_for_fn_args(fcx, ty_self, decl.inputs, ty_params);
4574     alt ty_self {
4575       obj_self(_) {
4576           populate_fn_ctxt_from_llself(fcx, option::get(fcx.llself));
4577       }
4578       _ { }
4579     }
4580
4581     // Create the first basic block in the function and keep a handle on it to
4582     //  pass to finish_fn later.
4583     let bcx = new_top_block_ctxt(fcx);
4584     let lltop = bcx.llbb;
4585     let block_ty = node_id_type(cx.ccx, body.node.id);
4586
4587     let arg_tys = arg_tys_of_fn(fcx.lcx.ccx, id);
4588     bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, arg_tys);
4589
4590     maybe_load_env(fcx);
4591
4592     // This call to trans_block is the place where we bridge between
4593     // translation calls that don't have a return value (trans_crate,
4594     // trans_mod, trans_item, trans_obj, et cetera) and those that do
4595     // (trans_block, trans_expr, et cetera).
4596     if ty::type_is_bot(cx.ccx.tcx, block_ty) ||
4597        ty::type_is_nil(cx.ccx.tcx, block_ty) ||
4598        option::is_none(body.node.expr) {
4599         bcx = trans_block_dps(bcx, body, ignore);
4600     } else if ty::type_is_immediate(cx.ccx.tcx, block_ty) {
4601         let cell = empty_dest_cell();
4602         bcx = trans_block_dps(bcx, body, by_val(cell));
4603         Store(bcx, *cell, fcx.llretptr);
4604     } else {
4605         bcx = trans_block_dps(bcx, body, save_in(fcx.llretptr));
4606     }
4607
4608     // FIXME: until LLVM has a unit type, we are moving around
4609     // C_nil values rather than their void type.
4610     if !bcx.unreachable { build_return(bcx); }
4611     // Insert the mandatory first few basic blocks before lltop.
4612     finish_fn(fcx, lltop);
4613 }
4614
4615 // trans_fn: creates an LLVM function corresponding to a source language
4616 // function.
4617 fn trans_fn(cx: @local_ctxt, sp: span, decl: ast::fn_decl, body: ast::blk,
4618             llfndecl: ValueRef, ty_self: self_arg, ty_params: [ast::ty_param],
4619             id: ast::node_id) {
4620     let do_time = cx.ccx.sess.get_opts().stats;
4621     let start = do_time ? time::get_time() : {sec: 0u32, usec: 0u32};
4622     let fcx = option::none;
4623     trans_closure(cx, sp, decl, body, llfndecl, ty_self, ty_params, id,
4624                   {|new_fcx| fcx = option::some(new_fcx);});
4625     if cx.ccx.sess.get_opts().extra_debuginfo {
4626         debuginfo::create_function(option::get(fcx));
4627     }
4628     if do_time {
4629         let end = time::get_time();
4630         log_fn_time(cx.ccx, str::connect(cx.path, "::"), start, end);
4631     }
4632 }
4633
4634 fn trans_res_ctor(cx: @local_ctxt, sp: span, dtor: ast::fn_decl,
4635                   ctor_id: ast::node_id, ty_params: [ast::ty_param]) {
4636     let ccx = cx.ccx;
4637
4638     // Create a function for the constructor
4639     let llctor_decl;
4640     alt ccx.item_ids.find(ctor_id) {
4641       some(x) { llctor_decl = x; }
4642       _ { ccx.sess.span_fatal(sp, "unbound ctor_id in trans_res_ctor"); }
4643     }
4644     let fcx = new_fn_ctxt(cx, sp, llctor_decl);
4645     let ret_t = ty::ret_ty_of_fn(cx.ccx.tcx, ctor_id);
4646     create_llargs_for_fn_args(fcx, no_self, dtor.inputs, ty_params);
4647     let bcx = new_top_block_ctxt(fcx);
4648     let lltop = bcx.llbb;
4649     let arg_t = arg_tys_of_fn(ccx, ctor_id)[0].ty;
4650     let tup_t = ty::mk_tup(ccx.tcx, [ty::mk_int(ccx.tcx), arg_t]);
4651     let arg = alt fcx.llargs.find(dtor.inputs[0].id) {
4652       some(local_mem(x)) { x }
4653     };
4654     let llretptr = fcx.llretptr;
4655     if ty::type_has_dynamic_size(ccx.tcx, ret_t) {
4656         let llret_t = T_ptr(T_struct([ccx.int_type, llvm::LLVMTypeOf(arg)]));
4657         llretptr = BitCast(bcx, llretptr, llret_t);
4658     }
4659
4660     // FIXME: silly checks
4661     check type_is_tup_like(bcx, tup_t);
4662     let {bcx, val: dst} = GEP_tup_like(bcx, tup_t, llretptr, [0, 1]);
4663     bcx = memmove_ty(bcx, dst, arg, arg_t);
4664     check type_is_tup_like(bcx, tup_t);
4665     let flag = GEP_tup_like(bcx, tup_t, llretptr, [0, 0]);
4666     bcx = flag.bcx;
4667     // FIXME #1184: Resource flag is larger than necessary
4668     let one = C_int(ccx, 1);
4669     Store(bcx, one, flag.val);
4670     build_return(bcx);
4671     finish_fn(fcx, lltop);
4672 }
4673
4674
4675 fn trans_tag_variant(cx: @local_ctxt, tag_id: ast::node_id,
4676                      variant: ast::variant, index: int, is_degen: bool,
4677                      ty_params: [ast::ty_param]) {
4678     let ccx = cx.ccx;
4679
4680     if vec::len::<ast::variant_arg>(variant.node.args) == 0u {
4681         ret; // nullary constructors are just constants
4682
4683     }
4684     // Translate variant arguments to function arguments.
4685
4686     let fn_args: [ast::arg] = [];
4687     let i = 0u;
4688     for varg: ast::variant_arg in variant.node.args {
4689         fn_args +=
4690             [{mode: ast::by_copy,
4691               ty: varg.ty,
4692               ident: "arg" + uint::to_str(i, 10u),
4693               id: varg.id}];
4694     }
4695     assert (ccx.item_ids.contains_key(variant.node.id));
4696     let llfndecl: ValueRef;
4697     alt ccx.item_ids.find(variant.node.id) {
4698       some(x) { llfndecl = x; }
4699       _ {
4700         ccx.sess.span_fatal(variant.span,
4701                                "unbound variant id in trans_tag_variant");
4702       }
4703     }
4704     let fcx = new_fn_ctxt(cx, variant.span, llfndecl);
4705     create_llargs_for_fn_args(fcx, no_self, fn_args, ty_params);
4706     let ty_param_substs: [ty::t] = [];
4707     i = 0u;
4708     for tp: ast::ty_param in ty_params {
4709         ty_param_substs += [ty::mk_param(ccx.tcx, i,
4710                                          ast_util::local_def(tp.id))];
4711         i += 1u;
4712     }
4713     let arg_tys = arg_tys_of_fn(ccx, variant.node.id);
4714     let bcx = new_top_block_ctxt(fcx);
4715     let lltop = bcx.llbb;
4716     bcx = copy_args_to_allocas(fcx, bcx, fn_args, arg_tys);
4717
4718     // Cast the tag to a type we can GEP into.
4719     let llblobptr =
4720         if is_degen {
4721             fcx.llretptr
4722         } else {
4723             let lltagptr =
4724                 PointerCast(bcx, fcx.llretptr, T_opaque_tag_ptr(ccx));
4725             let lldiscrimptr = GEPi(bcx, lltagptr, [0, 0]);
4726             Store(bcx, C_int(ccx, index), lldiscrimptr);
4727             GEPi(bcx, lltagptr, [0, 1])
4728         };
4729     i = 0u;
4730     let t_id = ast_util::local_def(tag_id);
4731     let v_id = ast_util::local_def(variant.node.id);
4732     for va: ast::variant_arg in variant.node.args {
4733         check (valid_variant_index(i, bcx, t_id, v_id));
4734         let rslt = GEP_tag(bcx, llblobptr, t_id, v_id, ty_param_substs, i);
4735         bcx = rslt.bcx;
4736         let lldestptr = rslt.val;
4737         // If this argument to this function is a tag, it'll have come in to
4738         // this function as an opaque blob due to the way that type_of()
4739         // works. So we have to cast to the destination's view of the type.
4740         let llarg = alt fcx.llargs.find(va.id) { some(local_mem(x)) { x } };
4741         let arg_ty = arg_tys[i].ty;
4742         if ty::type_contains_params(bcx_tcx(bcx), arg_ty) {
4743             lldestptr = PointerCast(bcx, lldestptr, val_ty(llarg));
4744         }
4745         bcx = memmove_ty(bcx, lldestptr, llarg, arg_ty);
4746         i += 1u;
4747     }
4748     build_return(bcx);
4749     finish_fn(fcx, lltop);
4750 }
4751
4752
4753 // FIXME: this should do some structural hash-consing to avoid
4754 // duplicate constants. I think. Maybe LLVM has a magical mode
4755 // that does so later on?
4756 fn trans_const_expr(cx: @crate_ctxt, e: @ast::expr) -> ValueRef {
4757     alt e.node {
4758       ast::expr_lit(lit) { ret trans_crate_lit(cx, *lit); }
4759       ast::expr_binary(b, e1, e2) {
4760         let te1 = trans_const_expr(cx, e1);
4761         let te2 = trans_const_expr(cx, e2);
4762         /* Neither type is bottom, and we expect them to be unified already,
4763          * so the following is safe. */
4764         let ty = ty::expr_ty(ccx_tcx(cx), e1);
4765         let is_float = ty::type_is_fp(ccx_tcx(cx), ty);
4766         let signed = ty::type_is_signed(ccx_tcx(cx), ty);
4767         ret alt b {
4768           ast::add.    {
4769             if is_float { llvm::LLVMConstFAdd(te1, te2) }
4770             else        { llvm::LLVMConstAdd(te1, te2) }
4771           }
4772           ast::sub.    {
4773             if is_float { llvm::LLVMConstFSub(te1, te2) }
4774             else        { llvm::LLVMConstSub(te1, te2) }
4775           }
4776           ast::mul.    {
4777             if is_float { llvm::LLVMConstFMul(te1, te2) }
4778             else        { llvm::LLVMConstMul(te1, te2) }
4779           }
4780           ast::div.    {
4781             if is_float    { llvm::LLVMConstFDiv(te1, te2) }
4782             else if signed { llvm::LLVMConstSDiv(te1, te2) }
4783             else           { llvm::LLVMConstUDiv(te1, te2) }
4784           }
4785           ast::rem.    {
4786             if is_float    { llvm::LLVMConstFRem(te1, te2) }
4787             else if signed { llvm::LLVMConstSRem(te1, te2) }
4788             else           { llvm::LLVMConstURem(te1, te2) }
4789           }
4790           ast::and.    |
4791           ast::or.     { cx.sess.span_unimpl(e.span, "binop logic"); }
4792           ast::bitxor. { llvm::LLVMConstXor(te1, te2) }
4793           ast::bitand. { llvm::LLVMConstAnd(te1, te2) }
4794           ast::bitor.  { llvm::LLVMConstOr(te1, te2) }
4795           ast::lsl.    { llvm::LLVMConstShl(te1, te2) }
4796           ast::lsr.    { llvm::LLVMConstLShr(te1, te2) }
4797           ast::asr.    { llvm::LLVMConstAShr(te1, te2) }
4798           ast::eq.     |
4799           ast::lt.     |
4800           ast::le.     |
4801           ast::ne.     |
4802           ast::ge.     |
4803           ast::gt.     { cx.sess.span_unimpl(e.span, "binop comparator"); }
4804         }
4805       }
4806       ast::expr_unary(u, e) {
4807         let te = trans_const_expr(cx, e);
4808         let ty = ty::expr_ty(ccx_tcx(cx), e);
4809         let is_float = ty::type_is_fp(ccx_tcx(cx), ty);
4810         ret alt u {
4811           ast::box(_)  |
4812           ast::uniq(_) |
4813           ast::deref.  { cx.sess.span_bug(e.span,
4814                            "bad unop type in trans_const_expr"); }
4815           ast::not.    { llvm::LLVMConstNot(te) }
4816           ast::neg.    {
4817             if is_float { llvm::LLVMConstFNeg(te) }
4818             else        { llvm::LLVMConstNeg(te) }
4819           }
4820         }
4821       }
4822       _ { cx.sess.span_bug(e.span,
4823             "bad constant expression type in trans_const_expr"); }
4824     }
4825 }
4826
4827 fn trans_const(cx: @crate_ctxt, e: @ast::expr, id: ast::node_id) {
4828     let v = trans_const_expr(cx, e);
4829
4830     // The scalars come back as 1st class LLVM vals
4831     // which we have to stick into global constants.
4832
4833     alt cx.consts.find(id) {
4834       some(g) {
4835         llvm::LLVMSetInitializer(g, v);
4836         llvm::LLVMSetGlobalConstant(g, True);
4837       }
4838       _ { cx.sess.span_fatal(e.span, "Unbound const in trans_const"); }
4839     }
4840 }
4841
4842 type c_stack_tys = {
4843     arg_tys: [TypeRef],
4844     ret_ty: TypeRef,
4845     ret_def: bool,
4846     base_fn_ty: TypeRef,
4847     bundle_ty: TypeRef,
4848     shim_fn_ty: TypeRef
4849 };
4850
4851 fn c_stack_tys(ccx: @crate_ctxt,
4852                sp: span,
4853                id: ast::node_id) -> @c_stack_tys {
4854     alt ty::struct(ccx.tcx, ty::node_id_to_type(ccx.tcx, id)) {
4855       ty::ty_native_fn(arg_tys, ret_ty) {
4856         let tcx = ccx.tcx;
4857         let llargtys = type_of_explicit_args(ccx, sp, arg_tys);
4858         check non_ty_var(ccx, ret_ty); // NDM does this truly hold?
4859         let llretty = type_of_inner(ccx, sp, ret_ty);
4860         let bundle_ty = T_struct(llargtys + [T_ptr(llretty)]);
4861         ret @{
4862             arg_tys: llargtys,
4863             ret_ty: llretty,
4864             ret_def: !ty::type_is_bot(tcx, ret_ty) &&
4865                 !ty::type_is_nil(tcx, ret_ty),
4866             base_fn_ty: T_fn(llargtys, llretty),
4867             bundle_ty: bundle_ty,
4868             shim_fn_ty: T_fn([T_ptr(bundle_ty)], T_void())
4869         };
4870       }
4871
4872       _ {
4873         ccx.sess.span_fatal(
4874             sp,
4875             "Non-function type for native fn");
4876       }
4877     }
4878 }
4879
4880 // For each native function F, we generate a wrapper function W and a shim
4881 // function S that all work together.  The wrapper function W is the function
4882 // that other rust code actually invokes.  Its job is to marshall the
4883 // arguments into a struct.  It then uses a small bit of assembly to switch
4884 // over to the C stack and invoke the shim function.  The shim function S then
4885 // unpacks the arguments from the struct and invokes the actual function F
4886 // according to its specified calling convention.
4887 //
4888 // Example: Given a native c-stack function F(x: X, y: Y) -> Z,
4889 // we generate a wrapper function W that looks like:
4890 //
4891 //    void W(Z* dest, void *env, X x, Y y) {
4892 //        struct { X x; Y y; Z *z; } args = { x, y, z };
4893 //        call_on_c_stack_shim(S, &args);
4894 //    }
4895 //
4896 // The shim function S then looks something like:
4897 //
4898 //     void S(struct { X x; Y y; Z *z; } *args) {
4899 //         *args->z = F(args->x, args->y);
4900 //     }
4901 //
4902 // However, if the return type of F is dynamically sized or of aggregate type,
4903 // the shim function looks like:
4904 //
4905 //     void S(struct { X x; Y y; Z *z; } *args) {
4906 //         F(args->z, args->x, args->y);
4907 //     }
4908 //
4909 // Note: on i386, the layout of the args struct is generally the same as the
4910 // desired layout of the arguments on the C stack.  Therefore, we could use
4911 // upcall_alloc_c_stack() to allocate the `args` structure and switch the
4912 // stack pointer appropriately to avoid a round of copies.  (In fact, the shim
4913 // function itself is unnecessary). We used to do this, in fact, and will
4914 // perhaps do so in the future.
4915 fn trans_native_mod(lcx: @local_ctxt, native_mod: ast::native_mod,
4916                     abi: ast::native_abi) {
4917     fn build_shim_fn(lcx: @local_ctxt,
4918                      native_item: @ast::native_item,
4919                      tys: @c_stack_tys,
4920                      cc: uint) -> ValueRef {
4921         let lname = link_name(native_item);
4922         let ccx = lcx_ccx(lcx);
4923         let span = native_item.span;
4924
4925         // Declare the "prototype" for the base function F:
4926         let llbasefn = decl_fn(ccx.llmod, lname, cc, tys.base_fn_ty);
4927
4928         // Create the shim function:
4929         let shim_name = lname + "__c_stack_shim";
4930         let llshimfn = decl_internal_cdecl_fn(
4931             ccx.llmod, shim_name, tys.shim_fn_ty);
4932
4933         // Declare the body of the shim function:
4934         let fcx = new_fn_ctxt(lcx, span, llshimfn);
4935         let bcx = new_top_block_ctxt(fcx);
4936         let lltop = bcx.llbb;
4937         let llargbundle = llvm::LLVMGetParam(llshimfn, 0u);
4938         let i = 0u, n = vec::len(tys.arg_tys);
4939         let llargvals = [];
4940         while i < n {
4941             let llargval = load_inbounds(bcx, llargbundle, [0, i as int]);
4942             llargvals += [llargval];
4943             i += 1u;
4944         }
4945
4946         // Create the call itself and store the return value:
4947         let llretval = CallWithConv(bcx, llbasefn, llargvals, cc); // r
4948         if tys.ret_def {
4949             // R** llretptr = &args->r;
4950             let llretptr = GEPi(bcx, llargbundle, [0, n as int]);
4951             // R* llretloc = *llretptr; /* (args->r) */
4952             let llretloc = Load(bcx, llretptr);
4953             // *args->r = r;
4954             Store(bcx, llretval, llretloc);
4955         }
4956
4957         // Finish up:
4958         build_return(bcx);
4959         finish_fn(fcx, lltop);
4960
4961         ret llshimfn;
4962     }
4963
4964     fn build_wrap_fn(lcx: @local_ctxt,
4965                      native_item: @ast::native_item,
4966                      tys: @c_stack_tys,
4967                      num_tps: uint,
4968                      llshimfn: ValueRef,
4969                      llwrapfn: ValueRef) {
4970         let span = native_item.span;
4971         let ccx = lcx_ccx(lcx);
4972         let fcx = new_fn_ctxt(lcx, span, llwrapfn);
4973         let bcx = new_top_block_ctxt(fcx);
4974         let lltop = bcx.llbb;
4975
4976         // Allocate the struct and write the arguments into it.
4977         let llargbundle = alloca(bcx, tys.bundle_ty);
4978         let i = 0u, n = vec::len(tys.arg_tys);
4979         let implicit_args = 2u + num_tps; // ret + env
4980         while i < n {
4981             let llargval = llvm::LLVMGetParam(llwrapfn, i + implicit_args);
4982             store_inbounds(bcx, llargval, llargbundle, [0, i as int]);
4983             i += 1u;
4984         }
4985         let llretptr = llvm::LLVMGetParam(llwrapfn, 0u);
4986         store_inbounds(bcx, llretptr, llargbundle, [0, n as int]);
4987
4988         // Create call itself.
4989         let call_shim_on_c_stack = ccx.upcalls.call_shim_on_c_stack;
4990         let llshimfnptr = PointerCast(bcx, llshimfn, T_ptr(T_i8()));
4991         let llrawargbundle = PointerCast(bcx, llargbundle, T_ptr(T_i8()));
4992         Call(bcx, call_shim_on_c_stack, [llrawargbundle, llshimfnptr]);
4993         build_return(bcx);
4994         finish_fn(fcx, lltop);
4995     }
4996
4997     let ccx = lcx_ccx(lcx);
4998     let cc: uint = lib::llvm::LLVMCCallConv;
4999     alt abi {
5000       ast::native_abi_rust_intrinsic. { ret; }
5001       ast::native_abi_cdecl. { cc = lib::llvm::LLVMCCallConv; }
5002       ast::native_abi_stdcall. { cc = lib::llvm::LLVMX86StdcallCallConv; }
5003     }
5004
5005     for native_item in native_mod.items {
5006       alt native_item.node {
5007         ast::native_item_ty. {}
5008         ast::native_item_fn(fn_decl, tps) {
5009           let span = native_item.span;
5010           let id = native_item.id;
5011           let tys = c_stack_tys(ccx, span, id);
5012           alt ccx.item_ids.find(id) {
5013             some(llwrapfn) {
5014               let llshimfn = build_shim_fn(lcx, native_item, tys, cc);
5015               build_wrap_fn(lcx, native_item, tys,
5016                             vec::len(tps), llshimfn, llwrapfn);
5017             }
5018
5019             none. {
5020               ccx.sess.span_fatal(
5021                   native_item.span,
5022                   "unbound function item in trans_native_mod");
5023             }
5024           }
5025         }
5026       }
5027     }
5028 }
5029
5030 fn trans_item(cx: @local_ctxt, item: ast::item) {
5031     alt item.node {
5032       ast::item_fn(decl, tps, body) {
5033         let sub_cx = extend_path(cx, item.ident);
5034         alt cx.ccx.item_ids.find(item.id) {
5035           some(llfndecl) {
5036             trans_fn(sub_cx, item.span, decl, body, llfndecl, no_self, tps,
5037                      item.id);
5038           }
5039           _ {
5040             cx.ccx.sess.span_fatal(item.span,
5041                                    "unbound function item in trans_item");
5042           }
5043         }
5044       }
5045       ast::item_obj(ob, tps, ctor_id) {
5046         let sub_cx =
5047             @{obj_typarams: tps, obj_fields: ob.fields
5048                  with *extend_path(cx, item.ident)};
5049         trans_obj(sub_cx, item.span, ob, ctor_id, tps);
5050       }
5051       ast::item_impl(tps, _, _, ms) {
5052         trans_impl::trans_impl(cx, item.ident, ms, item.id, tps);
5053       }
5054       ast::item_res(decl, tps, body, dtor_id, ctor_id) {
5055         trans_res_ctor(cx, item.span, decl, ctor_id, tps);
5056
5057         // Create a function for the destructor
5058         alt cx.ccx.item_ids.find(item.id) {
5059           some(lldtor_decl) {
5060             trans_fn(cx, item.span, decl, body, lldtor_decl, no_self,
5061                      tps, dtor_id);
5062           }
5063           _ {
5064             cx.ccx.sess.span_fatal(item.span, "unbound dtor in trans_item");
5065           }
5066         }
5067       }
5068       ast::item_mod(m) {
5069         let sub_cx =
5070             @{path: cx.path + [item.ident],
5071               module_path: cx.module_path + [item.ident] with *cx};
5072         trans_mod(sub_cx, m);
5073       }
5074       ast::item_tag(variants, tps) {
5075         let sub_cx = extend_path(cx, item.ident);
5076         let degen = vec::len(variants) == 1u;
5077         let i = 0;
5078         for variant: ast::variant in variants {
5079             trans_tag_variant(sub_cx, item.id, variant, i, degen, tps);
5080             i += 1;
5081         }
5082       }
5083       ast::item_const(_, expr) { trans_const(cx.ccx, expr, item.id); }
5084       ast::item_native_mod(native_mod) {
5085         let abi = alt attr::native_abi(item.attrs) {
5086           either::right(abi_) { abi_ }
5087           either::left(msg) { cx.ccx.sess.span_fatal(item.span, msg) }
5088         };
5089         trans_native_mod(cx, native_mod, abi);
5090       }
5091       _ {/* fall through */ }
5092     }
5093 }
5094
5095 // Translate a module.  Doing this amounts to translating the items in the
5096 // module; there ends up being no artifact (aside from linkage names) of
5097 // separate modules in the compiled program.  That's because modules exist
5098 // only as a convenience for humans working with the code, to organize names
5099 // and control visibility.
5100 fn trans_mod(cx: @local_ctxt, m: ast::_mod) {
5101     for item: @ast::item in m.items { trans_item(cx, *item); }
5102 }
5103
5104 fn get_pair_fn_ty(llpairty: TypeRef) -> TypeRef {
5105     // Bit of a kludge: pick the fn typeref out of the pair.
5106
5107     ret struct_elt(llpairty, 0u);
5108 }
5109
5110 fn register_fn(ccx: @crate_ctxt, sp: span, path: [str], flav: str,
5111                ty_params: [ast::ty_param], node_id: ast::node_id) {
5112     // FIXME: pull this out
5113     let t = node_id_type(ccx, node_id);
5114     check returns_non_ty_var(ccx, t);
5115     register_fn_full(ccx, sp, path, flav, ty_params, node_id, t);
5116 }
5117
5118 fn param_bounds(ccx: @crate_ctxt, tp: ast::ty_param) -> ty::param_bounds {
5119     ccx.tcx.ty_param_bounds.get(tp.id)
5120 }
5121
5122 fn register_fn_full(ccx: @crate_ctxt, sp: span, path: [str], _flav: str,
5123                     tps: [ast::ty_param], node_id: ast::node_id,
5124                     node_type: ty::t)
5125     : returns_non_ty_var(ccx, node_type) {
5126     let path = path;
5127     let llfty = type_of_fn_from_ty(ccx, sp, node_type,
5128                                    vec::map(tps, {|p| param_bounds(ccx, p)}));
5129     let ps: str = mangle_exported_name(ccx, path, node_type);
5130     let llfn: ValueRef = decl_cdecl_fn(ccx.llmod, ps, llfty);
5131     ccx.item_ids.insert(node_id, llfn);
5132     ccx.item_symbols.insert(node_id, ps);
5133
5134     let is_main: bool = is_main_name(path) && !ccx.sess.building_library();
5135     if is_main { create_main_wrapper(ccx, sp, llfn, node_type); }
5136 }
5137
5138 // Create a _rust_main(args: [str]) function which will be called from the
5139 // runtime rust_start function
5140 fn create_main_wrapper(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,
5141                        main_node_type: ty::t) {
5142
5143     if ccx.main_fn != none::<ValueRef> {
5144         ccx.sess.span_fatal(sp, "multiple 'main' functions");
5145     }
5146
5147     let main_takes_argv =
5148         alt ty::struct(ccx.tcx, main_node_type) {
5149           ty::ty_fn({inputs, _}) { vec::len(inputs) != 0u }
5150         };
5151
5152     let llfn = create_main(ccx, sp, main_llfn, main_takes_argv);
5153     ccx.main_fn = some(llfn);
5154     create_entry_fn(ccx, llfn);
5155
5156     fn create_main(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,
5157                    takes_argv: bool) -> ValueRef {
5158         let unit_ty = ty::mk_str(ccx.tcx);
5159         let vecarg_ty: ty::arg =
5160             {mode: ast::by_val,
5161              ty: ty::mk_vec(ccx.tcx, {ty: unit_ty, mut: ast::imm})};
5162         // FIXME: mk_nil should have a postcondition
5163         let nt = ty::mk_nil(ccx.tcx);
5164         let llfty = type_of_fn(ccx, sp, false, [vecarg_ty], nt, []);
5165         let llfdecl = decl_fn(ccx.llmod, "_rust_main",
5166                               lib::llvm::LLVMCCallConv, llfty);
5167
5168         let fcx = new_fn_ctxt(new_local_ctxt(ccx), sp, llfdecl);
5169
5170         let bcx = new_top_block_ctxt(fcx);
5171         let lltop = bcx.llbb;
5172
5173         let lloutputarg = llvm::LLVMGetParam(llfdecl, 0u);
5174         let llenvarg = llvm::LLVMGetParam(llfdecl, 1u);
5175         let args = [lloutputarg, llenvarg];
5176         if takes_argv { args += [llvm::LLVMGetParam(llfdecl, 2u)]; }
5177         Call(bcx, main_llfn, args);
5178         build_return(bcx);
5179
5180         finish_fn(fcx, lltop);
5181
5182         ret llfdecl;
5183     }
5184
5185     fn create_entry_fn(ccx: @crate_ctxt, rust_main: ValueRef) {
5186         #[cfg(target_os = "win32")]
5187         fn main_name() -> str { ret "WinMain@16"; }
5188         #[cfg(target_os = "macos")]
5189         fn main_name() -> str { ret "main"; }
5190         #[cfg(target_os = "linux")]
5191         fn main_name() -> str { ret "main"; }
5192         #[cfg(target_os = "freebsd")]
5193         fn main_name() -> str { ret "main"; }
5194         let llfty = T_fn([ccx.int_type, ccx.int_type], ccx.int_type);
5195         let llfn = decl_cdecl_fn(ccx.llmod, main_name(), llfty);
5196         let llbb = str::as_buf("top", {|buf|
5197             llvm::LLVMAppendBasicBlock(llfn, buf)
5198         });
5199         let bld = *ccx.builder;
5200         llvm::LLVMPositionBuilderAtEnd(bld, llbb);
5201         let crate_map = ccx.crate_map;
5202         let start_ty = T_fn([val_ty(rust_main), ccx.int_type, ccx.int_type,
5203                              val_ty(crate_map)], ccx.int_type);
5204         let start = str::as_buf("rust_start", {|buf|
5205             llvm::LLVMAddGlobal(ccx.llmod, start_ty, buf)
5206         });
5207         let args = [rust_main, llvm::LLVMGetParam(llfn, 0u),
5208                     llvm::LLVMGetParam(llfn, 1u), crate_map];
5209         let result = unsafe {
5210             llvm::LLVMBuildCall(bld, start, vec::to_ptr(args),
5211                                 vec::len(args), noname())
5212         };
5213         llvm::LLVMBuildRet(bld, result);
5214     }
5215 }
5216
5217 // Create a /real/ closure: this is like create_fn_pair, but creates a
5218 // a fn value on the stack with a specified environment (which need not be
5219 // on the stack).
5220 fn create_real_fn_pair(cx: @block_ctxt, llfnty: TypeRef, llfn: ValueRef,
5221                        llenvptr: ValueRef) -> ValueRef {
5222     let lcx = cx.fcx.lcx;
5223
5224     let pair = alloca(cx, T_fn_pair(lcx.ccx, llfnty));
5225     fill_fn_pair(cx, pair, llfn, llenvptr);
5226     ret pair;
5227 }
5228
5229 fn fill_fn_pair(bcx: @block_ctxt, pair: ValueRef, llfn: ValueRef,
5230                 llenvptr: ValueRef) {
5231     let ccx = bcx_ccx(bcx);
5232     let code_cell = GEPi(bcx, pair, [0, abi::fn_field_code]);
5233     Store(bcx, llfn, code_cell);
5234     let env_cell = GEPi(bcx, pair, [0, abi::fn_field_box]);
5235     let llenvblobptr =
5236         PointerCast(bcx, llenvptr, T_opaque_boxed_closure_ptr(ccx));
5237     Store(bcx, llenvblobptr, env_cell);
5238 }
5239
5240 // Returns the number of type parameters that the given native function has.
5241 fn native_fn_ty_param_count(cx: @crate_ctxt, id: ast::node_id) -> uint {
5242     let count;
5243     let native_item =
5244         alt cx.ast_map.find(id) { some(ast_map::node_native_item(i)) { i } };
5245     alt native_item.node {
5246       ast::native_item_ty. {
5247         cx.sess.bug("register_native_fn(): native fn isn't \
5248                         actually a fn");
5249       }
5250       ast::native_item_fn(_, tps) {
5251         count = vec::len::<ast::ty_param>(tps);
5252       }
5253     }
5254     ret count;
5255 }
5256
5257 fn native_fn_wrapper_type(cx: @crate_ctxt, sp: span,
5258                           param_bounds: [ty::param_bounds],
5259                           x: ty::t) -> TypeRef {
5260     alt ty::struct(cx.tcx, x) {
5261       ty::ty_native_fn(args, out) {
5262         ret type_of_fn(cx, sp, false, args, out, param_bounds);
5263       }
5264     }
5265 }
5266
5267 fn raw_native_fn_type(ccx: @crate_ctxt, sp: span, args: [ty::arg],
5268                       ret_ty: ty::t) -> TypeRef {
5269     check type_has_static_size(ccx, ret_ty);
5270     ret T_fn(type_of_explicit_args(ccx, sp, args), type_of(ccx, sp, ret_ty));
5271 }
5272
5273 fn link_name(i: @ast::native_item) -> str {
5274     alt attr::get_meta_item_value_str_by_name(i.attrs, "link_name") {
5275       none. { ret i.ident; }
5276       option::some(ln) { ret ln; }
5277     }
5278 }
5279
5280 fn collect_native_item(ccx: @crate_ctxt,
5281                        abi: @mutable option::t<ast::native_abi>,
5282                        i: @ast::native_item,
5283                        &&pt: [str],
5284                        _v: vt<[str]>) {
5285     alt i.node {
5286       ast::native_item_fn(_, tps) {
5287         let sp = i.span;
5288         let id = i.id;
5289         let node_type = node_id_type(ccx, id);
5290         let fn_abi =
5291             alt attr::get_meta_item_value_str_by_name(i.attrs, "abi") {
5292             option::none. {
5293                 // if abi isn't specified for this function, inherit from
5294                   // its enclosing native module
5295                   option::get(*abi)
5296               }
5297                 _ {
5298                     alt attr::native_abi(i.attrs) {
5299                       either::right(abi_) { abi_ }
5300                       either::left(msg) { ccx.sess.span_fatal(i.span, msg) }
5301                     }
5302                 }
5303             };
5304         alt fn_abi {
5305           ast::native_abi_rust_intrinsic. {
5306             // For intrinsics: link the function directly to the intrinsic
5307             // function itself.
5308             let fn_type = type_of_fn_from_ty(
5309                 ccx, sp, node_type,
5310                 vec::map(tps, {|p| param_bounds(ccx, p)}));
5311             let ri_name = "rust_intrinsic_" + link_name(i);
5312             let llnativefn = get_extern_fn(
5313                 ccx.externs, ccx.llmod, ri_name,
5314                 lib::llvm::LLVMCCallConv, fn_type);
5315             ccx.item_ids.insert(id, llnativefn);
5316             ccx.item_symbols.insert(id, ri_name);
5317           }
5318
5319           ast::native_abi_cdecl. | ast::native_abi_stdcall. {
5320             // For true external functions: create a rust wrapper
5321             // and link to that.  The rust wrapper will handle
5322             // switching to the C stack.
5323             let new_pt = pt + [i.ident];
5324             register_fn(ccx, i.span, new_pt, "native fn", tps, i.id);
5325           }
5326         }
5327       }
5328       _ { }
5329     }
5330 }
5331
5332 fn collect_item(ccx: @crate_ctxt, abi: @mutable option::t<ast::native_abi>,
5333                 i: @ast::item, &&pt: [str], v: vt<[str]>) {
5334     let new_pt = pt + [i.ident];
5335     alt i.node {
5336       ast::item_const(_, _) {
5337         let typ = node_id_type(ccx, i.id);
5338         let s =
5339             mangle_exported_name(ccx, pt + [i.ident],
5340                                  node_id_type(ccx, i.id));
5341         // FIXME: Could follow from a constraint on types of const
5342         // items
5343         let g = str::as_buf(s, {|buf|
5344             check (type_has_static_size(ccx, typ));
5345             llvm::LLVMAddGlobal(ccx.llmod, type_of(ccx, i.span, typ), buf)
5346         });
5347         ccx.item_symbols.insert(i.id, s);
5348         ccx.consts.insert(i.id, g);
5349       }
5350       ast::item_native_mod(native_mod) {
5351         // Propagate the native ABI down to collect_native_item(),
5352         alt attr::native_abi(i.attrs) {
5353           either::left(msg) { ccx.sess.span_fatal(i.span, msg); }
5354           either::right(abi_) {
5355             *abi = option::some(abi_);
5356           }
5357         }
5358       }
5359       ast::item_fn(_, tps, _) {
5360         register_fn(ccx, i.span, new_pt, "fn", tps, i.id);
5361       }
5362       ast::item_obj(ob, tps, ctor_id) {
5363         register_fn(ccx, i.span, new_pt, "obj_ctor", tps, ctor_id);
5364       }
5365       ast::item_impl(tps, _, _, methods) {
5366         let name = i.ident + int::str(i.id);
5367         for m in methods {
5368             register_fn(ccx, i.span, pt + [name, m.ident],
5369                         "impl_method", tps + m.tps, m.id);
5370         }
5371       }
5372       ast::item_res(_, tps, _, dtor_id, ctor_id) {
5373         register_fn(ccx, i.span, new_pt, "res_ctor", tps, ctor_id);
5374         // Note that the destructor is associated with the item's id, not
5375         // the dtor_id. This is a bit counter-intuitive, but simplifies
5376         // ty_res, which would have to carry around two def_ids otherwise
5377         // -- one to identify the type, and one to find the dtor symbol.
5378         let t = node_id_type(ccx, dtor_id);
5379         // FIXME: how to get rid of this check?
5380         check returns_non_ty_var(ccx, t);
5381         register_fn_full(ccx, i.span, new_pt, "res_dtor", tps, i.id, t);
5382       }
5383       ast::item_tag(variants, tps) {
5384         for variant in variants {
5385             if vec::len(variant.node.args) != 0u {
5386                 register_fn(ccx, i.span, new_pt + [variant.node.name],
5387                             "tag", tps, variant.node.id);
5388             }
5389         }
5390       }
5391       _ { }
5392     }
5393     visit::visit_item(i, new_pt, v);
5394 }
5395
5396 fn collect_items(ccx: @crate_ctxt, crate: @ast::crate) {
5397     let abi = @mutable none::<ast::native_abi>;
5398     visit::visit_crate(*crate, [], visit::mk_vt(@{
5399         visit_native_item: bind collect_native_item(ccx, abi, _, _, _),
5400         visit_item: bind collect_item(ccx, abi, _, _, _)
5401         with *visit::default_visitor()
5402     }));
5403 }
5404
5405 // The constant translation pass.
5406 fn trans_constant(ccx: @crate_ctxt, it: @ast::item, &&pt: [str],
5407                   v: vt<[str]>) {
5408     let new_pt = pt + [it.ident];
5409     visit::visit_item(it, new_pt, v);
5410     alt it.node {
5411       ast::item_tag(variants, _) {
5412         let i = 0u;
5413         for variant in variants {
5414             let p = new_pt + [variant.node.name, "discrim"];
5415             let s = mangle_exported_name(ccx, p, ty::mk_int(ccx.tcx));
5416             let discrim_gvar = str::as_buf(s, {|buf|
5417                 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
5418             });
5419             llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, i as int));
5420             llvm::LLVMSetGlobalConstant(discrim_gvar, True);
5421             ccx.discrims.insert(
5422                 ast_util::local_def(variant.node.id), discrim_gvar);
5423             ccx.discrim_symbols.insert(variant.node.id, s);
5424             i += 1u;
5425         }
5426       }
5427       ast::item_impl(tps, some(@{node: ast::ty_path(_, id), _}), _, ms) {
5428         let i_did = ast_util::def_id_of_def(ccx.tcx.def_map.get(id));
5429         let ty = ty::lookup_item_type(ccx.tcx, i_did).ty;
5430         let new_pt = pt + [it.ident + int::str(it.id), "wrap"];
5431         let extra_tps = vec::map(tps, {|p| param_bounds(ccx, p)});
5432         let tbl = C_struct(vec::map(*ty::iface_methods(ccx.tcx, i_did), {|im|
5433             alt vec::find(ms, {|m| m.ident == im.ident}) {
5434               some(m) {
5435                 trans_impl::trans_wrapper(ccx, new_pt, extra_tps, m)
5436               }
5437             }
5438         }));
5439         let s = mangle_exported_name(ccx, new_pt + ["!vtable"], ty);
5440         let vt_gvar = str::as_buf(s, {|buf|
5441             llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf)
5442         });
5443         llvm::LLVMSetInitializer(vt_gvar, tbl);
5444         llvm::LLVMSetGlobalConstant(vt_gvar, True);
5445         ccx.item_ids.insert(it.id, vt_gvar);
5446         ccx.item_symbols.insert(it.id, s);
5447       }
5448       _ { }
5449     }
5450 }
5451
5452 fn trans_constants(ccx: @crate_ctxt, crate: @ast::crate) {
5453     let visitor =
5454         @{visit_item: bind trans_constant(ccx, _, _, _)
5455              with *visit::default_visitor()};
5456     visit::visit_crate(*crate, [], visit::mk_vt(visitor));
5457 }
5458
5459 fn vp2i(cx: @block_ctxt, v: ValueRef) -> ValueRef {
5460     let ccx = bcx_ccx(cx);
5461     ret PtrToInt(cx, v, ccx.int_type);
5462 }
5463
5464 fn p2i(ccx: @crate_ctxt, v: ValueRef) -> ValueRef {
5465     ret llvm::LLVMConstPtrToInt(v, ccx.int_type);
5466 }
5467
5468 fn declare_intrinsics(llmod: ModuleRef) -> hashmap<str, ValueRef> {
5469     let T_memmove32_args: [TypeRef] =
5470         [T_ptr(T_i8()), T_ptr(T_i8()), T_i32(), T_i32(), T_i1()];
5471     let T_memmove64_args: [TypeRef] =
5472         [T_ptr(T_i8()), T_ptr(T_i8()), T_i64(), T_i32(), T_i1()];
5473     let T_memset32_args: [TypeRef] =
5474         [T_ptr(T_i8()), T_i8(), T_i32(), T_i32(), T_i1()];
5475     let T_memset64_args: [TypeRef] =
5476         [T_ptr(T_i8()), T_i8(), T_i64(), T_i32(), T_i1()];
5477     let T_trap_args: [TypeRef] = [];
5478     let gcroot =
5479         decl_cdecl_fn(llmod, "llvm.gcroot",
5480                       T_fn([T_ptr(T_ptr(T_i8())), T_ptr(T_i8())], T_void()));
5481     let gcread =
5482         decl_cdecl_fn(llmod, "llvm.gcread",
5483                       T_fn([T_ptr(T_i8()), T_ptr(T_ptr(T_i8()))], T_void()));
5484     let memmove32 =
5485         decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i32",
5486                       T_fn(T_memmove32_args, T_void()));
5487     let memmove64 =
5488         decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i64",
5489                       T_fn(T_memmove64_args, T_void()));
5490     let memset32 =
5491         decl_cdecl_fn(llmod, "llvm.memset.p0i8.i32",
5492                       T_fn(T_memset32_args, T_void()));
5493     let memset64 =
5494         decl_cdecl_fn(llmod, "llvm.memset.p0i8.i64",
5495                       T_fn(T_memset64_args, T_void()));
5496     let trap = decl_cdecl_fn(llmod, "llvm.trap", T_fn(T_trap_args, T_void()));
5497     let intrinsics = new_str_hash::<ValueRef>();
5498     intrinsics.insert("llvm.gcroot", gcroot);
5499     intrinsics.insert("llvm.gcread", gcread);
5500     intrinsics.insert("llvm.memmove.p0i8.p0i8.i32", memmove32);
5501     intrinsics.insert("llvm.memmove.p0i8.p0i8.i64", memmove64);
5502     intrinsics.insert("llvm.memset.p0i8.i32", memset32);
5503     intrinsics.insert("llvm.memset.p0i8.i64", memset64);
5504     intrinsics.insert("llvm.trap", trap);
5505     ret intrinsics;
5506 }
5507
5508 fn declare_dbg_intrinsics(llmod: ModuleRef,
5509                           intrinsics: hashmap<str, ValueRef>) {
5510     let declare =
5511         decl_cdecl_fn(llmod, "llvm.dbg.declare",
5512                       T_fn([T_metadata(), T_metadata()], T_void()));
5513     let value =
5514         decl_cdecl_fn(llmod, "llvm.dbg.value",
5515                       T_fn([T_metadata(), T_i64(), T_metadata()], T_void()));
5516     intrinsics.insert("llvm.dbg.declare", declare);
5517     intrinsics.insert("llvm.dbg.value", value);
5518 }
5519
5520 fn trap(bcx: @block_ctxt) {
5521     let v: [ValueRef] = [];
5522     alt bcx_ccx(bcx).intrinsics.find("llvm.trap") {
5523       some(x) { Call(bcx, x, v); }
5524       _ { bcx_ccx(bcx).sess.bug("unbound llvm.trap in trap"); }
5525     }
5526 }
5527
5528 fn create_module_map(ccx: @crate_ctxt) -> ValueRef {
5529     let elttype = T_struct([ccx.int_type, ccx.int_type]);
5530     let maptype = T_array(elttype, ccx.module_data.size() + 1u);
5531     let map =
5532         str::as_buf("_rust_mod_map",
5533                     {|buf| llvm::LLVMAddGlobal(ccx.llmod, maptype, buf) });
5534     llvm::LLVMSetLinkage(map,
5535                          lib::llvm::LLVMInternalLinkage as llvm::Linkage);
5536     let elts: [ValueRef] = [];
5537     ccx.module_data.items {|key, val|
5538         let elt = C_struct([p2i(ccx, C_cstr(ccx, key)),
5539                             p2i(ccx, val)]);
5540         elts += [elt];
5541     };
5542     let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
5543     elts += [term];
5544     llvm::LLVMSetInitializer(map, C_array(elttype, elts));
5545     ret map;
5546 }
5547
5548
5549 fn decl_crate_map(sess: session::session, mapname: str,
5550                   llmod: ModuleRef) -> ValueRef {
5551     let targ_cfg = sess.get_targ_cfg();
5552     let int_type = T_int(targ_cfg);
5553     let n_subcrates = 1;
5554     let cstore = sess.get_cstore();
5555     while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
5556     let mapname = sess.building_library() ? mapname : "toplevel";
5557     let sym_name = "_rust_crate_map_" + mapname;
5558     let arrtype = T_array(int_type, n_subcrates as uint);
5559     let maptype = T_struct([int_type, arrtype]);
5560     let map = str::as_buf(sym_name, {|buf|
5561         llvm::LLVMAddGlobal(llmod, maptype, buf)
5562     });
5563     llvm::LLVMSetLinkage(map, lib::llvm::LLVMExternalLinkage
5564                          as llvm::Linkage);
5565     ret map;
5566 }
5567
5568 // FIXME use hashed metadata instead of crate names once we have that
5569 fn fill_crate_map(ccx: @crate_ctxt, map: ValueRef) {
5570     let subcrates: [ValueRef] = [];
5571     let i = 1;
5572     let cstore = ccx.sess.get_cstore();
5573     while cstore::have_crate_data(cstore, i) {
5574         let nm = "_rust_crate_map_" + cstore::get_crate_data(cstore, i).name;
5575         let cr = str::as_buf(nm, {|buf|
5576             llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
5577         });
5578         subcrates += [p2i(ccx, cr)];
5579         i += 1;
5580     }
5581     subcrates += [C_int(ccx, 0)];
5582     llvm::LLVMSetInitializer(map, C_struct(
5583         [p2i(ccx, create_module_map(ccx)),
5584          C_array(ccx.int_type, subcrates)]));
5585 }
5586
5587 fn write_metadata(cx: @crate_ctxt, crate: @ast::crate) {
5588     if !cx.sess.building_library() { ret; }
5589     let llmeta = C_postr(metadata::encoder::encode_metadata(cx, crate));
5590     let llconst = trans_common::C_struct([llmeta]);
5591     let llglobal =
5592         str::as_buf("rust_metadata",
5593                     {|buf|
5594                         llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst), buf)
5595                     });
5596     llvm::LLVMSetInitializer(llglobal, llconst);
5597     let _: () =
5598         str::as_buf(cx.sess.get_targ_cfg().target_strs.meta_sect_name,
5599                     {|buf| llvm::LLVMSetSection(llglobal, buf) });
5600     llvm::LLVMSetLinkage(llglobal,
5601                          lib::llvm::LLVMInternalLinkage as llvm::Linkage);
5602
5603     let t_ptr_i8 = T_ptr(T_i8());
5604     llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8);
5605     let llvm_used =
5606         str::as_buf("llvm.used",
5607                     {|buf|
5608                         llvm::LLVMAddGlobal(cx.llmod, T_array(t_ptr_i8, 1u),
5609                                             buf)
5610                     });
5611     llvm::LLVMSetLinkage(llvm_used,
5612                          lib::llvm::LLVMAppendingLinkage as llvm::Linkage);
5613     llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
5614 }
5615
5616 // Writes the current ABI version into the crate.
5617 fn write_abi_version(ccx: @crate_ctxt) {
5618     shape::mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version),
5619                      false);
5620 }
5621
5622 fn trans_crate(sess: session::session, crate: @ast::crate, tcx: ty::ctxt,
5623                output: str, emap: resolve::exp_map, amap: ast_map::map,
5624                mut_map: mut::mut_map, copy_map: alias::copy_map,
5625                last_uses: last_use::last_uses, method_map: typeck::method_map,
5626                dict_map: typeck::dict_map)
5627     -> (ModuleRef, link::link_meta) {
5628     let sha = std::sha1::mk_sha1();
5629     let link_meta = link::build_link_meta(sess, *crate, output, sha);
5630
5631     // Append ".rc" to crate name as LLVM module identifier.
5632     //
5633     // LLVM code generator emits a ".file filename" directive
5634     // for ELF backends. Value of the "filename" is set as the
5635     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
5636     // crashes if the module identifer is same as other symbols
5637     // such as a function name in the module.
5638     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
5639     let llmod_id = link_meta.name + ".rc";
5640
5641     let llmod = str::as_buf(llmod_id, {|buf|
5642         llvm::LLVMModuleCreateWithNameInContext
5643             (buf, llvm::LLVMGetGlobalContext())
5644     });
5645     let data_layout = sess.get_targ_cfg().target_strs.data_layout;
5646     let targ_triple = sess.get_targ_cfg().target_strs.target_triple;
5647     let _: () =
5648         str::as_buf(data_layout,
5649                     {|buf| llvm::LLVMSetDataLayout(llmod, buf) });
5650     let _: () =
5651         str::as_buf(targ_triple,
5652                     {|buf| llvm::LLVMSetTarget(llmod, buf) });
5653     let targ_cfg = sess.get_targ_cfg();
5654     let td = mk_target_data(sess.get_targ_cfg().target_strs.data_layout);
5655     let tn = mk_type_names();
5656     let intrinsics = declare_intrinsics(llmod);
5657     if sess.get_opts().extra_debuginfo {
5658         declare_dbg_intrinsics(llmod, intrinsics);
5659     }
5660     let int_type = T_int(targ_cfg);
5661     let float_type = T_float(targ_cfg);
5662     let task_type = T_task(targ_cfg);
5663     let taskptr_type = T_ptr(task_type);
5664     tn.associate("taskptr", taskptr_type);
5665     let tydesc_type = T_tydesc(targ_cfg);
5666     tn.associate("tydesc", tydesc_type);
5667     let crate_map = decl_crate_map(sess, link_meta.name, llmod);
5668     let dbg_cx = if sess.get_opts().debuginfo {
5669         option::some(@{llmetadata: map::new_int_hash(),
5670                        names: namegen(0)})
5671     } else {
5672         option::none
5673     };
5674     let ccx =
5675         @{sess: sess,
5676           llmod: llmod,
5677           td: td,
5678           tn: tn,
5679           externs: new_str_hash::<ValueRef>(),
5680           intrinsics: intrinsics,
5681           item_ids: new_int_hash::<ValueRef>(),
5682           ast_map: amap,
5683           exp_map: emap,
5684           item_symbols: new_int_hash::<str>(),
5685           mutable main_fn: none::<ValueRef>,
5686           link_meta: link_meta,
5687           tag_sizes: ty::new_ty_hash(),
5688           discrims: ast_util::new_def_id_hash::<ValueRef>(),
5689           discrim_symbols: new_int_hash::<str>(),
5690           consts: new_int_hash::<ValueRef>(),
5691           tydescs: ty::new_ty_hash(),
5692           module_data: new_str_hash::<ValueRef>(),
5693           lltypes: ty::new_ty_hash(),
5694           names: namegen(0),
5695           sha: sha,
5696           type_sha1s: ty::new_ty_hash(),
5697           type_short_names: ty::new_ty_hash(),
5698           tcx: tcx,
5699           mut_map: mut_map,
5700           copy_map: copy_map,
5701           last_uses: last_uses,
5702           method_map: method_map,
5703           dict_map: dict_map,
5704           stats:
5705               {mutable n_static_tydescs: 0u,
5706                mutable n_derived_tydescs: 0u,
5707                mutable n_glues_created: 0u,
5708                mutable n_null_glues: 0u,
5709                mutable n_real_glues: 0u,
5710                fn_times: @mutable []},
5711           upcalls:
5712               upcall::declare_upcalls(targ_cfg, tn, tydesc_type,
5713                                       llmod),
5714           rust_object_type: T_rust_object(),
5715           tydesc_type: tydesc_type,
5716           int_type: int_type,
5717           float_type: float_type,
5718           task_type: task_type,
5719           opaque_vec_type: T_opaque_vec(targ_cfg),
5720           builder: BuilderRef_res(llvm::LLVMCreateBuilder()),
5721           shape_cx: shape::mk_ctxt(llmod),
5722           gc_cx: gc::mk_ctxt(),
5723           crate_map: crate_map,
5724           dbg_cx: dbg_cx};
5725     let cx = new_local_ctxt(ccx);
5726     collect_items(ccx, crate);
5727     trans_constants(ccx, crate);
5728     trans_mod(cx, crate.node.module);
5729     fill_crate_map(ccx, crate_map);
5730     emit_tydescs(ccx);
5731     shape::gen_shape_tables(ccx);
5732     write_abi_version(ccx);
5733
5734     // Translate the metadata.
5735     write_metadata(cx.ccx, crate);
5736     if ccx.sess.get_opts().stats {
5737         #error("--- trans stats ---");
5738         #error("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
5739         #error("n_derived_tydescs: %u", ccx.stats.n_derived_tydescs);
5740         #error("n_glues_created: %u", ccx.stats.n_glues_created);
5741         #error("n_null_glues: %u", ccx.stats.n_null_glues);
5742         #error("n_real_glues: %u", ccx.stats.n_real_glues);
5743
5744         for timing: {ident: str, time: int} in *ccx.stats.fn_times {
5745             #error("time: %s took %d ms", timing.ident, timing.time);
5746         }
5747     }
5748     ret (llmod, link_meta);
5749 }
5750 //
5751 // Local Variables:
5752 // mode: rust
5753 // fill-column: 78;
5754 // indent-tabs-mode: nil
5755 // c-basic-offset: 4
5756 // buffer-file-coding-system: utf-8-unix
5757 // End:
5758 //