1 // trans.rs: Translate the completed AST to the LLVM IR.
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.
8 // Hopefully useful general knowledge about trans:
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.
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;
22 import middle::{ty, gc, resolve, debuginfo};
23 import middle::freevars::*;
24 import back::{link, abi, upcall};
25 import syntax::{ast, ast_util, codemap};
27 import syntax::codemap::span;
28 import syntax::print::pprust::{expr_to_str, stmt_to_str};
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};
42 import trans_common::*;
43 import trans_build::*;
45 import trans_objects::{trans_anon_obj, trans_obj};
46 import tvec = trans_vec;
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)
54 fn type_of(cx: @crate_ctxt, sp: span, t: ty::t) : type_has_static_size(cx, t)
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)
62 fn type_of_explicit_args(cx: @crate_ctxt, sp: span, inputs: [ty::arg]) ->
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)];
77 // NB: must keep 4 fns in sync:
80 // - create_llargs_for_fn_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] = [];
87 // Arg 0: Output pointer.
88 check non_ty_var(cx, output);
89 let out_ty = T_ptr(type_of_inner(cx, sp, output));
92 // Arg 1: Env (closure-bindings / self-obj)
94 atys += [T_ptr(cx.rust_object_type)];
96 atys += [T_opaque_cbox_ptr(cx)];
99 // Args >2: ty params, if not acquired via capture...
101 for bounds in params {
102 atys += [T_ptr(cx.tydesc_type)];
103 for bound in *bounds {
105 ty::bound_iface(_) { atys += [T_ptr(T_dict())]; }
111 // ... then explicit args.
112 atys += type_of_explicit_args(cx, sp, inputs);
113 ret T_fn(atys, llvm::LLVMVoidType());
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
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);
127 fn type_of_inner(cx: @crate_ctxt, sp: span, t: ty::t)
128 : non_ty_var(cx, t) -> TypeRef {
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() }
136 T_nil() /* ...I guess? */
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) }
146 check non_ty_var(cx, mt_ty);
147 T_ptr(T_box(cx, type_of_inner(cx, sp, mt_ty))) }
150 check non_ty_var(cx, mt_ty);
151 T_ptr(type_of_inner(cx, sp, mt_ty)) }
154 if ty::type_has_dynamic_size(cx.tcx, mt_ty) {
155 T_ptr(cx.opaque_vec_type)
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))) }
163 check non_ty_var(cx, mt_ty);
164 T_ptr(type_of_inner(cx, sp, mt_ty)) }
166 let tys: [TypeRef] = [];
167 for f: ty::field in fields {
169 check non_ty_var(cx, mt_ty);
170 tys += [type_of_inner(cx, sp, mt_ty)];
175 T_fn_pair(cx, type_of_fn_from_ty(cx, sp, t, []))
177 ty::ty_native_fn(args, out) {
178 let nft = native_fn_wrapper_type(cx, sp, [], t);
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)]);
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
193 std::util::unreachable()
195 ty::ty_param(_, _) { T_typaram(cx.tn) }
196 ty::ty_send_type. | ty::ty_type. { T_ptr(cx.tydesc_type) }
200 check non_ty_var(cx, elt);
201 tys += [type_of_inner(cx, sp, elt)];
205 ty::ty_opaque_closure_ptr(_) {
206 T_opaque_cbox_ptr(cx)
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)
214 fail "type_of_inner not implemented for this kind of type";
217 cx.lltypes.insert(t, llty);
221 fn type_of_tag(cx: @crate_ctxt, sp: span, did: ast::def_id, t: ty::t)
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) }
231 if degen { T_struct([T_tag_variant(cx)]) }
232 else { T_opaque_tag(cx) }
236 fn type_of_ty_param_bounds_and_ty(lcx: @local_ctxt, sp: span,
237 tpt: ty::ty_param_bounds_and_ty) -> TypeRef {
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);
248 // FIXME: could have a precondition on tpt, but that
249 // doesn't work right now because one predicate can't imply
251 check (type_has_static_size(cx, t));
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) {
259 type_of(ccx, sp, typ)
264 // Name sanitation. LLVM will happily accept identifiers with weird names, but
266 fn sanitize(s: str) -> str {
275 if c == '{' as u8 || c == '(' as u8 {
278 if c != 10u8 && c != '}' as u8 && c != ')' as u8 &&
279 c != ' ' as u8 && c != '\t' as u8 && c != ';' as u8
282 result += str::unsafe_from_bytes(v);
292 fn log_fn_time(ccx: @crate_ctxt, name: str, start: time::timeval,
293 end: time::timeval) {
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}];
301 fn decl_fn(llmod: ModuleRef, name: str, cc: uint, llty: TypeRef) -> ValueRef {
303 str::as_buf(name, {|buf|
304 llvm::LLVMGetOrInsertFunction(llmod, buf, llty) });
305 llvm::LLVMSetFunctionCallConv(llfn, cc);
309 fn decl_cdecl_fn(llmod: ModuleRef, name: str, llty: TypeRef) -> ValueRef {
310 ret decl_fn(llmod, name, lib::llvm::LLVMCCallConv, llty);
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) ->
318 let llfn = decl_cdecl_fn(llmod, name, llty);
319 llvm::LLVMSetLinkage(llfn,
320 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
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);
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);
340 fn get_simple_extern_fn(cx: @block_ctxt,
341 externs: hashmap<str, ValueRef>,
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);
351 fn trans_native_call(cx: @block_ctxt, externs: hashmap<str, ValueRef>,
352 llmod: ModuleRef, name: str, args: [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)];
361 ret Call(cx, llnative, call_args);
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)]);
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()))]);
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);
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);
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));
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);
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);
407 fn llsize_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
408 ret llvm::LLVMConstIntCast(lib::llvm::llvm::LLVMSizeOf(t), cx.int_type,
412 fn llalign_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
413 ret llvm::LLVMConstIntCast(lib::llvm::llvm::LLVMAlignOf(t), cx.int_type,
417 fn size_of(cx: @block_ctxt, t: ty::t) -> result {
418 size_of_(cx, t, align_total)
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) {
430 rslt(cx, llsize_of(bcx_ccx(cx), type_of(ccx, sp, t)))
431 } else { dynamic_size_of(cx, t, mode) }
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) {
438 rslt(cx, llalign_of(bcx_ccx(cx), type_of(ccx, sp, t)))
439 } else { dynamic_align_of(cx, t) }
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);
447 fn dynastack_alloca(cx: @block_ctxt, t: TypeRef, n: ValueRef, ty: ty::t) ->
449 if cx.unreachable { ret llvm::LLVMGetUndef(t); }
451 let dy_cx = new_raw_block_ctxt(cx.fcx, cx.fcx.lldynamicallocas);
452 alt bcx_fcx(cx).llobstacktoken {
454 bcx_fcx(cx).llobstacktoken =
455 some(mk_obstack_token(bcx_ccx(cx), cx.fcx));
457 some(_) {/* no-op */ }
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)),
466 let lltydesc = get_tydesc(cx, ty, false, tps_normal, ti).result.val;
468 let llresult = Call(dy_cx, dynastack_alloc, [llsz, lltydesc]);
469 ret PointerCast(dy_cx, llresult, T_ptr(t));
472 fn mk_obstack_token(ccx: @crate_ctxt, fcx: @fn_ctxt) ->
474 let cx = new_raw_block_ctxt(fcx, fcx.lldynamicallocas);
475 ret Call(cx, ccx.upcalls.dynastack_mark, []);
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
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)); }
488 ret ty::mk_imm_uniq(ccx.tcx, ty::mk_nil(ccx.tcx));
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))]);
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))]);
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)]);
508 ret ty::fold_ty(ccx.tcx, ty::fm_general(bind simplifier(ccx, _)), typ);
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).
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.
526 tup_ty = ty::substitute_type_params(cx.tcx, subtys, tup_ty);
527 // Here we possibly do a recursive call.
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; }
536 cx.tag_sizes.insert(t, max_size);
540 cx.tcx.sess.span_fatal(sp, "non-tag passed to static_size_of_tag()");
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 {
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.
557 let off = C_int(bcx_ccx(cx), 0);
558 let max_align = C_int(bcx_ccx(cx), 1);
560 for e: ty::t in elts {
561 let elt_align = align_of(bcx, e);
563 let elt_size = size_of(bcx, e);
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);
571 align_to(bcx, off, max_align)
574 let {bcx, val: align} = align_of(bcx, t);
575 align_to(bcx, off, align)
580 alt ty::struct(bcx_tcx(cx), t) {
582 let szptr = field_of_tydesc(cx, t, false, abi::tydesc_field_size);
583 ret rslt(szptr.bcx, Load(szptr.bcx, szptr.val));
586 let tys: [ty::t] = [];
587 for f: ty::field in flds { tys += [f.mt.ty]; }
588 ret align_elements(cx, tys, mode);
592 for tp in elts { tys += [tp]; }
593 ret align_elements(cx, tys, mode);
595 ty::ty_tag(tid, tps) {
597 let ccx = bcx_ccx(bcx);
598 // Compute max(variant sizes).
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.
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);
612 let rslt = align_elements(bcx, tys, mode);
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);
618 let max_size_val = Load(bcx, max_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);
628 fn dynamic_align_of(cx: @block_ctxt, t: ty::t) -> result {
629 // FIXME: Typestate constraint that shows this alt is
631 alt ty::struct(bcx_tcx(cx), t) {
633 let aptr = field_of_tydesc(cx, t, false, abi::tydesc_field_align);
634 ret rslt(aptr.bcx, Load(aptr.bcx, aptr.val));
637 let a = C_int(bcx_ccx(cx), 1);
639 for f: ty::field in flds {
640 let align = align_of(bcx, f.mt.ty);
642 a = umax(bcx, a, align.val);
647 ret rslt(cx, C_int(bcx_ccx(cx), 1)); // FIXME: stub
650 let a = C_int(bcx_ccx(cx), 1);
653 let align = align_of(bcx, e);
655 a = umax(bcx, a, align.val);
662 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
663 // The type of the returned pointer is always i8*. If you care about the
664 // return type, use bump_ptr().
665 fn ptr_offs(bcx: @block_ctxt, base: ValueRef, sz: ValueRef) -> ValueRef {
666 let raw = PointerCast(bcx, base, T_ptr(T_i8()));
670 // Increment a pointer by a given amount and then cast it to be a pointer
672 fn bump_ptr(bcx: @block_ctxt, t: ty::t, base: ValueRef, sz: ValueRef) ->
674 let ccx = bcx_ccx(bcx);
675 let bumped = ptr_offs(bcx, base, sz);
676 if check type_has_static_size(ccx, t) {
678 let typ = T_ptr(type_of(ccx, sp, t));
679 PointerCast(bcx, bumped, typ)
683 // GEP_tup_like is a pain to use if you always have to precede it with a
685 fn GEP_tup_like_1(cx: @block_ctxt, t: ty::t, base: ValueRef, ixs: [int])
687 check type_is_tup_like(cx, t);
688 ret GEP_tup_like(cx, t, base, ixs);
691 // Replacement for the LLVM 'GEP' instruction when field-indexing into a
692 // tuple-like structure (tup, rec) with a static index. This one is driven off
693 // ty::struct and knows what to do when it runs into a ty_param stuck in the
694 // middle of the thing it's GEP'ing into. Much like size_of and align_of,
696 fn GEP_tup_like(bcx: @block_ctxt, t: ty::t, base: ValueRef, ixs: [int])
697 : type_is_tup_like(bcx, t) -> result {
698 // It might be a static-known type. Handle this.
699 if !ty::type_has_dynamic_size(bcx_tcx(bcx), t) {
700 ret rslt(bcx, GEPi(bcx, base, ixs));
702 // It is a dynamic-containing type that, if we convert directly to an LLVM
703 // TypeRef, will be all wrong; there's no proper LLVM type to represent
704 // it, and the lowering function will stick in i8* values for each
705 // ty_param, which is not right; the ty_params are all of some dynamic
708 // What we must do instead is sadder. We must look through the indices
709 // manually and split the input type into a prefix and a target. We then
710 // measure the prefix size, bump the input pointer by that amount, and
711 // cast to a pointer-to-target type.
713 // Given a type, an index vector and an element number N in that vector,
714 // calculate index X and the type that results by taking the first X-1
715 // elements of the type and splitting the Xth off. Return the prefix as
716 // well as the innermost Xth type.
718 fn split_type(ccx: @crate_ctxt, t: ty::t, ixs: [int], n: uint) ->
719 {prefix: [ty::t], target: ty::t} {
720 let len: uint = vec::len::<int>(ixs);
721 // We don't support 0-index or 1-index GEPs: The former is nonsense
722 // and the latter would only be meaningful if we supported non-0
723 // values for the 0th index (we don't).
727 // Since we're starting from a value that's a pointer to a
728 // *single* structure, the first index (in GEP-ese) should just be
729 // 0, to yield the pointee.
731 assert (ixs[n] == 0);
732 ret split_type(ccx, t, ixs, n + 1u);
735 let ix: int = ixs[n];
736 let prefix: [ty::t] = [];
739 prefix += [ty::get_element_type(ccx.tcx, t, i as uint)];
742 let selected = ty::get_element_type(ccx.tcx, t, i as uint);
744 // We are at the innermost index.
746 ret {prefix: prefix, target: selected};
748 // Not the innermost index; call self recursively to dig deeper.
749 // Once we get an inner result, append it current prefix and
752 let inner = split_type(ccx, selected, ixs, n + 1u);
753 prefix += inner.prefix;
754 ret {prefix: prefix with inner};
757 // We make a fake prefix tuple-type here; luckily for measuring sizes
758 // the tuple parens are associative so it doesn't matter that we've
759 // flattened the incoming structure.
761 let s = split_type(bcx_ccx(bcx), t, ixs, 0u);
764 for typ: ty::t in s.prefix { args += [typ]; }
765 let prefix_ty = ty::mk_tup(bcx_tcx(bcx), args);
767 let sz = size_of_(bcx, prefix_ty, align_next(s.target));
768 ret rslt(sz.bcx, bump_ptr(sz.bcx, s.target, base, sz.val));
772 // Replacement for the LLVM 'GEP' instruction when field indexing into a tag.
773 // This function uses GEP_tup_like() above and automatically performs casts as
774 // appropriate. @llblobptr is the data part of a tag value; its actual type is
775 // meaningless, as it will be cast away.
776 fn GEP_tag(cx: @block_ctxt, llblobptr: ValueRef, tag_id: ast::def_id,
777 variant_id: ast::def_id, ty_substs: [ty::t],
778 ix: uint) : valid_variant_index(ix, cx, tag_id, variant_id) ->
780 let variant = ty::tag_variant_with_id(bcx_tcx(cx), tag_id, variant_id);
781 // Synthesize a tuple type so that GEP_tup_like() can work its magic.
782 // Separately, store the type of the element we're interested in.
784 let arg_tys = variant.args;
786 let true_arg_tys: [ty::t] = [];
787 for aty: ty::t in arg_tys {
788 let arg_ty = ty::substitute_type_params(bcx_tcx(cx), ty_substs, aty);
789 true_arg_tys += [arg_ty];
792 // We know that ix < len(variant.args) -- so
793 // it's safe to do this. (Would be nice to have
794 // typestate guarantee that a dynamic bounds check
795 // error can't happen here, but that's in the future.)
796 let elem_ty = true_arg_tys[ix];
798 let tup_ty = ty::mk_tup(bcx_tcx(cx), true_arg_tys);
799 // Cast the blob pointer to the appropriate type, if we need to (i.e. if
800 // the blob pointer isn't dynamically sized).
802 let llunionptr: ValueRef;
804 let ccx = bcx_ccx(cx);
805 if check type_has_static_size(ccx, tup_ty) {
806 let llty = type_of(ccx, sp, tup_ty);
807 llunionptr = TruncOrBitCast(cx, llblobptr, T_ptr(llty));
808 } else { llunionptr = llblobptr; }
810 // Do the GEP_tup_like().
811 // Silly check -- postcondition on mk_tup?
812 check type_is_tup_like(cx, tup_ty);
813 let rs = GEP_tup_like(cx, tup_ty, llunionptr, [0, ix as int]);
814 // Cast the result to the appropriate type, if necessary.
816 let rs_ccx = bcx_ccx(rs.bcx);
818 if check type_has_static_size(rs_ccx, elem_ty) {
819 let llelemty = type_of(rs_ccx, sp, elem_ty);
820 PointerCast(rs.bcx, rs.val, T_ptr(llelemty))
823 ret rslt(rs.bcx, val);
826 // trans_shared_malloc: expects a type indicating which pointer type we want
827 // and a size indicating how much space we want malloc'd.
828 fn trans_shared_malloc(cx: @block_ctxt, llptr_ty: TypeRef, llsize: ValueRef)
830 // FIXME: need a table to collect tydesc globals.
832 let tydesc = C_null(T_ptr(bcx_ccx(cx).tydesc_type));
834 Call(cx, bcx_ccx(cx).upcalls.shared_malloc,
836 ret rslt(cx, PointerCast(cx, rval, llptr_ty));
839 // trans_malloc_boxed_raw: expects an unboxed type and returns a pointer to
840 // enough space for something of that type, along with space for a reference
841 // count; in other words, it allocates a box for something of that type.
842 fn trans_malloc_boxed_raw(cx: @block_ctxt, t: ty::t) -> result {
845 // Synthesize a fake box type structurally so we have something
846 // to measure the size of.
848 // We synthesize two types here because we want both the type of the
849 // pointer and the pointee. boxed_body is the type that we measure the
850 // size of; box_ptr is the type that's converted to a TypeRef and used as
851 // the pointer cast target in trans_raw_malloc.
853 // The mk_int here is the space being
854 // reserved for the refcount.
855 let boxed_body = ty::mk_tup(bcx_tcx(bcx), [ty::mk_int(bcx_tcx(cx)), t]);
856 let box_ptr = ty::mk_imm_box(bcx_tcx(bcx), t);
857 let r = size_of(cx, boxed_body);
858 let llsz = r.val; bcx = r.bcx;
860 // Grab the TypeRef type of box_ptr, because that's what trans_raw_malloc
862 // FIXME: Could avoid this check with a postcondition on mk_imm_box?
863 // (requires Issue #586)
864 let ccx = bcx_ccx(bcx);
866 check (type_has_static_size(ccx, box_ptr));
867 let llty = type_of(ccx, sp, box_ptr);
870 let tydesc_result = get_tydesc(bcx, t, true, tps_normal, ti);
871 let lltydesc = tydesc_result.result.val; bcx = tydesc_result.result.bcx;
873 let rval = Call(cx, ccx.upcalls.malloc,
875 ret rslt(cx, PointerCast(cx, rval, llty));
878 // trans_malloc_boxed: usefully wraps trans_malloc_box_raw; allocates a box,
879 // initializes the reference count to 1, and pulls out the body and rc
880 fn trans_malloc_boxed(cx: @block_ctxt, t: ty::t) ->
881 {bcx: @block_ctxt, box: ValueRef, body: ValueRef} {
882 let res = trans_malloc_boxed_raw(cx, t);
884 let rc = GEPi(res.bcx, box, [0, abi::box_rc_field_refcnt]);
885 Store(res.bcx, C_int(bcx_ccx(cx), 1), rc);
886 let body = GEPi(res.bcx, box, [0, abi::box_rc_field_body]);
887 ret {bcx: res.bcx, box: res.val, body: body};
890 // Type descriptor and type glue stuff
892 // Given a type and a field index into its corresponding type descriptor,
893 // returns an LLVM ValueRef of that field from the tydesc, generating the
894 // tydesc if necessary.
895 fn field_of_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool, field: int) ->
897 let ti = none::<@tydesc_info>;
898 let tydesc = get_tydesc(cx, t, escapes, tps_normal, ti).result;
900 GEPi(tydesc.bcx, tydesc.val, [0, field]));
903 // Given a type containing ty params, build a vector containing a ValueRef for
904 // each of the ty params it uses (from the current frame) and a vector of the
905 // indices of the ty params present in the type. This is used solely for
906 // constructing derived tydescs.
907 fn linearize_ty_params(cx: @block_ctxt, t: ty::t) ->
908 {params: [uint], descs: [ValueRef]} {
909 let param_vals: [ValueRef] = [];
910 let param_defs: [uint] = [];
912 {cx: @block_ctxt, mutable vals: [ValueRef], mutable defs: [uint]};
914 fn linearizer(r: @rr, t: ty::t) {
915 alt ty::struct(bcx_tcx(r.cx), t) {
916 ty::ty_param(pid, _) {
917 let seen: bool = false;
918 for d: uint in r.defs { if d == pid { seen = true; } }
920 r.vals += [r.cx.fcx.lltyparams[pid].desc];
927 let x = @{cx: cx, mutable vals: param_vals, mutable defs: param_defs};
928 let f = bind linearizer(x, _);
929 ty::walk_ty(bcx_tcx(cx), f, t);
930 ret {params: x.defs, descs: x.vals};
933 fn trans_stack_local_derived_tydesc(cx: @block_ctxt, llsz: ValueRef,
934 llalign: ValueRef, llroottydesc: ValueRef,
935 llfirstparam: ValueRef, n_params: uint,
936 obj_params: uint) -> ValueRef {
937 let llmyroottydesc = alloca(cx, bcx_ccx(cx).tydesc_type);
939 // By convention, desc 0 is the root descriptor.
940 let llroottydesc = Load(cx, llroottydesc);
941 Store(cx, llroottydesc, llmyroottydesc);
943 // Store a pointer to the rest of the descriptors.
944 let ccx = bcx_ccx(cx);
945 store_inbounds(cx, llfirstparam, llmyroottydesc,
946 [0, abi::tydesc_field_first_param]);
947 store_inbounds(cx, C_uint(ccx, n_params), llmyroottydesc,
948 [0, abi::tydesc_field_n_params]);
949 store_inbounds(cx, llsz, llmyroottydesc,
950 [0, abi::tydesc_field_size]);
951 store_inbounds(cx, llalign, llmyroottydesc,
952 [0, abi::tydesc_field_align]);
953 store_inbounds(cx, C_uint(ccx, obj_params), llmyroottydesc,
954 [0, abi::tydesc_field_obj_params]);
958 // Objects and closures store their type parameters differently (in the object
959 // or closure itself rather than in the type descriptor).
960 tag ty_param_storage { tps_normal; tps_obj(uint); tps_fn(uint); }
962 fn get_derived_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool,
963 storage: ty_param_storage,
964 &static_ti: option::t<@tydesc_info>) -> result {
965 alt cx.fcx.derived_tydescs.find(t) {
967 // If the tydesc escapes in this context, the cached derived
968 // tydesc also has to be one that was marked as escaping.
969 if !(escapes && !info.escapes) && storage == tps_normal {
970 ret rslt(cx, info.lltydesc);
973 none. {/* fall through */ }
978 tps_normal. { is_obj_body = false; }
979 tps_obj(_) | tps_fn(_) { is_obj_body = true; }
982 bcx_ccx(cx).stats.n_derived_tydescs += 1u;
983 let bcx = new_raw_block_ctxt(cx.fcx, cx.fcx.llderivedtydescs);
984 let tys = linearize_ty_params(bcx, t);
985 let root_ti = get_static_tydesc(bcx, t, tys.params, is_obj_body);
986 static_ti = some::<@tydesc_info>(root_ti);
987 lazily_emit_all_tydesc_glue(cx, static_ti);
988 let root = root_ti.tydesc;
989 let sz = size_of(bcx, t);
991 let align = align_of(bcx, t);
994 // Store the captured type descriptors in an alloca if the caller isn't
995 // promising to do so itself.
996 let n_params = ty::count_ty_params(bcx_tcx(bcx), t);
998 assert (n_params == vec::len::<uint>(tys.params));
999 assert (n_params == vec::len::<ValueRef>(tys.descs));
1001 let llparamtydescs =
1002 alloca(bcx, T_array(T_ptr(bcx_ccx(bcx).tydesc_type), n_params + 1u));
1005 // If the type descriptor escapes, we need to add in the root as
1006 // the first parameter, because upcall_get_type_desc() expects it.
1008 Store(bcx, root, GEPi(bcx, llparamtydescs, [0, 0]));
1012 for td: ValueRef in tys.descs {
1013 Store(bcx, td, GEPi(bcx, llparamtydescs, [0, i]));
1018 PointerCast(bcx, llparamtydescs,
1019 T_ptr(T_ptr(bcx_ccx(bcx).tydesc_type)));
1021 // The top bit indicates whether this type descriptor describes an object
1022 // (0) or a function (1).
1025 tps_normal. { obj_params = 0u; }
1026 tps_obj(np) { obj_params = np; }
1027 tps_fn(np) { obj_params = 0x80000000u | np; }
1032 let ccx = bcx_ccx(bcx);
1034 Call(bcx, ccx.upcalls.get_type_desc,
1035 [C_null(T_ptr(T_nil())), sz.val,
1036 align.val, C_uint(ccx, 1u + n_params), llfirstparam,
1037 C_uint(ccx, obj_params)]);
1041 trans_stack_local_derived_tydesc(bcx, sz.val, align.val, root,
1042 llfirstparam, n_params,
1045 bcx.fcx.derived_tydescs.insert(t, {lltydesc: v, escapes: escapes});
1049 type get_tydesc_result = {kind: tydesc_kind, result: result};
1051 fn get_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool,
1052 storage: ty_param_storage, &static_ti: option::t<@tydesc_info>)
1053 -> get_tydesc_result {
1055 // Is the supplied type a type param? If so, return the passed-in tydesc.
1056 alt ty::type_param(bcx_tcx(cx), t) {
1058 if id < vec::len(cx.fcx.lltyparams) {
1059 ret {kind: tk_param,
1060 result: rslt(cx, cx.fcx.lltyparams[id].desc)};
1062 bcx_tcx(cx).sess.span_bug(cx.sp,
1063 "Unbound typaram in get_tydesc: " +
1065 ty_to_str(bcx_tcx(cx), t) +
1070 none. {/* fall through */ }
1073 // Does it contain a type param? If so, generate a derived tydesc.
1074 if ty::type_contains_params(bcx_tcx(cx), t) {
1075 ret {kind: tk_derived,
1076 result: get_derived_tydesc(cx, t, escapes, storage, static_ti)};
1078 // Otherwise, generate a tydesc if necessary, and return it.
1079 let info = get_static_tydesc(cx, t, [], false);
1080 static_ti = some::<@tydesc_info>(info);
1081 ret {kind: tk_static, result: rslt(cx, info.tydesc)};
1084 fn get_static_tydesc(cx: @block_ctxt, t: ty::t, ty_params: [uint],
1085 is_obj_body: bool) -> @tydesc_info {
1086 alt bcx_ccx(cx).tydescs.find(t) {
1087 some(info) { ret info; }
1089 bcx_ccx(cx).stats.n_static_tydescs += 1u;
1090 let info = declare_tydesc(cx.fcx.lcx, cx.sp, t, ty_params,
1092 bcx_ccx(cx).tydescs.insert(t, info);
1098 fn set_no_inline(f: ValueRef) {
1099 llvm::LLVMAddFunctionAttr(f,
1100 lib::llvm::LLVMNoInlineAttribute as
1101 lib::llvm::llvm::Attribute,
1105 // Tell LLVM to emit the information necessary to unwind the stack for the
1107 fn set_uwtable(f: ValueRef) {
1108 llvm::LLVMAddFunctionAttr(f,
1109 lib::llvm::LLVMUWTableAttribute as
1110 lib::llvm::llvm::Attribute,
1114 fn set_always_inline(f: ValueRef) {
1115 llvm::LLVMAddFunctionAttr(f,
1116 lib::llvm::LLVMAlwaysInlineAttribute as
1117 lib::llvm::llvm::Attribute,
1121 fn set_custom_stack_growth_fn(f: ValueRef) {
1122 // TODO: Remove this hack to work around the lack of u64 in the FFI.
1123 llvm::LLVMAddFunctionAttr(f, 0 as lib::llvm::llvm::Attribute, 1u);
1126 fn set_glue_inlining(cx: @local_ctxt, f: ValueRef, t: ty::t) {
1127 if ty::type_is_structural(cx.ccx.tcx, t) {
1129 } else { set_always_inline(f); }
1133 // Generates the declaration for (but doesn't emit) a type descriptor.
1134 fn declare_tydesc(cx: @local_ctxt, sp: span, t: ty::t, ty_params: [uint],
1135 is_obj_body: bool) ->
1137 log(debug, "+++ declare_tydesc " + ty_to_str(cx.ccx.tcx, t));
1141 if check type_has_static_size(ccx, t) {
1142 let llty = type_of(ccx, sp, t);
1143 llsize = llsize_of(ccx, llty);
1144 llalign = llalign_of(ccx, llty);
1146 // These will be overwritten as the derived tydesc is generated, so
1147 // we create placeholder values.
1149 llsize = C_int(ccx, 0);
1150 llalign = C_int(ccx, 0);
1153 if cx.ccx.sess.get_opts().debuginfo {
1154 name = mangle_internal_name_by_type_only(cx.ccx, t, "tydesc");
1155 name = sanitize(name);
1156 } else { name = mangle_internal_name_by_seq(cx.ccx, "tydesc"); }
1160 llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type, buf)
1167 mutable take_glue: none::<ValueRef>,
1168 mutable drop_glue: none::<ValueRef>,
1169 mutable free_glue: none::<ValueRef>,
1170 mutable cmp_glue: none::<ValueRef>,
1171 ty_params: ty_params,
1172 is_obj_body: is_obj_body};
1173 log(debug, "--- declare_tydesc " + ty_to_str(cx.ccx.tcx, t));
1177 type glue_helper = fn(@block_ctxt, ValueRef, ty::t);
1179 fn declare_generic_glue(cx: @local_ctxt, t: ty::t, llfnty: TypeRef, name: str)
1183 if cx.ccx.sess.get_opts().debuginfo {
1184 fn_nm = mangle_internal_name_by_type_only(cx.ccx, t, "glue_" + name);
1185 fn_nm = sanitize(fn_nm);
1186 } else { fn_nm = mangle_internal_name_by_seq(cx.ccx, "glue_" + name); }
1187 let llfn = decl_cdecl_fn(cx.ccx.llmod, fn_nm, llfnty);
1188 set_glue_inlining(cx, llfn, t);
1192 // FIXME: was this causing the leak?
1193 fn make_generic_glue_inner(cx: @local_ctxt, sp: span, t: ty::t,
1194 llfn: ValueRef, helper: glue_helper,
1195 ty_params: [uint]) -> ValueRef {
1196 let fcx = new_fn_ctxt(cx, sp, llfn);
1197 llvm::LLVMSetLinkage(llfn,
1198 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
1199 cx.ccx.stats.n_glues_created += 1u;
1200 // Any nontrivial glue is with values passed *by alias*; this is a
1201 // requirement since in many contexts glue is invoked indirectly and
1202 // the caller has no idea if it's dealing with something that can be
1207 if check type_has_static_size(ccx, t) {
1208 T_ptr(type_of(ccx, sp, t))
1209 } else { T_ptr(T_i8()) };
1211 let ty_param_count = vec::len::<uint>(ty_params);
1212 let lltyparams = llvm::LLVMGetParam(llfn, 2u);
1213 let load_env_bcx = new_raw_block_ctxt(fcx, fcx.llloadenv);
1214 let lltydescs = [mutable];
1216 while p < ty_param_count {
1217 let llparam = GEPi(load_env_bcx, lltyparams, [p as int]);
1218 llparam = Load(load_env_bcx, llparam);
1219 vec::grow_set(lltydescs, ty_params[p], 0 as ValueRef, llparam);
1223 fcx.lltyparams = vec::map_mut(lltydescs, {|d| {desc: d, dicts: none}});
1225 let bcx = new_top_block_ctxt(fcx);
1226 let lltop = bcx.llbb;
1227 let llrawptr0 = llvm::LLVMGetParam(llfn, 3u);
1228 let llval0 = BitCast(bcx, llrawptr0, llty);
1229 helper(bcx, llval0, t);
1230 finish_fn(fcx, lltop);
1234 fn make_generic_glue(cx: @local_ctxt, sp: span, t: ty::t, llfn: ValueRef,
1235 helper: glue_helper, ty_params: [uint], name: str) ->
1237 if !cx.ccx.sess.get_opts().stats {
1238 ret make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
1241 let start = time::get_time();
1242 let llval = make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
1243 let end = time::get_time();
1244 log_fn_time(cx.ccx, "glue " + name + " " + ty_to_short_str(cx.ccx.tcx, t),
1249 fn emit_tydescs(ccx: @crate_ctxt) {
1250 ccx.tydescs.items {|key, val|
1251 let glue_fn_ty = T_ptr(T_glue_fn(ccx));
1252 let cmp_fn_ty = T_ptr(T_cmp_glue_fn(ccx));
1256 none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1257 some(v) { ccx.stats.n_real_glues += 1u; v }
1261 none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1262 some(v) { ccx.stats.n_real_glues += 1u; v }
1266 none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1267 some(v) { ccx.stats.n_real_glues += 1u; v }
1271 none. { ccx.stats.n_null_glues += 1u; C_null(cmp_fn_ty) }
1272 some(v) { ccx.stats.n_real_glues += 1u; v }
1275 let shape = shape::shape_of(ccx, key, ti.ty_params,
1278 llvm::LLVMConstPointerCast(ccx.shape_cx.llshapetables,
1282 C_named_struct(ccx.tydesc_type,
1283 [C_null(T_ptr(T_ptr(ccx.tydesc_type))),
1286 take_glue, // take_glue
1287 drop_glue, // drop_glue
1288 free_glue, // free_glue
1289 C_null(T_ptr(T_i8())), // unused
1290 C_null(glue_fn_ty), // sever_glue
1291 C_null(glue_fn_ty), // mark_glue
1292 C_null(glue_fn_ty), // unused
1293 cmp_glue, // cmp_glue
1294 C_shape(ccx, shape), // shape
1295 shape_tables, // shape_tables
1296 C_int(ccx, 0), // n_params
1297 C_int(ccx, 0)]); // n_obj_params
1299 let gvar = ti.tydesc;
1300 llvm::LLVMSetInitializer(gvar, tydesc);
1301 llvm::LLVMSetGlobalConstant(gvar, True);
1302 llvm::LLVMSetLinkage(gvar,
1303 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
1307 fn make_take_glue(cx: @block_ctxt, v: ValueRef, t: ty::t) {
1310 let tcx = bcx_tcx(cx);
1311 // NB: v is an *alias* of type t here, not a direct value.
1312 bcx = alt ty::struct(tcx, t) {
1314 incr_refcnt_of_boxed(bcx, Load(bcx, v))
1317 check trans_uniq::type_is_unique_box(bcx, t);
1318 let r = trans_uniq::duplicate(bcx, Load(bcx, v), t);
1319 Store(r.bcx, r.val, v);
1322 ty::ty_vec(_) | ty::ty_str. {
1323 let r = tvec::duplicate(bcx, Load(bcx, v), t);
1324 Store(r.bcx, r.val, v);
1328 // sendable type descriptors are basically unique pointers,
1329 // they must be cloned when copied:
1330 let r = Load(bcx, v);
1331 let s = Call(bcx, bcx_ccx(bcx).upcalls.create_shared_type_desc, [r]);
1335 ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1336 trans_closure::make_fn_glue(bcx, v, t, take_ty)
1338 ty::ty_opaque_closure_ptr(ck) {
1339 trans_closure::make_opaque_cbox_take_glue(bcx, ck, v)
1341 _ when ty::type_is_structural(bcx_tcx(bcx), t) {
1342 iter_structural_ty(bcx, v, t, take_ty)
1350 fn incr_refcnt_of_boxed(cx: @block_ctxt, box_ptr: ValueRef) -> @block_ctxt {
1351 let ccx = bcx_ccx(cx);
1353 GEPi(cx, box_ptr, [0, abi::box_rc_field_refcnt]);
1354 let rc = Load(cx, rc_ptr);
1355 rc = Add(cx, rc, C_int(ccx, 1));
1356 Store(cx, rc, rc_ptr);
1360 fn free_box(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1361 ret alt ty::struct(bcx_tcx(bcx), t) {
1362 ty::ty_box(body_mt) {
1363 let v = PointerCast(bcx, v, type_of_1(bcx, t));
1364 let body = GEPi(bcx, v, [0, abi::box_rc_field_body]);
1365 let bcx = drop_ty(bcx, body, body_mt.ty);
1366 trans_free_if_not_gc(bcx, v)
1369 _ { fail "free_box invoked with non-box type"; }
1373 fn make_free_glue(bcx: @block_ctxt, v: ValueRef, t: ty::t) {
1374 // v is a pointer to the actual box component of the type here. The
1375 // ValueRef will have the wrong type here (make_generic_glue is casting
1376 // everything to a pointer to the type that the glue acts on).
1377 let bcx = alt ty::struct(bcx_tcx(bcx), t) {
1378 ty::ty_box(body_mt) {
1381 ty::ty_uniq(content_mt) {
1382 check trans_uniq::type_is_unique_box(bcx, t);
1383 let v = PointerCast(bcx, v, type_of_1(bcx, t));
1384 trans_uniq::make_free_glue(bcx, v, t)
1386 ty::ty_vec(_) | ty::ty_str. {
1387 tvec::make_free_glue(bcx, PointerCast(bcx, v, type_of_1(bcx, t)), t)
1390 // Call through the obj's own fields-drop glue first.
1391 // Then free the body.
1392 let ccx = bcx_ccx(bcx);
1393 let llbox_ty = T_opaque_obj_ptr(ccx);
1394 let b = PointerCast(bcx, v, llbox_ty);
1395 let body = GEPi(bcx, b, [0, abi::box_rc_field_body]);
1397 GEPi(bcx, body, [0, abi::obj_body_elt_tydesc]);
1398 let tydesc = Load(bcx, tydescptr);
1400 call_tydesc_glue_full(bcx, body, tydesc,
1401 abi::tydesc_field_drop_glue, ti);
1402 trans_free_if_not_gc(bcx, b)
1405 // sendable type descriptors are basically unique pointers,
1406 // they must be freed.
1407 let ccx = bcx_ccx(bcx);
1408 let v = PointerCast(bcx, v, T_ptr(ccx.tydesc_type));
1409 Call(bcx, ccx.upcalls.free_shared_type_desc, [v]);
1412 ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1413 trans_closure::make_fn_glue(bcx, v, t, free_ty)
1415 ty::ty_opaque_closure_ptr(ck) {
1416 trans_closure::make_opaque_cbox_free_glue(bcx, ck, v)
1423 fn make_drop_glue(bcx: @block_ctxt, v0: ValueRef, t: ty::t) {
1424 // NB: v0 is an *alias* of type t here, not a direct value.
1425 let ccx = bcx_ccx(bcx);
1427 alt ty::struct(ccx.tcx, t) {
1428 ty::ty_box(_) { decr_refcnt_maybe_free(bcx, Load(bcx, v0), t) }
1429 ty::ty_uniq(_) | ty::ty_vec(_) | ty::ty_str. | ty::ty_send_type. {
1430 free_ty(bcx, Load(bcx, v0), t)
1434 GEPi(bcx, v0, [0, abi::obj_field_box]);
1435 decr_refcnt_maybe_free(bcx, Load(bcx, box_cell), t)
1437 ty::ty_res(did, inner, tps) {
1438 trans_res_drop(bcx, v0, did, inner, tps)
1440 ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1441 trans_closure::make_fn_glue(bcx, v0, t, drop_ty)
1443 ty::ty_opaque_closure_ptr(ck) {
1444 trans_closure::make_opaque_cbox_drop_glue(bcx, ck, v0)
1447 if ty::type_needs_drop(ccx.tcx, t) &&
1448 ty::type_is_structural(ccx.tcx, t) {
1449 iter_structural_ty(bcx, v0, t, drop_ty)
1456 fn trans_res_drop(cx: @block_ctxt, rs: ValueRef, did: ast::def_id,
1457 inner_t: ty::t, tps: [ty::t]) -> @block_ctxt {
1458 let ccx = bcx_ccx(cx);
1459 let inner_t_s = ty::substitute_type_params(ccx.tcx, tps, inner_t);
1460 let tup_ty = ty::mk_tup(ccx.tcx, [ty::mk_int(ccx.tcx), inner_t_s]);
1461 let drop_cx = new_sub_block_ctxt(cx, "drop res");
1462 let next_cx = new_sub_block_ctxt(cx, "next");
1465 check type_is_tup_like(cx, tup_ty);
1466 let drop_flag = GEP_tup_like(cx, tup_ty, rs, [0, 0]);
1467 let cx = drop_flag.bcx;
1468 let null_test = IsNull(cx, Load(cx, drop_flag.val));
1469 CondBr(cx, null_test, next_cx.llbb, drop_cx.llbb);
1472 check type_is_tup_like(cx, tup_ty);
1473 let val = GEP_tup_like(cx, tup_ty, rs, [0, 1]);
1475 // Find and call the actual destructor.
1476 let dtor_addr = trans_common::get_res_dtor(ccx, cx.sp, did, inner_t);
1477 let args = [cx.fcx.llretptr, null_env_ptr(cx)];
1478 for tp: ty::t in tps {
1479 let ti: option::t<@tydesc_info> = none;
1480 let td = get_tydesc(cx, tp, false, tps_normal, ti).result;
1484 // Kludge to work around the fact that we know the precise type of the
1485 // value here, but the dtor expects a type that still has opaque pointers
1486 // for type variables.
1487 let val_llty = lib::llvm::fn_ty_param_tys
1488 (llvm::LLVMGetElementType
1489 (llvm::LLVMTypeOf(dtor_addr)))[vec::len(args)];
1490 let val_cast = BitCast(cx, val.val, val_llty);
1491 Call(cx, dtor_addr, args + [val_cast]);
1493 cx = drop_ty(cx, val.val, inner_t_s);
1494 // FIXME #1184: Resource flag is larger than necessary
1495 Store(cx, C_int(ccx, 0), drop_flag.val);
1496 Br(cx, next_cx.llbb);
1500 fn decr_refcnt_maybe_free(cx: @block_ctxt, box_ptr: ValueRef, t: ty::t)
1502 let ccx = bcx_ccx(cx);
1503 let rc_adj_cx = new_sub_block_ctxt(cx, "rc--");
1504 let free_cx = new_sub_block_ctxt(cx, "free");
1505 let next_cx = new_sub_block_ctxt(cx, "next");
1506 let llbox_ty = T_opaque_obj_ptr(ccx);
1507 let box_ptr = PointerCast(cx, box_ptr, llbox_ty);
1508 let null_test = IsNull(cx, box_ptr);
1509 CondBr(cx, null_test, next_cx.llbb, rc_adj_cx.llbb);
1511 GEPi(rc_adj_cx, box_ptr, [0, abi::box_rc_field_refcnt]);
1512 let rc = Load(rc_adj_cx, rc_ptr);
1513 rc = Sub(rc_adj_cx, rc, C_int(ccx, 1));
1514 Store(rc_adj_cx, rc, rc_ptr);
1515 let zero_test = ICmp(rc_adj_cx, lib::llvm::LLVMIntEQ, C_int(ccx, 0), rc);
1516 CondBr(rc_adj_cx, zero_test, free_cx.llbb, next_cx.llbb);
1517 let free_cx = free_ty(free_cx, box_ptr, t);
1518 Br(free_cx, next_cx.llbb);
1523 // Structural comparison: a rather involved form of glue.
1524 fn maybe_name_value(cx: @crate_ctxt, v: ValueRef, s: str) {
1525 if cx.sess.get_opts().save_temps {
1526 let _: () = str::as_buf(s, {|buf| llvm::LLVMSetValueName(v, buf) });
1531 // Used only for creating scalar comparison glue.
1532 tag scalar_type { nil_type; signed_int; unsigned_int; floating_point; }
1535 fn compare_scalar_types(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef,
1536 t: ty::t, op: ast::binop) -> result {
1537 let f = bind compare_scalar_values(cx, lhs, rhs, _, op);
1539 alt ty::struct(bcx_tcx(cx), t) {
1540 ty::ty_nil. { ret rslt(cx, f(nil_type)); }
1541 ty::ty_bool. | ty::ty_ptr(_) { ret rslt(cx, f(unsigned_int)); }
1542 ty::ty_int(_) { ret rslt(cx, f(signed_int)); }
1543 ty::ty_uint(_) { ret rslt(cx, f(unsigned_int)); }
1544 ty::ty_float(_) { ret rslt(cx, f(floating_point)); }
1546 ret rslt(trans_fail(cx, none,
1547 "attempt to compare values of type type"),
1551 let cx = trans_fail(cx, none::<span>,
1552 "attempt to compare values of type native");
1553 ret rslt(cx, C_nil());
1556 // Should never get here, because t is scalar.
1557 bcx_ccx(cx).sess.bug("non-scalar type passed to \
1558 compare_scalar_types");
1564 // A helper function to do the actual comparison of scalar values.
1565 fn compare_scalar_values(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef,
1566 nt: scalar_type, op: ast::binop) -> ValueRef {
1569 // We don't need to do actual comparisons for nil.
1570 // () == () holds but () < () does not.
1572 ast::eq. | ast::le. | ast::ge. { ret C_bool(true); }
1573 ast::ne. | ast::lt. | ast::gt. { ret C_bool(false); }
1578 ast::eq. { lib::llvm::LLVMRealOEQ }
1579 ast::ne. { lib::llvm::LLVMRealUNE }
1580 ast::lt. { lib::llvm::LLVMRealOLT }
1581 ast::le. { lib::llvm::LLVMRealOLE }
1582 ast::gt. { lib::llvm::LLVMRealOGT }
1583 ast::ge. { lib::llvm::LLVMRealOGE }
1585 ret FCmp(cx, cmp, lhs, rhs);
1589 ast::eq. { lib::llvm::LLVMIntEQ }
1590 ast::ne. { lib::llvm::LLVMIntNE }
1591 ast::lt. { lib::llvm::LLVMIntSLT }
1592 ast::le. { lib::llvm::LLVMIntSLE }
1593 ast::gt. { lib::llvm::LLVMIntSGT }
1594 ast::ge. { lib::llvm::LLVMIntSGE }
1596 ret ICmp(cx, cmp, lhs, rhs);
1600 ast::eq. { lib::llvm::LLVMIntEQ }
1601 ast::ne. { lib::llvm::LLVMIntNE }
1602 ast::lt. { lib::llvm::LLVMIntULT }
1603 ast::le. { lib::llvm::LLVMIntULE }
1604 ast::gt. { lib::llvm::LLVMIntUGT }
1605 ast::ge. { lib::llvm::LLVMIntUGE }
1607 ret ICmp(cx, cmp, lhs, rhs);
1612 type val_pair_fn = fn(@block_ctxt, ValueRef, ValueRef) -> @block_ctxt;
1613 type val_and_ty_fn = fn(@block_ctxt, ValueRef, ty::t) -> @block_ctxt;
1615 fn load_inbounds(cx: @block_ctxt, p: ValueRef, idxs: [int]) -> ValueRef {
1616 ret Load(cx, GEPi(cx, p, idxs));
1619 fn store_inbounds(cx: @block_ctxt, v: ValueRef, p: ValueRef,
1621 Store(cx, v, GEPi(cx, p, idxs));
1624 // Iterates through the elements of a structural type.
1625 fn iter_structural_ty(cx: @block_ctxt, av: ValueRef, t: ty::t,
1626 f: val_and_ty_fn) -> @block_ctxt {
1627 fn iter_boxpp(cx: @block_ctxt, box_cell: ValueRef, f: val_and_ty_fn) ->
1629 let box_ptr = Load(cx, box_cell);
1630 let tnil = ty::mk_nil(bcx_tcx(cx));
1631 let tbox = ty::mk_imm_box(bcx_tcx(cx), tnil);
1632 let inner_cx = new_sub_block_ctxt(cx, "iter box");
1633 let next_cx = new_sub_block_ctxt(cx, "next");
1634 let null_test = IsNull(cx, box_ptr);
1635 CondBr(cx, null_test, next_cx.llbb, inner_cx.llbb);
1636 let inner_cx = f(inner_cx, box_cell, tbox);
1637 Br(inner_cx, next_cx.llbb);
1641 fn iter_variant(cx: @block_ctxt, a_tup: ValueRef,
1642 variant: ty::variant_info, tps: [ty::t], tid: ast::def_id,
1643 f: val_and_ty_fn) -> @block_ctxt {
1644 if vec::len::<ty::t>(variant.args) == 0u { ret cx; }
1645 let fn_ty = variant.ctor_ty;
1646 let ccx = bcx_ccx(cx);
1648 alt ty::struct(ccx.tcx, fn_ty) {
1649 ty::ty_fn({inputs: args, _}) {
1651 let v_id = variant.id;
1652 for a: ty::arg in args {
1653 check (valid_variant_index(j, cx, tid, v_id));
1654 let rslt = GEP_tag(cx, a_tup, tid, v_id, tps, j);
1655 let llfldp_a = rslt.val;
1657 let ty_subst = ty::substitute_type_params(ccx.tcx, tps, a.ty);
1658 cx = f(cx, llfldp_a, ty_subst);
1667 Typestate constraint that shows the unimpl case doesn't happen?
1670 alt ty::struct(bcx_tcx(cx), t) {
1671 ty::ty_rec(fields) {
1673 for fld: ty::field in fields {
1675 check type_is_tup_like(cx, t);
1676 let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
1677 cx = f(bcx, llfld_a, fld.mt.ty);
1685 check type_is_tup_like(cx, t);
1686 let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
1687 cx = f(bcx, llfld_a, arg);
1691 ty::ty_res(_, inner, tps) {
1692 let tcx = bcx_tcx(cx);
1693 let inner1 = ty::substitute_type_params(tcx, tps, inner);
1694 let inner_t_s = ty::substitute_type_params(tcx, tps, inner);
1695 let tup_t = ty::mk_tup(tcx, [ty::mk_int(tcx), inner_t_s]);
1697 check type_is_tup_like(cx, tup_t);
1698 let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, tup_t, av, [0, 1]);
1699 ret f(bcx, llfld_a, inner1);
1701 ty::ty_tag(tid, tps) {
1702 let variants = ty::tag_variants(bcx_tcx(cx), tid);
1703 let n_variants = vec::len(*variants);
1705 // Cast the tags to types we can GEP into.
1706 if n_variants == 1u {
1707 ret iter_variant(cx, av, variants[0], tps, tid, f);
1710 let ccx = bcx_ccx(cx);
1711 let lltagty = T_opaque_tag_ptr(ccx);
1712 let av_tag = PointerCast(cx, av, lltagty);
1713 let lldiscrim_a_ptr = GEPi(cx, av_tag, [0, 0]);
1714 let llunion_a_ptr = GEPi(cx, av_tag, [0, 1]);
1715 let lldiscrim_a = Load(cx, lldiscrim_a_ptr);
1717 // NB: we must hit the discriminant first so that structural
1718 // comparison know not to proceed when the discriminants differ.
1719 cx = f(cx, lldiscrim_a_ptr, ty::mk_int(bcx_tcx(cx)));
1720 let unr_cx = new_sub_block_ctxt(cx, "tag-iter-unr");
1721 Unreachable(unr_cx);
1722 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb, n_variants);
1723 let next_cx = new_sub_block_ctxt(cx, "tag-iter-next");
1725 for variant: ty::variant_info in *variants {
1727 new_sub_block_ctxt(cx,
1728 "tag-iter-variant-" +
1729 uint::to_str(i, 10u));
1730 AddCase(llswitch, C_int(ccx, i as int), variant_cx.llbb);
1732 iter_variant(variant_cx, llunion_a_ptr, variant, tps, tid, f);
1733 Br(variant_cx, next_cx.llbb);
1739 let box_cell_a = GEPi(cx, av, [0, abi::obj_field_box]);
1740 ret iter_boxpp(cx, box_cell_a, f);
1742 _ { bcx_ccx(cx).sess.unimpl("type in iter_structural_ty"); }
1747 fn lazily_emit_all_tydesc_glue(cx: @block_ctxt,
1748 static_ti: option::t<@tydesc_info>) {
1749 lazily_emit_tydesc_glue(cx, abi::tydesc_field_take_glue, static_ti);
1750 lazily_emit_tydesc_glue(cx, abi::tydesc_field_drop_glue, static_ti);
1751 lazily_emit_tydesc_glue(cx, abi::tydesc_field_free_glue, static_ti);
1752 lazily_emit_tydesc_glue(cx, abi::tydesc_field_cmp_glue, static_ti);
1755 fn lazily_emit_all_generic_info_tydesc_glues(cx: @block_ctxt,
1757 for ti: option::t<@tydesc_info> in gi.static_tis {
1758 lazily_emit_all_tydesc_glue(cx, ti);
1762 fn lazily_emit_tydesc_glue(cx: @block_ctxt, field: int,
1763 static_ti: option::t<@tydesc_info>) {
1767 if field == abi::tydesc_field_take_glue {
1771 #debug("+++ lazily_emit_tydesc_glue TAKE %s",
1772 ty_to_str(bcx_tcx(cx), ti.ty));
1773 let lcx = cx.fcx.lcx;
1775 declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1777 ti.take_glue = some::<ValueRef>(glue_fn);
1778 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1780 ti.ty_params, "take");
1781 #debug("--- lazily_emit_tydesc_glue TAKE %s",
1782 ty_to_str(bcx_tcx(cx), ti.ty));
1785 } else if field == abi::tydesc_field_drop_glue {
1789 #debug("+++ lazily_emit_tydesc_glue DROP %s",
1790 ty_to_str(bcx_tcx(cx), ti.ty));
1791 let lcx = cx.fcx.lcx;
1793 declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1795 ti.drop_glue = some::<ValueRef>(glue_fn);
1796 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1798 ti.ty_params, "drop");
1799 #debug("--- lazily_emit_tydesc_glue DROP %s",
1800 ty_to_str(bcx_tcx(cx), ti.ty));
1803 } else if field == abi::tydesc_field_free_glue {
1807 #debug("+++ lazily_emit_tydesc_glue FREE %s",
1808 ty_to_str(bcx_tcx(cx), ti.ty));
1809 let lcx = cx.fcx.lcx;
1811 declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1813 ti.free_glue = some::<ValueRef>(glue_fn);
1814 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1816 ti.ty_params, "free");
1817 #debug("--- lazily_emit_tydesc_glue FREE %s",
1818 ty_to_str(bcx_tcx(cx), ti.ty));
1821 } else if field == abi::tydesc_field_cmp_glue {
1825 #debug("+++ lazily_emit_tydesc_glue CMP %s",
1826 ty_to_str(bcx_tcx(cx), ti.ty));
1827 ti.cmp_glue = some(bcx_ccx(cx).upcalls.cmp_type);
1828 #debug("--- lazily_emit_tydesc_glue CMP %s",
1829 ty_to_str(bcx_tcx(cx), ti.ty));
1837 fn call_tydesc_glue_full(cx: @block_ctxt, v: ValueRef, tydesc: ValueRef,
1838 field: int, static_ti: option::t<@tydesc_info>) {
1839 lazily_emit_tydesc_glue(cx, field, static_ti);
1841 let static_glue_fn = none;
1843 none. {/* no-op */ }
1845 if field == abi::tydesc_field_take_glue {
1846 static_glue_fn = sti.take_glue;
1847 } else if field == abi::tydesc_field_drop_glue {
1848 static_glue_fn = sti.drop_glue;
1849 } else if field == abi::tydesc_field_free_glue {
1850 static_glue_fn = sti.free_glue;
1855 let llrawptr = PointerCast(cx, v, T_ptr(T_i8()));
1857 GEPi(cx, tydesc, [0, abi::tydesc_field_first_param]);
1858 lltydescs = Load(cx, lltydescs);
1861 alt static_glue_fn {
1863 let llfnptr = GEPi(cx, tydesc, [0, field]);
1864 llfn = Load(cx, llfnptr);
1866 some(sgf) { llfn = sgf; }
1869 Call(cx, llfn, [C_null(T_ptr(T_nil())), C_null(T_ptr(T_nil())),
1870 lltydescs, llrawptr]);
1873 fn call_tydesc_glue(cx: @block_ctxt, v: ValueRef, t: ty::t, field: int) ->
1875 let ti: option::t<@tydesc_info> = none::<@tydesc_info>;
1876 let {bcx: bcx, val: td} = get_tydesc(cx, t, false, tps_normal, ti).result;
1877 call_tydesc_glue_full(bcx, v, td, field, ti);
1881 fn call_cmp_glue(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef, t: ty::t,
1882 llop: ValueRef) -> result {
1883 // We can't use call_tydesc_glue_full() and friends here because compare
1884 // glue has a special signature.
1888 let r = spill_if_immediate(bcx, lhs, t);
1891 r = spill_if_immediate(bcx, rhs, t);
1895 let llrawlhsptr = BitCast(bcx, lllhs, T_ptr(T_i8()));
1896 let llrawrhsptr = BitCast(bcx, llrhs, T_ptr(T_i8()));
1897 let ti = none::<@tydesc_info>;
1898 r = get_tydesc(bcx, t, false, tps_normal, ti).result;
1899 let lltydesc = r.val;
1901 lazily_emit_tydesc_glue(bcx, abi::tydesc_field_cmp_glue, ti);
1903 GEPi(bcx, lltydesc, [0, abi::tydesc_field_first_param]);
1904 lltydescs = Load(bcx, lltydescs);
1910 GEPi(bcx, lltydesc, [0, abi::tydesc_field_cmp_glue]);
1911 llfn = Load(bcx, llfnptr);
1913 some(sti) { llfn = option::get(sti.cmp_glue); }
1916 let llcmpresultptr = alloca(bcx, T_i1());
1917 Call(bcx, llfn, [llcmpresultptr, lltydesc, lltydescs,
1918 llrawlhsptr, llrawrhsptr, llop]);
1919 ret rslt(bcx, Load(bcx, llcmpresultptr));
1922 fn take_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1923 if ty::type_needs_drop(bcx_tcx(cx), t) {
1924 ret call_tydesc_glue(cx, v, t, abi::tydesc_field_take_glue);
1929 fn drop_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1930 if ty::type_needs_drop(bcx_tcx(cx), t) {
1931 ret call_tydesc_glue(cx, v, t, abi::tydesc_field_drop_glue);
1936 fn drop_ty_immediate(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1937 alt ty::struct(bcx_tcx(bcx), t) {
1938 ty::ty_uniq(_) | ty::ty_vec(_) | ty::ty_str. {
1939 ret free_ty(bcx, v, t);
1941 ty::ty_box(_) { ret decr_refcnt_maybe_free(bcx, v, t); }
1945 fn take_ty_immediate(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
1946 alt ty::struct(bcx_tcx(bcx), t) {
1947 ty::ty_box(_) { ret rslt(incr_refcnt_of_boxed(bcx, v), v); }
1949 check trans_uniq::type_is_unique_box(bcx, t);
1950 ret trans_uniq::duplicate(bcx, v, t);
1952 ty::ty_str. | ty::ty_vec(_) { ret tvec::duplicate(bcx, v, t); }
1953 _ { ret rslt(bcx, v); }
1957 fn free_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1958 if ty::type_needs_drop(bcx_tcx(cx), t) {
1959 ret call_tydesc_glue(cx, v, t, abi::tydesc_field_free_glue);
1964 fn call_memmove(cx: @block_ctxt, dst: ValueRef, src: ValueRef,
1965 n_bytes: ValueRef) -> result {
1966 // TODO: Provide LLVM with better alignment information when the alignment
1967 // is statically known (it must be nothing more than a constant int, or
1968 // LLVM complains -- not even a constant element of a tydesc works).
1970 let ccx = bcx_ccx(cx);
1971 let key = alt ccx.sess.get_targ_cfg().arch {
1972 session::arch_x86. | session::arch_arm. { "llvm.memmove.p0i8.p0i8.i32" }
1973 session::arch_x86_64. { "llvm.memmove.p0i8.p0i8.i64" }
1975 let i = ccx.intrinsics;
1976 assert (i.contains_key(key));
1977 let memmove = i.get(key);
1978 let src_ptr = PointerCast(cx, src, T_ptr(T_i8()));
1979 let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
1980 // FIXME #1184: Resource flag is larger than necessary
1981 let size = IntCast(cx, n_bytes, ccx.int_type);
1982 let align = C_i32(1i32);
1983 let volatile = C_bool(false);
1984 let ret_val = Call(cx, memmove, [dst_ptr, src_ptr, size,
1986 ret rslt(cx, ret_val);
1989 fn call_bzero(cx: @block_ctxt, dst: ValueRef, n_bytes: ValueRef,
1990 align_bytes: ValueRef) -> result {
1991 // FIXME: switch to the 64-bit variant when on such a platform.
1992 let ccx = bcx_ccx(cx);
1993 let i = ccx.intrinsics;
1994 assert (i.contains_key("llvm.memset.p0i8.i32"));
1995 let memset = i.get("llvm.memset.p0i8.i32");
1996 let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
1997 let size = IntCast(cx, n_bytes, T_i32());
1999 if lib::llvm::llvm::LLVMIsConstant(align_bytes) == True {
2000 IntCast(cx, align_bytes, T_i32())
2001 } else { IntCast(cx, C_int(ccx, 0), T_i32()) };
2002 let volatile = C_bool(false);
2004 Call(cx, memset, [dst_ptr, C_u8(0u), size, align, volatile]));
2007 fn memmove_ty(bcx: @block_ctxt, dst: ValueRef, src: ValueRef, t: ty::t) ->
2009 let ccx = bcx_ccx(bcx);
2010 if check type_has_static_size(ccx, t) {
2011 if ty::type_is_structural(bcx_tcx(bcx), t) {
2013 let llsz = llsize_of(ccx, type_of(ccx, sp, t));
2014 ret call_memmove(bcx, dst, src, llsz).bcx;
2016 Store(bcx, Load(bcx, src), dst);
2020 let {bcx, val: llsz} = size_of(bcx, t);
2021 ret call_memmove(bcx, dst, src, llsz).bcx;
2024 tag copy_action { INIT; DROP_EXISTING; }
2026 // These are the types that are passed by pointer.
2027 fn type_is_structural_or_param(tcx: ty::ctxt, t: ty::t) -> bool {
2028 if ty::type_is_structural(tcx, t) { ret true; }
2029 alt ty::struct(tcx, t) {
2030 ty::ty_param(_, _) { ret true; }
2035 fn copy_val(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2036 src: ValueRef, t: ty::t) -> @block_ctxt {
2037 if action == DROP_EXISTING &&
2038 (type_is_structural_or_param(bcx_tcx(cx), t) ||
2039 ty::type_is_unique(bcx_tcx(cx), t)) {
2040 let do_copy_cx = new_sub_block_ctxt(cx, "do_copy");
2041 let next_cx = new_sub_block_ctxt(cx, "next");
2042 let dstcmp = load_if_immediate(cx, dst, t);
2043 let self_assigning =
2044 ICmp(cx, lib::llvm::LLVMIntNE,
2045 PointerCast(cx, dstcmp, val_ty(src)), src);
2046 CondBr(cx, self_assigning, do_copy_cx.llbb, next_cx.llbb);
2047 do_copy_cx = copy_val_no_check(do_copy_cx, action, dst, src, t);
2048 Br(do_copy_cx, next_cx.llbb);
2051 ret copy_val_no_check(cx, action, dst, src, t);
2054 fn copy_val_no_check(bcx: @block_ctxt, action: copy_action, dst: ValueRef,
2055 src: ValueRef, t: ty::t) -> @block_ctxt {
2056 let ccx = bcx_ccx(bcx), bcx = bcx;
2057 if ty::type_is_scalar(ccx.tcx, t) || ty::type_is_native(ccx.tcx, t) {
2058 Store(bcx, src, dst);
2061 if ty::type_is_nil(ccx.tcx, t) || ty::type_is_bot(ccx.tcx, t) { ret bcx; }
2062 if ty::type_is_boxed(ccx.tcx, t) || ty::type_is_vec(ccx.tcx, t) ||
2063 ty::type_is_unique_box(ccx.tcx, t) {
2064 if action == DROP_EXISTING { bcx = drop_ty(bcx, dst, t); }
2065 Store(bcx, src, dst);
2066 ret take_ty(bcx, dst, t);
2068 if type_is_structural_or_param(ccx.tcx, t) {
2069 if action == DROP_EXISTING { bcx = drop_ty(bcx, dst, t); }
2070 bcx = memmove_ty(bcx, dst, src, t);
2071 ret take_ty(bcx, dst, t);
2073 ccx.sess.bug("unexpected type in trans::copy_val_no_check: " +
2074 ty_to_str(ccx.tcx, t));
2078 // This works like copy_val, except that it deinitializes the source.
2079 // Since it needs to zero out the source, src also needs to be an lval.
2080 // FIXME: We always zero out the source. Ideally we would detect the
2081 // case where a variable is always deinitialized by block exit and thus
2082 // doesn't need to be dropped.
2083 fn move_val(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2084 src: lval_result, t: ty::t) -> @block_ctxt {
2085 let src_val = src.val;
2086 let tcx = bcx_tcx(cx), cx = cx;
2087 if ty::type_is_scalar(tcx, t) || ty::type_is_native(tcx, t) {
2088 if src.kind == owned { src_val = Load(cx, src_val); }
2089 Store(cx, src_val, dst);
2091 } else if ty::type_is_nil(tcx, t) || ty::type_is_bot(tcx, t) {
2093 } else if ty::type_is_boxed(tcx, t) || ty::type_is_unique(tcx, t) {
2094 if src.kind == owned { src_val = Load(cx, src_val); }
2095 if action == DROP_EXISTING { cx = drop_ty(cx, dst, t); }
2096 Store(cx, src_val, dst);
2097 if src.kind == owned { ret zero_alloca(cx, src.val, t); }
2098 // If we're here, it must be a temporary.
2099 revoke_clean(cx, src_val);
2101 } else if type_is_structural_or_param(tcx, t) {
2102 if action == DROP_EXISTING { cx = drop_ty(cx, dst, t); }
2103 cx = memmove_ty(cx, dst, src_val, t);
2104 if src.kind == owned { ret zero_alloca(cx, src_val, t); }
2105 // If we're here, it must be a temporary.
2106 revoke_clean(cx, src_val);
2109 /* FIXME: suggests a type constraint */
2110 bcx_ccx(cx).sess.bug("unexpected type in trans::move_val: " +
2114 fn store_temp_expr(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2115 src: lval_result, t: ty::t, last_use: bool)
2117 // Lvals in memory are not temporaries. Copy them.
2118 if src.kind != temporary && !last_use {
2119 let v = src.kind == owned ? load_if_immediate(cx, src.val, t)
2121 ret copy_val(cx, action, dst, v, t);
2123 ret move_val(cx, action, dst, src, t);
2126 fn trans_crate_lit(cx: @crate_ctxt, lit: ast::lit) -> ValueRef {
2128 ast::lit_int(i, t) { C_integral(T_int_ty(cx, t), i as u64, True) }
2129 ast::lit_uint(u, t) { C_integral(T_uint_ty(cx, t), u, False) }
2130 ast::lit_float(fs, t) { C_floating(fs, T_float_ty(cx, t)) }
2131 ast::lit_bool(b) { C_bool(b) }
2132 ast::lit_nil. { C_nil() }
2134 cx.sess.span_unimpl(lit.span, "unique string in this context");
2139 fn trans_lit(cx: @block_ctxt, lit: ast::lit, dest: dest) -> @block_ctxt {
2140 if dest == ignore { ret cx; }
2142 ast::lit_str(s) { ret tvec::trans_str(cx, s, dest); }
2144 ret store_in_dest(cx, trans_crate_lit(bcx_ccx(cx), lit), dest);
2150 // Converts an annotation to a type
2151 fn node_id_type(cx: @crate_ctxt, id: ast::node_id) -> ty::t {
2152 ret ty::node_id_to_monotype(cx.tcx, id);
2155 fn node_type(cx: @crate_ctxt, sp: span, id: ast::node_id) -> TypeRef {
2156 let ty = node_id_type(cx, id);
2157 // How to make this a precondition?
2158 // FIXME (again, would require a predicate that implies
2159 // another predicate)
2160 check (type_has_static_size(cx, ty));
2164 fn trans_unary(bcx: @block_ctxt, op: ast::unop, e: @ast::expr,
2165 id: ast::node_id, dest: dest) -> @block_ctxt {
2166 if dest == ignore { ret trans_expr(bcx, e, ignore); }
2167 let e_ty = ty::expr_ty(bcx_tcx(bcx), e);
2170 let {bcx, val} = trans_temp_expr(bcx, e);
2171 ret store_in_dest(bcx, Not(bcx, val), dest);
2174 let {bcx, val} = trans_temp_expr(bcx, e);
2175 let neg = if ty::type_is_fp(bcx_tcx(bcx), e_ty) {
2177 } else { Neg(bcx, val) };
2178 ret store_in_dest(bcx, neg, dest);
2181 let {bcx, box, body} = trans_malloc_boxed(bcx, e_ty);
2182 add_clean_free(bcx, box, false);
2183 // Cast the body type to the type of the value. This is needed to
2184 // make tags work, since tags have a different LLVM type depending
2185 // on whether they're boxed or not.
2186 let ccx = bcx_ccx(bcx);
2187 if check type_has_static_size(ccx, e_ty) {
2189 let llety = T_ptr(type_of(ccx, e_sp, e_ty));
2190 body = PointerCast(bcx, body, llety);
2192 bcx = trans_expr_save_in(bcx, e, body);
2193 revoke_clean(bcx, box);
2194 ret store_in_dest(bcx, box, dest);
2197 ret trans_uniq::trans_uniq(bcx, e, id, dest);
2200 bcx_ccx(bcx).sess.bug("deref expressions should have been \
2201 translated using trans_lval(), not \
2207 fn trans_compare(cx: @block_ctxt, op: ast::binop, lhs: ValueRef,
2208 _lhs_t: ty::t, rhs: ValueRef, rhs_t: ty::t) -> result {
2209 if ty::type_is_scalar(bcx_tcx(cx), rhs_t) {
2210 let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, op);
2211 ret rslt(rs.bcx, rs.val);
2214 // Determine the operation we need.
2217 ast::eq. | ast::ne. { llop = C_u8(abi::cmp_glue_op_eq); }
2218 ast::lt. | ast::ge. { llop = C_u8(abi::cmp_glue_op_lt); }
2219 ast::le. | ast::gt. { llop = C_u8(abi::cmp_glue_op_le); }
2222 let rs = call_cmp_glue(cx, lhs, rhs, rhs_t, llop);
2224 // Invert the result if necessary.
2226 ast::eq. | ast::lt. | ast::le. { ret rslt(rs.bcx, rs.val); }
2227 ast::ne. | ast::ge. | ast::gt. {
2228 ret rslt(rs.bcx, Not(rs.bcx, rs.val));
2233 // Important to get types for both lhs and rhs, because one might be _|_
2234 // and the other not.
2235 fn trans_eager_binop(cx: @block_ctxt, op: ast::binop, lhs: ValueRef,
2236 lhs_t: ty::t, rhs: ValueRef, rhs_t: ty::t, dest: dest)
2238 if dest == ignore { ret cx; }
2240 if ty::type_is_bot(bcx_tcx(cx), intype) { intype = rhs_t; }
2241 let is_float = ty::type_is_fp(bcx_tcx(cx), intype);
2243 if op == ast::add && ty::type_is_sequence(bcx_tcx(cx), intype) {
2244 ret tvec::trans_add(cx, intype, lhs, rhs, dest);
2246 let cx = cx, val = alt op {
2248 if is_float { FAdd(cx, lhs, rhs) }
2249 else { Add(cx, lhs, rhs) }
2252 if is_float { FSub(cx, lhs, rhs) }
2253 else { Sub(cx, lhs, rhs) }
2256 if is_float { FMul(cx, lhs, rhs) }
2257 else { Mul(cx, lhs, rhs) }
2260 if is_float { FDiv(cx, lhs, rhs) }
2261 else if ty::type_is_signed(bcx_tcx(cx), intype) {
2263 } else { UDiv(cx, lhs, rhs) }
2266 if is_float { FRem(cx, lhs, rhs) }
2267 else if ty::type_is_signed(bcx_tcx(cx), intype) {
2269 } else { URem(cx, lhs, rhs) }
2271 ast::bitor. { Or(cx, lhs, rhs) }
2272 ast::bitand. { And(cx, lhs, rhs) }
2273 ast::bitxor. { Xor(cx, lhs, rhs) }
2274 ast::lsl. { Shl(cx, lhs, rhs) }
2275 ast::lsr. { LShr(cx, lhs, rhs) }
2276 ast::asr. { AShr(cx, lhs, rhs) }
2278 let cmpr = trans_compare(cx, op, lhs, lhs_t, rhs, rhs_t);
2283 ret store_in_dest(cx, val, dest);
2286 fn trans_assign_op(bcx: @block_ctxt, op: ast::binop, dst: @ast::expr,
2287 src: @ast::expr) -> @block_ctxt {
2288 let tcx = bcx_tcx(bcx);
2289 let t = ty::expr_ty(tcx, src);
2290 let lhs_res = trans_lval(bcx, dst);
2291 assert (lhs_res.kind == owned);
2292 // Special case for `+= [x]`
2293 alt ty::struct(tcx, t) {
2296 ast::expr_vec(args, _) {
2297 ret tvec::trans_append_literal(lhs_res.bcx,
2298 lhs_res.val, t, args);
2305 let {bcx, val: rhs_val} = trans_temp_expr(lhs_res.bcx, src);
2306 if ty::type_is_sequence(tcx, t) {
2309 ret tvec::trans_append(bcx, t, lhs_res.val, rhs_val);
2314 ret trans_eager_binop(bcx, op, Load(bcx, lhs_res.val), t, rhs_val, t,
2315 save_in(lhs_res.val));
2318 fn autoderef(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result_t {
2319 let v1: ValueRef = v;
2321 let ccx = bcx_ccx(cx);
2324 alt ty::struct(ccx.tcx, t1) {
2326 let body = GEPi(cx, v1, [0, abi::box_rc_field_body]);
2329 // Since we're changing levels of box indirection, we may have
2330 // to cast this pointer, since statically-sized tag types have
2331 // different types depending on whether they're behind a box
2333 if check type_has_static_size(ccx, t1) {
2334 let llty = type_of(ccx, sp, t1);
2335 v1 = PointerCast(cx, body, T_ptr(llty));
2336 } else { v1 = body; }
2339 check trans_uniq::type_is_unique_box(cx, t1);
2340 let derefed = trans_uniq::autoderef(cx, v1, t1);
2344 ty::ty_res(did, inner, tps) {
2345 t1 = ty::substitute_type_params(ccx.tcx, tps, inner);
2346 v1 = GEPi(cx, v1, [0, 1]);
2348 ty::ty_tag(did, tps) {
2349 let variants = ty::tag_variants(ccx.tcx, did);
2350 if vec::len(*variants) != 1u ||
2351 vec::len(variants[0].args) != 1u {
2355 ty::substitute_type_params(ccx.tcx, tps, variants[0].args[0]);
2356 if check type_has_static_size(ccx, t1) {
2357 v1 = PointerCast(cx, v1, T_ptr(type_of(ccx, sp, t1)));
2358 } else { } // FIXME: typestate hack
2362 v1 = load_if_immediate(cx, v1, t1);
2364 ret {bcx: cx, val: v1, ty: t1};
2367 fn trans_lazy_binop(bcx: @block_ctxt, op: ast::binop, a: @ast::expr,
2368 b: @ast::expr, dest: dest) -> @block_ctxt {
2369 let is_and = alt op { ast::and. { true } ast::or. { false } };
2370 let lhs_res = trans_temp_expr(bcx, a);
2371 if lhs_res.bcx.unreachable { ret lhs_res.bcx; }
2372 let rhs_cx = new_scope_block_ctxt(lhs_res.bcx, "rhs");
2373 let rhs_res = trans_temp_expr(rhs_cx, b);
2375 let lhs_past_cx = new_scope_block_ctxt(lhs_res.bcx, "lhs");
2376 // The following line ensures that any cleanups for rhs
2377 // are done within the block for rhs. This is necessary
2378 // because and/or are lazy. So the rhs may never execute,
2379 // and the cleanups can't be pushed into later code.
2380 let rhs_bcx = trans_block_cleanups(rhs_res.bcx, rhs_cx);
2382 CondBr(lhs_res.bcx, lhs_res.val, rhs_cx.llbb, lhs_past_cx.llbb);
2384 CondBr(lhs_res.bcx, lhs_res.val, lhs_past_cx.llbb, rhs_cx.llbb);
2387 let join_cx = new_sub_block_ctxt(bcx, "join");
2388 Br(lhs_past_cx, join_cx.llbb);
2389 if rhs_bcx.unreachable {
2390 ret store_in_dest(join_cx, C_bool(!is_and), dest);
2392 Br(rhs_bcx, join_cx.llbb);
2393 let phi = Phi(join_cx, T_bool(), [C_bool(!is_and), rhs_res.val],
2394 [lhs_past_cx.llbb, rhs_bcx.llbb]);
2395 ret store_in_dest(join_cx, phi, dest);
2398 fn trans_binary(cx: @block_ctxt, op: ast::binop, a: @ast::expr, b: @ast::expr,
2399 dest: dest) -> @block_ctxt {
2400 // First couple cases are lazy:
2402 ast::and. | ast::or. {
2403 ret trans_lazy_binop(cx, op, a, b, dest);
2406 // Remaining cases are eager:
2407 let lhs = trans_temp_expr(cx, a);
2408 let rhs = trans_temp_expr(lhs.bcx, b);
2409 ret trans_eager_binop(rhs.bcx, op, lhs.val,
2410 ty::expr_ty(bcx_tcx(cx), a), rhs.val,
2411 ty::expr_ty(bcx_tcx(cx), b), dest);
2417 by_val(@mutable ValueRef);
2422 fn empty_dest_cell() -> @mutable ValueRef {
2423 ret @mutable llvm::LLVMGetUndef(T_nil());
2426 fn dup_for_join(dest: dest) -> dest {
2428 by_val(_) { by_val(empty_dest_cell()) }
2433 fn join_returns(parent_cx: @block_ctxt, in_cxs: [@block_ctxt],
2434 in_ds: [dest], out_dest: dest) -> @block_ctxt {
2435 let out = new_sub_block_ctxt(parent_cx, "join");
2436 let reachable = false, i = 0u, phi = none;
2438 if !cx.unreachable {
2443 if option::is_none(phi) {
2444 phi = some(EmptyPhi(out, val_ty(*cell)));
2446 AddIncomingToPhi(option::get(phi), *cell, cx.llbb);
2457 by_val(cell) { *cell = option::get(phi); }
2464 // Used to put an immediate value in a dest.
2465 fn store_in_dest(bcx: @block_ctxt, val: ValueRef, dest: dest) -> @block_ctxt {
2468 by_val(cell) { *cell = val; }
2469 save_in(addr) { Store(bcx, val, addr); }
2474 fn get_dest_addr(dest: dest) -> ValueRef {
2475 alt dest { save_in(a) { a } }
2478 fn trans_if(cx: @block_ctxt, cond: @ast::expr, thn: ast::blk,
2479 els: option::t<@ast::expr>, dest: dest)
2481 let {bcx, val: cond_val} = trans_temp_expr(cx, cond);
2483 let then_dest = dup_for_join(dest);
2484 let else_dest = dup_for_join(dest);
2485 let then_cx = new_scope_block_ctxt(bcx, "then");
2486 let else_cx = new_scope_block_ctxt(bcx, "else");
2487 CondBr(bcx, cond_val, then_cx.llbb, else_cx.llbb);
2488 then_cx = trans_block_dps(then_cx, thn, then_dest);
2489 // Calling trans_block directly instead of trans_expr
2490 // because trans_expr will create another scope block
2491 // context for the block, but we've already got the
2496 ast::expr_if(_, _, _) {
2497 let elseif_blk = ast_util::block_from_expr(elexpr);
2498 else_cx = trans_block_dps(else_cx, elseif_blk, else_dest);
2500 ast::expr_block(blk) {
2501 else_cx = trans_block_dps(else_cx, blk, else_dest);
2507 ret join_returns(cx, [then_cx, else_cx], [then_dest, else_dest], dest);
2510 fn trans_for(cx: @block_ctxt, local: @ast::local, seq: @ast::expr,
2511 body: ast::blk) -> @block_ctxt {
2512 fn inner(bcx: @block_ctxt, local: @ast::local, curr: ValueRef, t: ty::t,
2513 body: ast::blk, outer_next_cx: @block_ctxt) -> @block_ctxt {
2514 let next_cx = new_sub_block_ctxt(bcx, "next");
2516 new_loop_scope_block_ctxt(bcx, option::some(next_cx),
2517 outer_next_cx, "for loop scope");
2518 Br(bcx, scope_cx.llbb);
2519 let curr = PointerCast(bcx, curr, T_ptr(type_of_or_i8(bcx, t)));
2520 let bcx = trans_alt::bind_irrefutable_pat(scope_cx, local.node.pat,
2522 bcx = trans_block_dps(bcx, body, ignore);
2523 Br(bcx, next_cx.llbb);
2526 let ccx = bcx_ccx(cx);
2527 let next_cx = new_sub_block_ctxt(cx, "next");
2528 let seq_ty = ty::expr_ty(bcx_tcx(cx), seq);
2529 let {bcx: bcx, val: seq} = trans_temp_expr(cx, seq);
2530 let seq = PointerCast(bcx, seq, T_ptr(ccx.opaque_vec_type));
2531 let fill = tvec::get_fill(bcx, seq);
2532 if ty::type_is_str(bcx_tcx(bcx), seq_ty) {
2533 fill = Sub(bcx, fill, C_int(ccx, 1));
2535 let bcx = tvec::iter_vec_raw(bcx, seq, seq_ty, fill,
2536 bind inner(_, local, _, _, body, next_cx));
2537 Br(bcx, next_cx.llbb);
2541 fn trans_while(cx: @block_ctxt, cond: @ast::expr, body: ast::blk)
2543 let next_cx = new_sub_block_ctxt(cx, "while next");
2545 new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
2547 let body_cx = new_scope_block_ctxt(cond_cx, "while loop body");
2548 let body_end = trans_block(body_cx, body);
2549 let cond_res = trans_temp_expr(cond_cx, cond);
2550 Br(body_end, cond_cx.llbb);
2551 let cond_bcx = trans_block_cleanups(cond_res.bcx, cond_cx);
2552 CondBr(cond_bcx, cond_res.val, body_cx.llbb, next_cx.llbb);
2553 Br(cx, cond_cx.llbb);
2557 fn trans_do_while(cx: @block_ctxt, body: ast::blk, cond: @ast::expr) ->
2559 let next_cx = new_sub_block_ctxt(cx, "next");
2561 new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
2562 "do-while loop body");
2563 let body_end = trans_block(body_cx, body);
2564 let cond_cx = new_scope_block_ctxt(body_cx, "do-while cond");
2565 Br(body_end, cond_cx.llbb);
2566 let cond_res = trans_temp_expr(cond_cx, cond);
2567 let cond_bcx = trans_block_cleanups(cond_res.bcx, cond_cx);
2568 CondBr(cond_bcx, cond_res.val, body_cx.llbb, next_cx.llbb);
2569 Br(cx, body_cx.llbb);
2573 type generic_info = {
2575 static_tis: [option::t<@tydesc_info>],
2576 tydescs: [ValueRef],
2577 param_bounds: @[ty::param_bounds],
2578 origins: option::t<typeck::dict_res>
2582 temporary; //< Temporary value passed by value if of immediate type
2583 owned; //< Non-temporary value passed by pointer
2584 owned_imm; //< Non-temporary value passed by value
2586 type local_var_result = {val: ValueRef, kind: lval_kind};
2587 type lval_result = {bcx: @block_ctxt, val: ValueRef, kind: lval_kind};
2592 dict_env(ValueRef, ValueRef);
2594 type lval_maybe_callee = {bcx: @block_ctxt,
2598 generic: option::t<generic_info>};
2600 fn null_env_ptr(bcx: @block_ctxt) -> ValueRef {
2601 C_null(T_opaque_cbox_ptr(bcx_ccx(bcx)))
2604 fn lval_from_local_var(bcx: @block_ctxt, r: local_var_result) -> lval_result {
2605 ret { bcx: bcx, val: r.val, kind: r.kind };
2608 fn lval_owned(bcx: @block_ctxt, val: ValueRef) -> lval_result {
2609 ret {bcx: bcx, val: val, kind: owned};
2611 fn lval_temp(bcx: @block_ctxt, val: ValueRef) -> lval_result {
2612 ret {bcx: bcx, val: val, kind: temporary};
2615 fn lval_no_env(bcx: @block_ctxt, val: ValueRef, kind: lval_kind)
2616 -> lval_maybe_callee {
2617 ret {bcx: bcx, val: val, kind: kind, env: is_closure, generic: none};
2620 fn trans_external_path(cx: @block_ctxt, did: ast::def_id,
2621 tpt: ty::ty_param_bounds_and_ty) -> ValueRef {
2622 let lcx = cx.fcx.lcx;
2623 let name = csearch::get_symbol(lcx.ccx.sess.get_cstore(), did);
2624 ret get_extern_const(lcx.ccx.externs, lcx.ccx.llmod, name,
2625 type_of_ty_param_bounds_and_ty(lcx, cx.sp, tpt));
2628 fn lval_static_fn(bcx: @block_ctxt, fn_id: ast::def_id, id: ast::node_id)
2629 -> lval_maybe_callee {
2630 let ccx = bcx_ccx(bcx);
2631 let tpt = ty::lookup_item_type(ccx.tcx, fn_id);
2632 let val = if fn_id.crate == ast::local_crate {
2633 // Internal reference.
2634 assert (ccx.item_ids.contains_key(fn_id.node));
2635 ccx.item_ids.get(fn_id.node)
2637 // External reference.
2638 trans_external_path(bcx, fn_id, tpt)
2640 let tys = ty::node_id_to_type_params(ccx.tcx, id);
2641 let gen = none, bcx = bcx;
2642 if vec::len(tys) != 0u {
2643 let tydescs = [], tis = [];
2645 // TODO: Doesn't always escape.
2647 let td = get_tydesc(bcx, t, true, tps_normal, ti).result;
2650 tydescs += [td.val];
2652 gen = some({item_type: tpt.ty,
2655 param_bounds: tpt.bounds,
2656 origins: ccx.dict_map.find(id)});
2658 ret {bcx: bcx, val: val, kind: owned, env: null_env, generic: gen};
2661 fn lookup_discriminant(lcx: @local_ctxt, vid: ast::def_id) -> ValueRef {
2663 alt ccx.discrims.find(vid) {
2665 // It's an external discriminant that we haven't seen yet.
2666 assert (vid.crate != ast::local_crate);
2667 let sym = csearch::get_symbol(lcx.ccx.sess.get_cstore(), vid);
2671 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
2673 llvm::LLVMSetLinkage(gvar,
2674 lib::llvm::LLVMExternalLinkage as llvm::Linkage);
2675 llvm::LLVMSetGlobalConstant(gvar, True);
2676 lcx.ccx.discrims.insert(vid, gvar);
2679 some(llval) { ret llval; }
2683 fn trans_local_var(cx: @block_ctxt, def: ast::def) -> local_var_result {
2684 fn take_local(table: hashmap<ast::node_id, local_val>,
2685 id: ast::node_id) -> local_var_result {
2686 alt table.find(id) {
2687 some(local_mem(v)) { {val: v, kind: owned} }
2688 some(local_imm(v)) { {val: v, kind: owned_imm} }
2692 ast::def_upvar(did, _, _) {
2693 assert (cx.fcx.llupvars.contains_key(did.node));
2694 ret { val: cx.fcx.llupvars.get(did.node), kind: owned };
2696 ast::def_arg(did, _) {
2697 ret take_local(cx.fcx.llargs, did.node);
2699 ast::def_local(did, _) | ast::def_binding(did) {
2700 ret take_local(cx.fcx.lllocals, did.node);
2702 ast::def_obj_field(did, _) {
2703 assert (cx.fcx.llobjfields.contains_key(did.node));
2704 ret { val: cx.fcx.llobjfields.get(did.node), kind: owned };
2706 ast::def_self(did) {
2707 let slf = option::get(cx.fcx.llself);
2708 let ptr = PointerCast(cx, slf.v, T_ptr(type_of_or_i8(cx, slf.t)));
2709 ret {val: ptr, kind: owned};
2712 bcx_ccx(cx).sess.span_unimpl
2713 (cx.sp, "unsupported def type in trans_local_def");
2718 fn trans_path(cx: @block_ctxt, p: @ast::path, id: ast::node_id)
2719 -> lval_maybe_callee {
2720 ret trans_var(cx, p.span, bcx_tcx(cx).def_map.get(id), id);
2723 fn trans_var(cx: @block_ctxt, sp: span, def: ast::def, id: ast::node_id)
2724 -> lval_maybe_callee {
2725 let ccx = bcx_ccx(cx);
2727 ast::def_fn(did, _) | ast::def_native_fn(did, _) {
2728 ret lval_static_fn(cx, did, id);
2730 ast::def_variant(tid, vid) {
2731 if vec::len(ty::tag_variant_with_id(ccx.tcx, tid, vid).args) > 0u {
2733 ret lval_static_fn(cx, vid, id);
2736 let tag_ty = node_id_type(ccx, id);
2737 let alloc_result = alloc_ty(cx, tag_ty);
2738 let lltagblob = alloc_result.val;
2739 let lltagty = type_of_tag(ccx, sp, tid, tag_ty);
2740 let bcx = alloc_result.bcx;
2741 let lltagptr = PointerCast(bcx, lltagblob, T_ptr(lltagty));
2742 let lldiscrimptr = GEPi(bcx, lltagptr, [0, 0]);
2743 let d = if vec::len(*ty::tag_variants(ccx.tcx, tid)) != 1u {
2744 let lldiscrim_gv = lookup_discriminant(bcx.fcx.lcx, vid);
2745 let lldiscrim = Load(bcx, lldiscrim_gv);
2747 } else { C_int(ccx, 0) };
2748 Store(bcx, d, lldiscrimptr);
2749 ret lval_no_env(bcx, lltagptr, temporary);
2752 ast::def_const(did) {
2753 if did.crate == ast::local_crate {
2754 assert (ccx.consts.contains_key(did.node));
2755 ret lval_no_env(cx, ccx.consts.get(did.node), owned);
2757 let tp = ty::node_id_to_monotype(ccx.tcx, id);
2758 let val = trans_external_path(cx, did, {bounds: @[], ty: tp});
2759 ret lval_no_env(cx, load_if_immediate(cx, val, tp), owned_imm);
2763 let loc = trans_local_var(cx, def);
2764 ret lval_no_env(cx, loc.val, loc.kind);
2769 fn trans_object_field(bcx: @block_ctxt, o: @ast::expr, field: ast::ident)
2770 -> {bcx: @block_ctxt, mthptr: ValueRef, objptr: ValueRef} {
2771 let {bcx, val} = trans_temp_expr(bcx, o);
2772 let {bcx, val, ty} = autoderef(bcx, val, ty::expr_ty(bcx_tcx(bcx), o));
2773 ret trans_object_field_inner(bcx, val, field, ty);
2776 fn trans_object_field_inner(bcx: @block_ctxt, o: ValueRef,
2777 field: ast::ident, o_ty: ty::t)
2778 -> {bcx: @block_ctxt, mthptr: ValueRef, objptr: ValueRef} {
2779 let ccx = bcx_ccx(bcx), tcx = ccx.tcx;
2780 let mths = alt ty::struct(tcx, o_ty) { ty::ty_obj(ms) { ms } };
2782 let ix = option::get(ty::method_idx(field, mths));
2783 let vtbl = Load(bcx, GEPi(bcx, o, [0, abi::obj_field_vtbl]));
2784 let vtbl_type = T_ptr(T_array(T_ptr(T_nil()), ix + 1u));
2785 vtbl = PointerCast(bcx, vtbl, vtbl_type);
2787 let v = GEPi(bcx, vtbl, [0, ix as int]);
2788 let fn_ty: ty::t = ty::mk_fn(tcx, mths[ix].fty);
2789 let ret_ty = ty::ty_fn_ret(tcx, fn_ty);
2790 // FIXME: constrain ty_obj?
2791 let ll_fn_ty = type_of_fn(ccx, bcx.sp, true,
2792 ty::ty_fn_args(tcx, fn_ty), ret_ty, []);
2793 v = Load(bcx, PointerCast(bcx, v, T_ptr(T_ptr(ll_fn_ty))));
2794 ret {bcx: bcx, mthptr: v, objptr: o};
2798 fn trans_rec_field(bcx: @block_ctxt, base: @ast::expr,
2799 field: ast::ident) -> lval_result {
2800 let {bcx, val} = trans_temp_expr(bcx, base);
2801 let {bcx, val, ty} = autoderef(bcx, val, ty::expr_ty(bcx_tcx(bcx), base));
2802 let fields = alt ty::struct(bcx_tcx(bcx), ty) { ty::ty_rec(fs) { fs } };
2803 let ix = option::get(ty::field_idx(field, fields));
2805 check type_is_tup_like(bcx, ty);
2806 let {bcx, val} = GEP_tup_like(bcx, ty, val, [0, ix as int]);
2807 ret {bcx: bcx, val: val, kind: owned};
2810 fn trans_index(cx: @block_ctxt, sp: span, base: @ast::expr, idx: @ast::expr,
2811 id: ast::node_id) -> lval_result {
2812 // Is this an interior vector?
2813 let base_ty = ty::expr_ty(bcx_tcx(cx), base);
2814 let exp = trans_temp_expr(cx, base);
2815 let lv = autoderef(exp.bcx, exp.val, base_ty);
2816 let ix = trans_temp_expr(lv.bcx, idx);
2819 let ccx = bcx_ccx(cx);
2821 // Cast to an LLVM integer. Rust is less strict than LLVM in this regard.
2823 let ix_size = llsize_of_real(bcx_ccx(cx), val_ty(ix.val));
2824 let int_size = llsize_of_real(bcx_ccx(cx), ccx.int_type);
2825 if ix_size < int_size {
2826 ix_val = ZExt(bcx, ix.val, ccx.int_type);
2827 } else if ix_size > int_size {
2828 ix_val = Trunc(bcx, ix.val, ccx.int_type);
2829 } else { ix_val = ix.val; }
2831 let unit_ty = node_id_type(bcx_ccx(cx), id);
2832 let unit_sz = size_of(bcx, unit_ty);
2834 maybe_name_value(bcx_ccx(cx), unit_sz.val, "unit_sz");
2835 let scaled_ix = Mul(bcx, ix_val, unit_sz.val);
2836 maybe_name_value(bcx_ccx(cx), scaled_ix, "scaled_ix");
2837 let lim = tvec::get_fill(bcx, v);
2838 let body = tvec::get_dataptr(bcx, v, type_of_or_i8(bcx, unit_ty));
2839 let bounds_check = ICmp(bcx, lib::llvm::LLVMIntULT, scaled_ix, lim);
2840 let fail_cx = new_sub_block_ctxt(bcx, "fail");
2841 let next_cx = new_sub_block_ctxt(bcx, "next");
2842 let ncx = bcx_ccx(next_cx);
2843 CondBr(bcx, bounds_check, next_cx.llbb, fail_cx.llbb);
2844 // fail: bad bounds check.
2846 trans_fail(fail_cx, some::<span>(sp), "bounds check");
2848 if check type_has_static_size(ncx, unit_ty) {
2849 let elt_1 = GEP(next_cx, body, [ix_val]);
2850 let llunitty = type_of(ncx, sp, unit_ty);
2851 PointerCast(next_cx, elt_1, T_ptr(llunitty))
2853 body = PointerCast(next_cx, body, T_ptr(T_i8()));
2854 GEP(next_cx, body, [scaled_ix])
2857 ret lval_owned(next_cx, elt);
2860 fn expr_is_lval(bcx: @block_ctxt, e: @ast::expr) -> bool {
2861 let ccx = bcx_ccx(bcx);
2862 ty::expr_is_lval(ccx.method_map, ccx.tcx, e)
2865 fn trans_callee(bcx: @block_ctxt, e: @ast::expr) -> lval_maybe_callee {
2867 ast::expr_path(p) { ret trans_path(bcx, p, e.id); }
2868 ast::expr_field(base, ident, _) {
2869 // Lval means this is a record field, so not a method
2870 if !expr_is_lval(bcx, e) {
2871 alt bcx_ccx(bcx).method_map.find(e.id) {
2872 some(typeck::method_static(did)) { // An impl method
2873 ret trans_impl::trans_static_callee(bcx, e, base, did);
2875 some(typeck::method_param(iid, off, p, b)) {
2876 ret trans_impl::trans_dict_callee(
2877 bcx, e, base, iid, off, p, b);
2879 none. { // An object method
2880 let of = trans_object_field(bcx, base, ident);
2881 ret {bcx: of.bcx, val: of.mthptr, kind: owned,
2882 env: obj_env(of.objptr), generic: none};
2889 let lv = trans_temp_lval(bcx, e);
2890 ret lval_no_env(lv.bcx, lv.val, lv.kind);
2893 // Use this when you know you are compiling an lval.
2894 // The additional bool returned indicates whether it's mem (that is
2895 // represented as an alloca or heap, hence needs a 'load' to be used as an
2897 fn trans_lval(cx: @block_ctxt, e: @ast::expr) -> lval_result {
2900 let v = trans_path(cx, p, e.id);
2901 ret lval_maybe_callee_to_lval(v, ty::expr_ty(bcx_tcx(cx), e));
2903 ast::expr_field(base, ident, _) {
2904 ret trans_rec_field(cx, base, ident);
2906 ast::expr_index(base, idx) {
2907 ret trans_index(cx, e.span, base, idx, e.id);
2909 ast::expr_unary(ast::deref., base) {
2910 let ccx = bcx_ccx(cx);
2911 let sub = trans_temp_expr(cx, base);
2912 let t = ty::expr_ty(ccx.tcx, base);
2914 alt ty::struct(ccx.tcx, t) {
2916 GEPi(sub.bcx, sub.val, [0, abi::box_rc_field_body])
2918 ty::ty_res(_, _, _) {
2919 GEPi(sub.bcx, sub.val, [0, 1])
2922 let ety = ty::expr_ty(ccx.tcx, e);
2925 if check type_has_static_size(ccx, ety) {
2926 T_ptr(type_of(ccx, sp, ety))
2927 } else { T_typaram_ptr(ccx.tn) };
2928 PointerCast(sub.bcx, sub.val, ellty)
2930 ty::ty_ptr(_) | ty::ty_uniq(_) { sub.val }
2932 ret lval_owned(sub.bcx, val);
2934 // This is a by-ref returning call. Regular calls are not lval
2935 ast::expr_call(f, args, _) {
2936 let cell = empty_dest_cell();
2937 let bcx = trans_call(cx, f, args, e.id, by_val(cell));
2938 ret lval_owned(bcx, *cell);
2940 _ { bcx_ccx(cx).sess.span_bug(e.span, "non-lval in trans_lval"); }
2944 fn maybe_add_env(bcx: @block_ctxt, c: lval_maybe_callee)
2945 -> (lval_kind, ValueRef) {
2947 is_closure. { (c.kind, c.val) }
2948 obj_env(_) | dict_env(_, _) {
2949 fail "Taking the value of a method does not work yet (issue #435)";
2952 let llfnty = llvm::LLVMGetElementType(val_ty(c.val));
2953 (temporary, create_real_fn_pair(bcx, llfnty, c.val,
2959 fn lval_maybe_callee_to_lval(c: lval_maybe_callee, ty: ty::t) -> lval_result {
2962 let n_args = vec::len(ty::ty_fn_args(bcx_tcx(c.bcx), ty));
2963 let args = vec::init_elt(none::<@ast::expr>, n_args);
2964 let space = alloc_ty(c.bcx, ty);
2965 let bcx = trans_closure::trans_bind_1(space.bcx, ty, c, args, ty,
2966 save_in(space.val));
2967 add_clean_temp(bcx, space.val, ty);
2968 ret {bcx: bcx, val: space.val, kind: temporary};
2971 let (kind, val) = maybe_add_env(c.bcx, c);
2972 ret {bcx: c.bcx, val: val, kind: kind};
2977 fn int_cast(bcx: @block_ctxt, lldsttype: TypeRef, llsrctype: TypeRef,
2978 llsrc: ValueRef, signed: bool) -> ValueRef {
2979 let srcsz = llvm::LLVMGetIntTypeWidth(llsrctype);
2980 let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype);
2981 ret if dstsz == srcsz {
2982 BitCast(bcx, llsrc, lldsttype)
2983 } else if srcsz > dstsz {
2984 TruncOrBitCast(bcx, llsrc, lldsttype)
2986 SExtOrBitCast(bcx, llsrc, lldsttype)
2987 } else { ZExtOrBitCast(bcx, llsrc, lldsttype) };
2990 fn float_cast(bcx: @block_ctxt, lldsttype: TypeRef, llsrctype: TypeRef,
2991 llsrc: ValueRef) -> ValueRef {
2992 let srcsz = lib::llvm::float_width(llsrctype);
2993 let dstsz = lib::llvm::float_width(lldsttype);
2994 ret if dstsz > srcsz {
2995 FPExt(bcx, llsrc, lldsttype)
2996 } else if srcsz > dstsz {
2997 FPTrunc(bcx, llsrc, lldsttype)
3001 fn trans_cast(cx: @block_ctxt, e: @ast::expr, id: ast::node_id,
3002 dest: dest) -> @block_ctxt {
3003 let ccx = bcx_ccx(cx);
3004 let e_res = trans_temp_expr(cx, e);
3005 let ll_t_in = val_ty(e_res.val);
3006 let t_in = ty::expr_ty(ccx.tcx, e);
3007 let t_out = node_id_type(ccx, id);
3008 // Check should be avoidable because it's a cast.
3009 // FIXME: Constrain types so as to avoid this check.
3010 check (type_has_static_size(ccx, t_out));
3011 let ll_t_out = type_of(ccx, e.span, t_out);
3013 tag kind { pointer; integral; float; other; }
3014 fn t_kind(tcx: ty::ctxt, t: ty::t) -> kind {
3015 ret if ty::type_is_fp(tcx, t) {
3017 } else if ty::type_is_native(tcx, t) ||
3018 ty::type_is_unsafe_ptr(tcx, t) {
3020 } else if ty::type_is_integral(tcx, t) {
3024 let k_in = t_kind(ccx.tcx, t_in);
3025 let k_out = t_kind(ccx.tcx, t_out);
3026 let s_in = k_in == integral && ty::type_is_signed(ccx.tcx, t_in);
3029 alt {in: k_in, out: k_out} {
3030 {in: integral., out: integral.} {
3031 int_cast(e_res.bcx, ll_t_out, ll_t_in, e_res.val, s_in)
3033 {in: float., out: float.} {
3034 float_cast(e_res.bcx, ll_t_out, ll_t_in, e_res.val)
3036 {in: integral., out: float.} {
3038 SIToFP(e_res.bcx, e_res.val, ll_t_out)
3039 } else { UIToFP(e_res.bcx, e_res.val, ll_t_out) }
3041 {in: float., out: integral.} {
3042 if ty::type_is_signed(ccx.tcx, t_out) {
3043 FPToSI(e_res.bcx, e_res.val, ll_t_out)
3044 } else { FPToUI(e_res.bcx, e_res.val, ll_t_out) }
3046 {in: integral., out: pointer.} {
3047 IntToPtr(e_res.bcx, e_res.val, ll_t_out)
3049 {in: pointer., out: integral.} {
3050 PtrToInt(e_res.bcx, e_res.val, ll_t_out)
3052 {in: pointer., out: pointer.} {
3053 PointerCast(e_res.bcx, e_res.val, ll_t_out)
3055 _ { ccx.sess.bug("Translating unsupported cast.") }
3057 ret store_in_dest(e_res.bcx, newval, dest);
3060 fn trans_arg_expr(cx: @block_ctxt, arg: ty::arg, lldestty0: TypeRef,
3061 &to_zero: [{v: ValueRef, t: ty::t}],
3062 &to_revoke: [{v: ValueRef, t: ty::t}], e: @ast::expr) ->
3064 let ccx = bcx_ccx(cx);
3065 let e_ty = ty::expr_ty(ccx.tcx, e);
3066 let is_bot = ty::type_is_bot(ccx.tcx, e_ty);
3067 let lv = trans_temp_lval(cx, e);
3071 // For values of type _|_, we generate an
3072 // "undef" value, as such a value should never
3073 // be inspected. It's important for the value
3074 // to have type lldestty0 (the callee's expected type).
3075 val = llvm::LLVMGetUndef(lldestty0);
3076 } else if arg.mode == ast::by_ref || arg.mode == ast::by_val {
3077 let copied = false, imm = ty::type_is_immediate(ccx.tcx, e_ty);
3078 if arg.mode == ast::by_ref && lv.kind != owned && imm {
3079 val = do_spill_noroot(bcx, val);
3082 if ccx.copy_map.contains_key(e.id) && lv.kind != temporary {
3084 let alloc = alloc_ty(bcx, e_ty);
3085 bcx = copy_val(alloc.bcx, INIT, alloc.val,
3086 load_if_immediate(alloc.bcx, val, e_ty), e_ty);
3088 } else { bcx = take_ty(bcx, val, e_ty); }
3089 add_clean(bcx, val, e_ty);
3091 if arg.mode == ast::by_val && (lv.kind == owned || !imm) {
3092 val = Load(bcx, val);
3094 } else if arg.mode == ast::by_copy {
3095 let {bcx: cx, val: alloc} = alloc_ty(bcx, e_ty);
3096 let last_use = ccx.last_uses.contains_key(e.id);
3098 if lv.kind == temporary { revoke_clean(bcx, val); }
3099 if lv.kind == owned || !ty::type_is_immediate(ccx.tcx, e_ty) {
3100 bcx = memmove_ty(bcx, alloc, val, e_ty);
3101 if last_use && ty::type_needs_drop(ccx.tcx, e_ty) {
3102 bcx = zero_alloca(bcx, val, e_ty);
3104 } else { Store(bcx, val, alloc); }
3106 if lv.kind != temporary && !last_use {
3107 bcx = take_ty(bcx, val, e_ty);
3109 } else if ty::type_is_immediate(ccx.tcx, e_ty) && lv.kind != owned {
3110 let r = do_spill(bcx, val, e_ty);
3115 if !is_bot && ty::type_contains_params(ccx.tcx, arg.ty) {
3116 let lldestty = lldestty0;
3117 val = PointerCast(bcx, val, lldestty);
3120 // Collect arg for later if it happens to be one we've moving out.
3121 if arg.mode == ast::by_move {
3122 if lv.kind == owned {
3123 // Use actual ty, not declared ty -- anything else doesn't make
3124 // sense if declared ty is a ty param
3125 to_zero += [{v: lv.val, t: e_ty}];
3126 } else { to_revoke += [{v: lv.val, t: e_ty}]; }
3132 // NB: must keep 4 fns in sync:
3135 // - create_llargs_for_fn_args.
3138 fn trans_args(cx: @block_ctxt, llenv: ValueRef,
3139 gen: option::t<generic_info>, es: [@ast::expr], fn_ty: ty::t,
3141 -> {bcx: @block_ctxt,
3144 to_zero: [{v: ValueRef, t: ty::t}],
3145 to_revoke: [{v: ValueRef, t: ty::t}]} {
3147 let args: [ty::arg] = ty::ty_fn_args(bcx_tcx(cx), fn_ty);
3148 let llargs: [ValueRef] = [];
3149 let lltydescs: [ValueRef] = [];
3153 let ccx = bcx_ccx(cx);
3157 let retty = ty::ty_fn_ret(tcx, fn_ty), full_retty = retty;
3160 lazily_emit_all_generic_info_tydesc_glues(cx, g);
3161 let i = 0u, n_orig = 0u;
3162 for param in *g.param_bounds {
3163 lltydescs += [g.tydescs[i]];
3164 for bound in *param {
3166 ty::bound_iface(_) {
3167 let res = trans_impl::get_dict(
3168 bcx, option::get(g.origins)[n_orig]);
3169 lltydescs += [res.val];
3178 args = ty::ty_fn_args(tcx, g.item_type);
3179 retty = ty::ty_fn_ret(tcx, g.item_type);
3183 // Arg 0: Output pointer.
3184 let llretslot = alt dest {
3186 if ty::type_is_nil(tcx, retty) {
3187 llvm::LLVMGetUndef(T_ptr(T_nil()))
3189 let {bcx: cx, val} = alloc_ty(bcx, full_retty);
3194 save_in(dst) { dst }
3196 let {bcx: cx, val} = alloc_ty(bcx, full_retty);
3202 if ty::type_contains_params(tcx, retty) {
3203 // It's possible that the callee has some generic-ness somewhere in
3204 // its return value -- say a method signature within an obj or a fn
3205 // type deep in a structure -- which the caller has a concrete view
3206 // of. If so, cast the caller's view of the restlot to the callee's
3207 // view, for the sake of making a type-compatible call.
3208 check non_ty_var(ccx, retty);
3209 let llretty = T_ptr(type_of_inner(ccx, bcx.sp, retty));
3210 llargs += [PointerCast(cx, llretslot, llretty)];
3211 } else { llargs += [llretslot]; }
3213 // Arg 1: Env (closure-bindings / self-obj)
3216 // Args >2: ty_params ...
3217 llargs += lltydescs;
3219 // ... then explicit args.
3221 // First we figure out the caller's view of the types of the arguments.
3222 // This will be needed if this is a generic call, because the callee has
3223 // to cast her view of the arguments to the caller's view.
3224 let arg_tys = type_of_explicit_args(ccx, cx.sp, args);
3226 for e: @ast::expr in es {
3227 let r = trans_arg_expr(bcx, args[i], arg_tys[i], to_zero, to_revoke,
3237 to_revoke: to_revoke};
3240 fn trans_call(in_cx: @block_ctxt, f: @ast::expr,
3241 args: [@ast::expr], id: ast::node_id, dest: dest)
3243 // NB: 'f' isn't necessarily a function; it might be an entire self-call
3244 // expression because of the hack that allows us to process self-calls
3246 let tcx = bcx_tcx(in_cx);
3247 let fn_expr_ty = ty::expr_ty(tcx, f);
3249 let cx = new_scope_block_ctxt(in_cx, "call");
3251 let f_res = trans_callee(cx, f);
3252 let bcx = f_res.bcx;
3254 let faddr = f_res.val;
3255 let llenv, dict_param = none;
3258 llenv = llvm::LLVMGetUndef(T_opaque_cbox_ptr(bcx_ccx(cx)));
3260 obj_env(e) { llenv = e; }
3261 dict_env(dict, e) { llenv = e; dict_param = some(dict); }
3263 // It's a closure. Have to fetch the elements
3264 if f_res.kind == owned {
3265 faddr = load_if_immediate(bcx, faddr, fn_expr_ty);
3268 faddr = GEPi(bcx, pair, [0, abi::fn_field_code]);
3269 faddr = Load(bcx, faddr);
3270 let llclosure = GEPi(bcx, pair, [0, abi::fn_field_box]);
3271 llenv = Load(bcx, llclosure);
3275 let ret_ty = ty::node_id_to_type(tcx, id);
3277 trans_args(bcx, llenv, f_res.generic, args, fn_expr_ty, dest);
3279 let llargs = args_res.args;
3280 option::may(dict_param) {|dict| llargs = [dict] + llargs}
3281 let llretslot = args_res.retslot;
3283 /* If the block is terminated,
3284 then one or more of the args has
3285 type _|_. Since that means it diverges, the code
3286 for the call itself is unreachable. */
3287 bcx = invoke_full(bcx, faddr, llargs, args_res.to_zero,
3288 args_res.to_revoke);
3291 if llvm::LLVMIsUndef(llretslot) != lib::llvm::True {
3292 bcx = drop_ty(bcx, llretslot, ret_ty);
3295 save_in(_) { } // Already saved by callee
3297 *cell = Load(bcx, llretslot);
3300 // Forget about anything we moved out.
3301 bcx = zero_and_revoke(bcx, args_res.to_zero, args_res.to_revoke);
3303 bcx = trans_block_cleanups(bcx, cx);
3304 let next_cx = new_sub_block_ctxt(in_cx, "next");
3305 if bcx.unreachable || ty::type_is_bot(tcx, ret_ty) {
3306 Unreachable(next_cx);
3308 Br(bcx, next_cx.llbb);
3312 fn zero_and_revoke(bcx: @block_ctxt,
3313 to_zero: [{v: ValueRef, t: ty::t}],
3314 to_revoke: [{v: ValueRef, t: ty::t}]) -> @block_ctxt {
3316 for {v, t} in to_zero {
3317 bcx = zero_alloca(bcx, v, t);
3319 for {v, _} in to_revoke { revoke_clean(bcx, v); }
3323 fn invoke(bcx: @block_ctxt, llfn: ValueRef,
3324 llargs: [ValueRef]) -> @block_ctxt {
3325 ret invoke_(bcx, llfn, llargs, [], [], Invoke);
3328 fn invoke_full(bcx: @block_ctxt, llfn: ValueRef, llargs: [ValueRef],
3329 to_zero: [{v: ValueRef, t: ty::t}],
3330 to_revoke: [{v: ValueRef, t: ty::t}]) -> @block_ctxt {
3331 ret invoke_(bcx, llfn, llargs, to_zero, to_revoke, Invoke);
3334 fn invoke_(bcx: @block_ctxt, llfn: ValueRef, llargs: [ValueRef],
3335 to_zero: [{v: ValueRef, t: ty::t}],
3336 to_revoke: [{v: ValueRef, t: ty::t}],
3337 invoker: fn(@block_ctxt, ValueRef, [ValueRef],
3338 BasicBlockRef, BasicBlockRef)) -> @block_ctxt {
3339 // FIXME: May be worth turning this into a plain call when there are no
3341 if bcx.unreachable { ret bcx; }
3342 let normal_bcx = new_sub_block_ctxt(bcx, "normal return");
3343 invoker(bcx, llfn, llargs, normal_bcx.llbb,
3344 get_landing_pad(bcx, to_zero, to_revoke));
3348 fn get_landing_pad(bcx: @block_ctxt,
3349 to_zero: [{v: ValueRef, t: ty::t}],
3350 to_revoke: [{v: ValueRef, t: ty::t}]
3351 ) -> BasicBlockRef {
3352 let have_zero_or_revoke = vec::is_not_empty(to_zero)
3353 || vec::is_not_empty(to_revoke);
3354 let scope_bcx = find_scope_for_lpad(bcx, have_zero_or_revoke);
3355 if scope_bcx.lpad_dirty || have_zero_or_revoke {
3356 let unwind_bcx = new_sub_block_ctxt(bcx, "unwind");
3357 trans_landing_pad(unwind_bcx, to_zero, to_revoke);
3358 scope_bcx.lpad = some(unwind_bcx.llbb);
3359 scope_bcx.lpad_dirty = have_zero_or_revoke;
3361 assert option::is_some(scope_bcx.lpad);
3362 ret option::get(scope_bcx.lpad);
3364 fn find_scope_for_lpad(bcx: @block_ctxt,
3365 have_zero_or_revoke: bool) -> @block_ctxt {
3366 let scope_bcx = bcx;
3368 scope_bcx = find_scope_cx(scope_bcx);
3369 if vec::is_not_empty(scope_bcx.cleanups)
3370 || have_zero_or_revoke {
3373 scope_bcx = alt scope_bcx.parent {
3374 parent_some(b) { b }
3385 fn trans_landing_pad(bcx: @block_ctxt,
3386 to_zero: [{v: ValueRef, t: ty::t}],
3387 to_revoke: [{v: ValueRef, t: ty::t}]) -> BasicBlockRef {
3388 // The landing pad return type (the type being propagated). Not sure what
3389 // this represents but it's determined by the personality function and
3390 // this is what the EH proposal example uses.
3391 let llretty = T_struct([T_ptr(T_i8()), T_i32()]);
3392 // The exception handling personality function. This is the C++
3393 // personality function __gxx_personality_v0, wrapped in our naming
3395 let personality = bcx_ccx(bcx).upcalls.rust_personality;
3396 // The only landing pad clause will be 'cleanup'
3398 let llpad = LandingPad(bcx, llretty, personality, clauses);
3399 // The landing pad result is used both for modifying the landing pad
3400 // in the C API and as the exception value
3401 let llretval = llpad;
3402 // The landing pad block is a cleanup
3403 SetCleanup(bcx, llpad);
3405 // Because we may have unwound across a stack boundary, we must call into
3406 // the runtime to figure out which stack segment we are on and place the
3407 // stack limit back into the TLS.
3408 Call(bcx, bcx_ccx(bcx).upcalls.reset_stack_limit, []);
3410 // FIXME: This seems like a very naive and redundant way to generate the
3411 // landing pads, as we're re-generating all in-scope cleanups for each
3412 // function call. Probably good optimization opportunities here.
3413 let bcx = zero_and_revoke(bcx, to_zero, to_revoke);
3416 scope_cx = find_scope_cx(scope_cx);
3417 bcx = trans_block_cleanups(bcx, scope_cx);
3418 scope_cx = alt scope_cx.parent {
3419 parent_some(b) { b }
3420 parent_none. { break; }
3424 // Continue unwinding
3425 Resume(bcx, llretval);
3429 fn trans_tup(bcx: @block_ctxt, elts: [@ast::expr], id: ast::node_id,
3430 dest: dest) -> @block_ctxt {
3431 let t = node_id_type(bcx.fcx.lcx.ccx, id);
3433 let addr = alt dest {
3435 for ex in elts { bcx = trans_expr(bcx, ex, ignore); }
3438 save_in(pos) { pos }
3440 let temp_cleanups = [], i = 0;
3442 let dst = GEP_tup_like_1(bcx, t, addr, [0, i]);
3443 let e_ty = ty::expr_ty(bcx_tcx(bcx), e);
3444 bcx = trans_expr_save_in(dst.bcx, e, dst.val);
3445 add_clean_temp_mem(bcx, dst.val, e_ty);
3446 temp_cleanups += [dst.val];
3449 for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
3453 fn trans_rec(bcx: @block_ctxt, fields: [ast::field],
3454 base: option::t<@ast::expr>, id: ast::node_id,
3455 dest: dest) -> @block_ctxt {
3456 let t = node_id_type(bcx_ccx(bcx), id);
3458 let addr = alt dest {
3461 bcx = trans_expr(bcx, fld.node.expr, ignore);
3465 save_in(pos) { pos }
3468 let ty_fields = alt ty::struct(bcx_tcx(bcx), t) { ty::ty_rec(f) { f } };
3469 let temp_cleanups = [];
3471 let ix = option::get(vec::position_pred(ty_fields, {|ft|
3472 str::eq(fld.node.ident, ft.ident)
3474 let dst = GEP_tup_like_1(bcx, t, addr, [0, ix as int]);
3475 bcx = trans_expr_save_in(dst.bcx, fld.node.expr, dst.val);
3476 add_clean_temp_mem(bcx, dst.val, ty_fields[ix].mt.ty);
3477 temp_cleanups += [dst.val];
3481 let {bcx: cx, val: base_val} = trans_temp_expr(bcx, bexp), i = 0;
3483 // Copy over inherited fields
3484 for tf in ty_fields {
3485 if !vec::any(fields, {|f| str::eq(f.node.ident, tf.ident)}) {
3486 let dst = GEP_tup_like_1(bcx, t, addr, [0, i]);
3487 let base = GEP_tup_like_1(bcx, t, base_val, [0, i]);
3488 let val = load_if_immediate(base.bcx, base.val, tf.mt.ty);
3489 bcx = copy_val(base.bcx, INIT, dst.val, val, tf.mt.ty);
3497 // Now revoke the cleanups as we pass responsibility for the data
3498 // structure on to the caller
3499 for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
3503 // Store the result of an expression in the given memory location, ensuring
3504 // that nil or bot expressions get ignore rather than save_in as destination.
3505 fn trans_expr_save_in(bcx: @block_ctxt, e: @ast::expr, dest: ValueRef)
3507 let tcx = bcx_tcx(bcx), t = ty::expr_ty(tcx, e);
3508 let do_ignore = ty::type_is_bot(tcx, t) || ty::type_is_nil(tcx, t);
3509 ret trans_expr(bcx, e, do_ignore ? ignore : save_in(dest));
3512 // Call this to compile an expression that you need as an intermediate value,
3513 // and you want to know whether you're dealing with an lval or not (the kind
3514 // field in the returned struct). For non-intermediates, use trans_expr or
3515 // trans_expr_save_in. For intermediates where you don't care about lval-ness,
3516 // use trans_temp_expr.
3517 fn trans_temp_lval(bcx: @block_ctxt, e: @ast::expr) -> lval_result {
3519 if expr_is_lval(bcx, e) {
3520 ret trans_lval(bcx, e);
3522 let tcx = bcx_tcx(bcx);
3523 let ty = ty::expr_ty(tcx, e);
3524 if ty::type_is_nil(tcx, ty) || ty::type_is_bot(tcx, ty) {
3525 bcx = trans_expr(bcx, e, ignore);
3526 ret {bcx: bcx, val: C_nil(), kind: temporary};
3527 } else if ty::type_is_immediate(bcx_tcx(bcx), ty) {
3528 let cell = empty_dest_cell();
3529 bcx = trans_expr(bcx, e, by_val(cell));
3530 add_clean_temp(bcx, *cell, ty);
3531 ret {bcx: bcx, val: *cell, kind: temporary};
3533 let {bcx, val: scratch} = alloc_ty(bcx, ty);
3534 bcx = trans_expr_save_in(bcx, e, scratch);
3535 add_clean_temp(bcx, scratch, ty);
3536 ret {bcx: bcx, val: scratch, kind: temporary};
3541 // Use only for intermediate values. See trans_expr and trans_expr_save_in for
3542 // expressions that must 'end up somewhere' (or get ignored).
3543 fn trans_temp_expr(bcx: @block_ctxt, e: @ast::expr) -> result {
3544 let {bcx, val, kind} = trans_temp_lval(bcx, e);
3546 val = load_if_immediate(bcx, val, ty::expr_ty(bcx_tcx(bcx), e));
3548 ret {bcx: bcx, val: val};
3551 // Translate an expression, with the dest argument deciding what happens with
3552 // the result. Invariants:
3553 // - exprs returning nil or bot always get dest=ignore
3554 // - exprs with non-immediate type never get dest=by_val
3555 fn trans_expr(bcx: @block_ctxt, e: @ast::expr, dest: dest) -> @block_ctxt {
3556 let tcx = bcx_tcx(bcx);
3557 debuginfo::update_source_pos(bcx, e.span);
3559 if expr_is_lval(bcx, e) {
3560 ret lval_to_dps(bcx, e, dest);
3564 ast::expr_if(cond, thn, els) | ast::expr_if_check(cond, thn, els) {
3565 ret trans_if(bcx, cond, thn, els, dest);
3567 ast::expr_ternary(_, _, _) {
3568 ret trans_expr(bcx, ast_util::ternary_to_if(e), dest);
3570 ast::expr_alt(expr, arms) {
3571 ret trans_alt::trans_alt(bcx, expr, arms, dest);
3573 ast::expr_block(blk) {
3574 let sub_cx = new_scope_block_ctxt(bcx, "block-expr body");
3575 Br(bcx, sub_cx.llbb);
3576 sub_cx = trans_block_dps(sub_cx, blk, dest);
3577 let next_cx = new_sub_block_ctxt(bcx, "next");
3578 Br(sub_cx, next_cx.llbb);
3579 if sub_cx.unreachable { Unreachable(next_cx); }
3582 ast::expr_rec(args, base) {
3583 ret trans_rec(bcx, args, base, e.id, dest);
3585 ast::expr_tup(args) { ret trans_tup(bcx, args, e.id, dest); }
3586 ast::expr_lit(lit) { ret trans_lit(bcx, *lit, dest); }
3587 ast::expr_vec(args, _) { ret tvec::trans_vec(bcx, args, e.id, dest); }
3588 ast::expr_binary(op, x, y) { ret trans_binary(bcx, op, x, y, dest); }
3589 ast::expr_unary(op, x) {
3590 assert op != ast::deref; // lvals are handled above
3591 ret trans_unary(bcx, op, x, e.id, dest);
3593 ast::expr_fn(proto, decl, body, cap_clause) {
3594 ret trans_closure::trans_expr_fn(
3595 bcx, proto, decl, body, e.span, e.id, *cap_clause, dest);
3597 ast::expr_fn_block(decl, body) {
3598 alt ty::struct(tcx, ty::expr_ty(tcx, e)) {
3599 ty::ty_fn({proto, _}) {
3600 #debug("translating fn_block %s with type %s",
3601 expr_to_str(e), ty_to_str(tcx, ty::expr_ty(tcx, e)));
3602 let cap_clause = { copies: [], moves: [] };
3603 ret trans_closure::trans_expr_fn(
3604 bcx, proto, decl, body, e.span, e.id, cap_clause, dest);
3607 fail "Type of fn block is not a function!";
3611 ast::expr_bind(f, args) {
3612 ret trans_closure::trans_bind(
3613 bcx, f, args, e.id, dest);
3616 if !expr_is_lval(bcx, a) {
3617 ret trans_expr(bcx, a, dest);
3619 else { ret lval_to_dps(bcx, a, dest); }
3621 ast::expr_cast(val, _) { ret trans_cast(bcx, val, e.id, dest); }
3622 ast::expr_anon_obj(anon_obj) {
3623 ret trans_anon_obj(bcx, e.span, anon_obj, e.id, dest);
3625 ast::expr_call(f, args, _) {
3626 ret trans_call(bcx, f, args, e.id, dest);
3628 ast::expr_field(_, _, _) {
3629 fail "Taking the value of a method does not work yet (issue #435)";
3632 // These return nothing
3634 assert dest == ignore;
3635 ret trans_break(e.span, bcx);
3638 assert dest == ignore;
3639 ret trans_cont(e.span, bcx);
3642 assert dest == ignore;
3643 ret trans_ret(bcx, ex);
3646 // Ideally, the expr_be tag would have a precondition
3647 // that is_call_expr(ex) -- but we don't support that
3650 check (ast_util::is_call_expr(ex));
3651 ret trans_be(bcx, ex);
3653 ast::expr_fail(expr) {
3654 assert dest == ignore;
3655 ret trans_fail_expr(bcx, some(e.span), expr);
3657 ast::expr_log(_, lvl, a) {
3658 assert dest == ignore;
3659 ret trans_log(lvl, bcx, a);
3661 ast::expr_assert(a) {
3662 assert dest == ignore;
3663 ret trans_check_expr(bcx, a, "Assertion");
3665 ast::expr_check(ast::checked_expr., a) {
3666 assert dest == ignore;
3667 ret trans_check_expr(bcx, a, "Predicate");
3669 ast::expr_check(ast::claimed_expr., a) {
3670 assert dest == ignore;
3671 /* Claims are turned on and off by a global variable
3672 that the RTS sets. This case generates code to
3673 check the value of that variable, doing nothing
3674 if it's set to false and acting like a check
3677 get_extern_const(bcx_ccx(bcx).externs, bcx_ccx(bcx).llmod,
3678 "check_claims", T_bool());
3679 let cond = Load(bcx, c);
3681 let then_cx = new_scope_block_ctxt(bcx, "claim_then");
3682 let check_cx = trans_check_expr(then_cx, a, "Claim");
3683 let next_cx = new_sub_block_ctxt(bcx, "join");
3685 CondBr(bcx, cond, then_cx.llbb, next_cx.llbb);
3686 Br(check_cx, next_cx.llbb);
3689 ast::expr_for(decl, seq, body) {
3690 assert dest == ignore;
3691 ret trans_for(bcx, decl, seq, body);
3693 ast::expr_while(cond, body) {
3694 assert dest == ignore;
3695 ret trans_while(bcx, cond, body);
3697 ast::expr_do_while(body, cond) {
3698 assert dest == ignore;
3699 ret trans_do_while(bcx, body, cond);
3701 ast::expr_assign(dst, src) {
3702 assert dest == ignore;
3703 let src_r = trans_temp_lval(bcx, src);
3704 let {bcx, val: addr, kind} = trans_lval(src_r.bcx, dst);
3705 assert kind == owned;
3706 ret store_temp_expr(bcx, DROP_EXISTING, addr, src_r,
3707 ty::expr_ty(bcx_tcx(bcx), src),
3708 bcx_ccx(bcx).last_uses.contains_key(src.id));
3710 ast::expr_move(dst, src) {
3711 // FIXME: calculate copy init-ness in typestate.
3712 assert dest == ignore;
3713 let src_r = trans_temp_lval(bcx, src);
3714 let {bcx, val: addr, kind} = trans_lval(src_r.bcx, dst);
3715 assert kind == owned;
3716 ret move_val(bcx, DROP_EXISTING, addr, src_r,
3717 ty::expr_ty(bcx_tcx(bcx), src));
3719 ast::expr_swap(dst, src) {
3720 assert dest == ignore;
3721 let lhs_res = trans_lval(bcx, dst);
3722 assert lhs_res.kind == owned;
3723 let rhs_res = trans_lval(lhs_res.bcx, src);
3724 let t = ty::expr_ty(tcx, src);
3725 let {bcx: bcx, val: tmp_alloc} = alloc_ty(rhs_res.bcx, t);
3726 // Swap through a temporary.
3727 bcx = move_val(bcx, INIT, tmp_alloc, lhs_res, t);
3728 bcx = move_val(bcx, INIT, lhs_res.val, rhs_res, t);
3729 ret move_val(bcx, INIT, rhs_res.val, lval_owned(bcx, tmp_alloc), t);
3731 ast::expr_assign_op(op, dst, src) {
3732 assert dest == ignore;
3733 ret trans_assign_op(bcx, op, dst, src);
3738 fn lval_to_dps(bcx: @block_ctxt, e: @ast::expr, dest: dest) -> @block_ctxt {
3739 let lv = trans_lval(bcx, e), ccx = bcx_ccx(bcx);
3740 let {bcx, val, kind} = lv;
3741 let last_use = kind == owned && ccx.last_uses.contains_key(e.id);
3742 let ty = ty::expr_ty(ccx.tcx, e);
3745 if kind == temporary {
3746 revoke_clean(bcx, val);
3748 } else if last_use {
3749 *cell = Load(bcx, val);
3750 if ty::type_needs_drop(ccx.tcx, ty) {
3751 bcx = zero_alloca(bcx, val, ty);
3754 if kind == owned { val = Load(bcx, val); }
3755 let {bcx: cx, val} = take_ty_immediate(bcx, val, ty);
3761 bcx = store_temp_expr(bcx, INIT, loc, lv, ty, last_use);
3768 fn do_spill(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
3769 // We have a value but we have to spill it, and root it, to pass by alias.
3772 if ty::type_is_bot(bcx_tcx(bcx), t) {
3773 ret rslt(bcx, C_null(T_ptr(T_i8())));
3776 let r = alloc_ty(bcx, t);
3780 Store(bcx, v, llptr);
3782 ret rslt(bcx, llptr);
3785 // Since this function does *not* root, it is the caller's responsibility to
3786 // ensure that the referent is pointed to by a root.
3787 fn do_spill_noroot(cx: @block_ctxt, v: ValueRef) -> ValueRef {
3788 let llptr = alloca(cx, val_ty(v));
3789 Store(cx, v, llptr);
3793 fn spill_if_immediate(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
3794 if ty::type_is_immediate(bcx_tcx(cx), t) { ret do_spill(cx, v, t); }
3798 fn load_if_immediate(cx: @block_ctxt, v: ValueRef, t: ty::t) -> ValueRef {
3799 if ty::type_is_immediate(bcx_tcx(cx), t) { ret Load(cx, v); }
3803 fn trans_log(lvl: @ast::expr, cx: @block_ctxt, e: @ast::expr) -> @block_ctxt {
3804 let ccx = bcx_ccx(cx);
3805 let lcx = cx.fcx.lcx;
3806 let modname = str::connect(lcx.module_path, "::");
3807 let global = if lcx.ccx.module_data.contains_key(modname) {
3808 lcx.ccx.module_data.get(modname)
3810 let s = link::mangle_internal_name_by_path_and_seq(
3811 lcx.ccx, lcx.module_path, "loglevel");
3812 let global = str::as_buf(s, {|buf|
3813 llvm::LLVMAddGlobal(lcx.ccx.llmod, T_i32(), buf)
3815 llvm::LLVMSetGlobalConstant(global, False);
3816 llvm::LLVMSetInitializer(global, C_null(T_i32()));
3817 llvm::LLVMSetLinkage(global,
3818 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
3819 lcx.ccx.module_data.insert(modname, global);
3822 let level_cx = new_scope_block_ctxt(cx, "level");
3823 let log_cx = new_scope_block_ctxt(cx, "log");
3824 let after_cx = new_sub_block_ctxt(cx, "after");
3825 let load = Load(cx, global);
3827 Br(cx, level_cx.llbb);
3828 let level_res = trans_temp_expr(level_cx, lvl);
3829 let test = ICmp(level_res.bcx, lib::llvm::LLVMIntUGE,
3830 load, level_res.val);
3832 CondBr(level_res.bcx, test, log_cx.llbb, after_cx.llbb);
3833 let sub = trans_temp_expr(log_cx, e);
3834 let e_ty = ty::expr_ty(bcx_tcx(cx), e);
3835 let log_bcx = sub.bcx;
3837 let ti = none::<@tydesc_info>;
3838 let r = get_tydesc(log_bcx, e_ty, false, tps_normal, ti).result;
3840 let lltydesc = r.val;
3842 // Call the polymorphic log function.
3843 r = spill_if_immediate(log_bcx, sub.val, e_ty);
3845 let llvalptr = r.val;
3846 let llval_i8 = PointerCast(log_bcx, llvalptr, T_ptr(T_i8()));
3848 Call(log_bcx, ccx.upcalls.log_type,
3849 [lltydesc, llval_i8, level_res.val]);
3851 log_bcx = trans_block_cleanups(log_bcx, log_cx);
3852 Br(log_bcx, after_cx.llbb);
3853 ret trans_block_cleanups(after_cx, level_cx);
3856 fn trans_check_expr(cx: @block_ctxt, e: @ast::expr, s: str) -> @block_ctxt {
3857 let cond_res = trans_temp_expr(cx, e);
3858 let expr_str = s + " " + expr_to_str(e) + " failed";
3859 let fail_cx = new_sub_block_ctxt(cx, "fail");
3860 trans_fail(fail_cx, some::<span>(e.span), expr_str);
3861 let next_cx = new_sub_block_ctxt(cx, "next");
3862 CondBr(cond_res.bcx, cond_res.val, next_cx.llbb, fail_cx.llbb);
3866 fn trans_fail_expr(bcx: @block_ctxt, sp_opt: option::t<span>,
3867 fail_expr: option::t<@ast::expr>) -> @block_ctxt {
3871 let tcx = bcx_tcx(bcx);
3872 let expr_res = trans_temp_expr(bcx, expr);
3873 let e_ty = ty::expr_ty(tcx, expr);
3876 if ty::type_is_str(tcx, e_ty) {
3877 let data = tvec::get_dataptr(
3878 bcx, expr_res.val, type_of_or_i8(
3879 bcx, ty::mk_mach_uint(tcx, ast::ty_u8)));
3880 ret trans_fail_value(bcx, sp_opt, data);
3881 } else if bcx.unreachable {
3884 bcx_ccx(bcx).sess.span_bug(
3885 expr.span, "fail called with unsupported type " +
3886 ty_to_str(tcx, e_ty));
3889 _ { ret trans_fail(bcx, sp_opt, "explicit failure"); }
3893 fn trans_fail(bcx: @block_ctxt, sp_opt: option::t<span>, fail_str: str) ->
3895 let V_fail_str = C_cstr(bcx_ccx(bcx), fail_str);
3896 ret trans_fail_value(bcx, sp_opt, V_fail_str);
3899 fn trans_fail_value(bcx: @block_ctxt, sp_opt: option::t<span>,
3900 V_fail_str: ValueRef) -> @block_ctxt {
3901 let ccx = bcx_ccx(bcx);
3906 let loc = bcx_ccx(bcx).sess.lookup_pos(sp.lo);
3907 V_filename = C_cstr(bcx_ccx(bcx), loc.filename);
3908 V_line = loc.line as int;
3910 none. { V_filename = C_cstr(bcx_ccx(bcx), "<runtime>"); V_line = 0; }
3912 let V_str = PointerCast(bcx, V_fail_str, T_ptr(T_i8()));
3913 V_filename = PointerCast(bcx, V_filename, T_ptr(T_i8()));
3914 let args = [V_str, V_filename, C_int(ccx, V_line)];
3915 let bcx = invoke(bcx, bcx_ccx(bcx).upcalls._fail, args);
3920 fn trans_break_cont(sp: span, bcx: @block_ctxt, to_end: bool)
3922 // Locate closest loop block, outputting cleanup as we go.
3923 let cleanup_cx = bcx, bcx = bcx;
3925 bcx = trans_block_cleanups(bcx, cleanup_cx);
3926 alt copy cleanup_cx.kind {
3927 LOOP_SCOPE_BLOCK(_cont, _break) {
3929 Br(bcx, _break.llbb);
3932 option::some(_cont) { Br(bcx, _cont.llbb); }
3933 _ { Br(bcx, cleanup_cx.llbb); }
3940 alt cleanup_cx.parent {
3941 parent_some(cx) { cleanup_cx = cx; }
3943 bcx_ccx(bcx).sess.span_fatal
3944 (sp, if to_end { "Break" } else { "Cont" } +
3951 // If we get here without returning, it's a bug
3952 bcx_ccx(bcx).sess.bug("in trans::trans_break_cont()");
3955 fn trans_break(sp: span, cx: @block_ctxt) -> @block_ctxt {
3956 ret trans_break_cont(sp, cx, true);
3959 fn trans_cont(sp: span, cx: @block_ctxt) -> @block_ctxt {
3960 ret trans_break_cont(sp, cx, false);
3963 fn trans_ret(bcx: @block_ctxt, e: option::t<@ast::expr>) -> @block_ctxt {
3964 let cleanup_cx = bcx, bcx = bcx;
3966 some(x) { bcx = trans_expr_save_in(bcx, x, bcx.fcx.llretptr); }
3969 // run all cleanups and back out.
3971 let more_cleanups: bool = true;
3972 while more_cleanups {
3973 bcx = trans_block_cleanups(bcx, cleanup_cx);
3974 alt cleanup_cx.parent {
3975 parent_some(b) { cleanup_cx = b; }
3976 parent_none. { more_cleanups = false; }
3984 fn build_return(bcx: @block_ctxt) { Br(bcx, bcx_fcx(bcx).llreturn); }
3986 // fn trans_be(cx: &@block_ctxt, e: &@ast::expr) -> result {
3987 fn trans_be(cx: @block_ctxt, e: @ast::expr) : ast_util::is_call_expr(e) ->
3989 // FIXME: Turn this into a real tail call once
3990 // calling convention issues are settled
3991 ret trans_ret(cx, some(e));
3994 fn init_local(bcx: @block_ctxt, local: @ast::local) -> @block_ctxt {
3995 let ty = node_id_type(bcx_ccx(bcx), local.node.id);
3996 let llptr = alt bcx.fcx.lllocals.find(local.node.id) {
3997 some(local_mem(v)) { v }
3998 // This is a local that is kept immediate
4000 let initexpr = alt local.node.init { some({expr, _}) { expr } };
4001 let {bcx, val, kind} = trans_temp_lval(bcx, initexpr);
4002 if kind != temporary {
4003 if kind == owned { val = Load(bcx, val); }
4004 let rs = take_ty_immediate(bcx, val, ty);
4005 bcx = rs.bcx; val = rs.val;
4006 add_clean_temp(bcx, val, ty);
4008 bcx.fcx.lllocals.insert(local.node.pat.id, local_imm(val));
4014 alt local.node.init {
4016 if init.op == ast::init_assign || !expr_is_lval(bcx, init.expr) {
4017 bcx = trans_expr_save_in(bcx, init.expr, llptr);
4018 } else { // This is a move from an lval, must perform an actual move
4019 let sub = trans_lval(bcx, init.expr);
4020 bcx = move_val(sub.bcx, INIT, llptr, sub, ty);
4023 _ { bcx = zero_alloca(bcx, llptr, ty); }
4025 // Make a note to drop this slot on the way out.
4026 add_clean(bcx, llptr, ty);
4027 ret trans_alt::bind_irrefutable_pat(bcx, local.node.pat, llptr, false);
4030 fn init_ref_local(bcx: @block_ctxt, local: @ast::local) -> @block_ctxt {
4031 let init_expr = option::get(local.node.init).expr;
4032 let {bcx, val, kind} = trans_lval(bcx, init_expr);
4034 owned_imm. { val = do_spill_noroot(bcx, val); }
4037 ret trans_alt::bind_irrefutable_pat(bcx, local.node.pat, val, false);
4040 fn zero_alloca(cx: @block_ctxt, llptr: ValueRef, t: ty::t)
4043 let ccx = bcx_ccx(cx);
4044 if check type_has_static_size(ccx, t) {
4046 let llty = type_of(ccx, sp, t);
4047 Store(bcx, C_null(llty), llptr);
4049 let llsz = size_of(bcx, t);
4050 // FIXME passing in the align here is correct, but causes issue #843
4051 // let llalign = align_of(llsz.bcx, t);
4052 bcx = call_bzero(llsz.bcx, llptr, llsz.val, C_int(ccx, 0)).bcx;
4057 fn trans_stmt(cx: @block_ctxt, s: ast::stmt) -> @block_ctxt {
4058 // FIXME Fill in cx.sp
4060 if (!bcx_ccx(cx).sess.get_opts().no_asm_comments) {
4061 add_span_comment(cx, s.span, stmt_to_str(s));
4065 debuginfo::update_source_pos(cx, s.span);
4068 ast::stmt_expr(e, _) | ast::stmt_semi(e, _) {
4069 bcx = trans_expr(cx, e, ignore);
4071 ast::stmt_decl(d, _) {
4073 ast::decl_local(locals) {
4074 for (style, local) in locals {
4075 if style == ast::let_copy {
4076 bcx = init_local(bcx, local);
4078 bcx = init_ref_local(bcx, local);
4080 if bcx_ccx(cx).sess.get_opts().extra_debuginfo {
4081 debuginfo::create_local_var(bcx, local);
4085 ast::decl_item(i) { trans_item(cx.fcx.lcx, *i); }
4088 _ { bcx_ccx(cx).sess.unimpl("stmt variant"); }
4094 // You probably don't want to use this one. See the
4095 // next three functions instead.
4096 fn new_block_ctxt(cx: @fn_ctxt, parent: block_parent, kind: block_kind,
4097 name: str) -> @block_ctxt {
4099 if cx.lcx.ccx.sess.get_opts().save_temps ||
4100 cx.lcx.ccx.sess.get_opts().debuginfo {
4101 s = cx.lcx.ccx.names.next(name);
4103 let llbb: BasicBlockRef =
4104 str::as_buf(s, {|buf| llvm::LLVMAppendBasicBlock(cx.llfn, buf) });
4105 let bcx = @{llbb: llbb,
4106 mutable terminated: false,
4107 mutable unreachable: false,
4110 mutable cleanups: [],
4111 mutable lpad_dirty: true,
4112 mutable lpad: option::none,
4117 if cx.unreachable { Unreachable(bcx); }
4125 // Use this when you're at the top block of a function or the like.
4126 fn new_top_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4127 ret new_block_ctxt(fcx, parent_none, SCOPE_BLOCK, "function top level");
4131 // Use this when you're at a curly-brace or similar lexical scope.
4132 fn new_scope_block_ctxt(bcx: @block_ctxt, n: str) -> @block_ctxt {
4133 ret new_block_ctxt(bcx.fcx, parent_some(bcx), SCOPE_BLOCK, n);
4136 fn new_loop_scope_block_ctxt(bcx: @block_ctxt, _cont: option::t<@block_ctxt>,
4137 _break: @block_ctxt, n: str) -> @block_ctxt {
4138 ret new_block_ctxt(bcx.fcx, parent_some(bcx),
4139 LOOP_SCOPE_BLOCK(_cont, _break), n);
4143 // Use this when you're making a general CFG BB within a scope.
4144 fn new_sub_block_ctxt(bcx: @block_ctxt, n: str) -> @block_ctxt {
4145 ret new_block_ctxt(bcx.fcx, parent_some(bcx), NON_SCOPE_BLOCK, n);
4148 fn new_raw_block_ctxt(fcx: @fn_ctxt, llbb: BasicBlockRef) -> @block_ctxt {
4150 mutable terminated: false,
4151 mutable unreachable: false,
4152 parent: parent_none,
4153 kind: NON_SCOPE_BLOCK,
4154 mutable cleanups: [],
4155 mutable lpad_dirty: true,
4156 mutable lpad: option::none,
4162 // trans_block_cleanups: Go through all the cleanups attached to this
4163 // block_ctxt and execute them.
4165 // When translating a block that introdces new variables during its scope, we
4166 // need to make sure those variables go out of scope when the block ends. We
4167 // do that by running a 'cleanup' function for each variable.
4168 // trans_block_cleanups runs all the cleanup functions for the block.
4169 fn trans_block_cleanups(bcx: @block_ctxt, cleanup_cx: @block_ctxt) ->
4171 if bcx.unreachable { ret bcx; }
4172 if cleanup_cx.kind == NON_SCOPE_BLOCK {
4173 assert (vec::len::<cleanup>(cleanup_cx.cleanups) == 0u);
4175 let i = vec::len::<cleanup>(cleanup_cx.cleanups), bcx = bcx;
4178 let c = cleanup_cx.cleanups[i];
4180 clean(cfn) { bcx = cfn(bcx); }
4181 clean_temp(_, cfn) { bcx = cfn(bcx); }
4187 fn trans_fn_cleanups(fcx: @fn_ctxt, cx: @block_ctxt) {
4188 alt fcx.llobstacktoken {
4190 let lltoken = lltoken_; // satisfy alias checker
4191 Call(cx, fcx_ccx(fcx).upcalls.dynastack_free, [lltoken]);
4193 none. {/* nothing to do */ }
4197 fn block_locals(b: ast::blk, it: block(@ast::local)) {
4198 for s: @ast::stmt in b.node.stmts {
4200 ast::stmt_decl(d, _) {
4202 ast::decl_local(locals) {
4203 for (style, local) in locals {
4204 if style == ast::let_copy { it(local); }
4207 _ {/* fall through */ }
4210 _ {/* fall through */ }
4215 fn llstaticallocas_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4216 ret @{llbb: fcx.llstaticallocas,
4217 mutable terminated: false,
4218 mutable unreachable: false,
4219 parent: parent_none,
4221 mutable cleanups: [],
4222 mutable lpad_dirty: true,
4223 mutable lpad: option::none,
4228 fn llderivedtydescs_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4229 ret @{llbb: fcx.llderivedtydescs,
4230 mutable terminated: false,
4231 mutable unreachable: false,
4232 parent: parent_none,
4234 mutable cleanups: [],
4235 mutable lpad_dirty: true,
4236 mutable lpad: option::none,
4242 fn alloc_ty(cx: @block_ctxt, t: ty::t) -> result {
4244 let ccx = bcx_ccx(cx);
4246 if check type_has_static_size(ccx, t) {
4248 alloca(bcx, type_of(ccx, sp, t))
4250 // NB: we have to run this particular 'size_of' in a
4251 // block_ctxt built on the llderivedtydescs block for the fn,
4252 // so that the size dominates the array_alloca that
4255 let n = size_of(llderivedtydescs_block_ctxt(bcx.fcx), t);
4256 bcx.fcx.llderivedtydescs = n.bcx.llbb;
4257 dynastack_alloca(bcx, T_i8(), n.val, t)
4260 // NB: since we've pushed all size calculations in this
4261 // function up to the alloca block, we actually return the
4262 // block passed into us unmodified; it doesn't really
4263 // have to be passed-and-returned here, but it fits
4264 // past caller conventions and may well make sense again,
4265 // so we leave it as-is.
4267 if bcx_tcx(cx).sess.get_opts().do_gc {
4268 bcx = gc::add_gc_root(bcx, val, t);
4274 fn alloc_local(cx: @block_ctxt, local: @ast::local) -> @block_ctxt {
4275 let t = node_id_type(bcx_ccx(cx), local.node.id);
4276 let is_simple = alt local.node.pat.node {
4277 ast::pat_bind(_, none.) { true } _ { false }
4279 // Do not allocate space for locals that can be kept immediate.
4280 let ccx = bcx_ccx(cx);
4281 if is_simple && !ccx.mut_map.contains_key(local.node.pat.id) &&
4282 !ccx.last_uses.contains_key(local.node.pat.id) &&
4283 ty::type_is_immediate(ccx.tcx, t) {
4284 alt local.node.init {
4285 some({op: ast::init_assign., _}) { ret cx; }
4289 let r = alloc_ty(cx, t);
4290 alt local.node.pat.node {
4291 ast::pat_bind(ident, none.) {
4292 if bcx_ccx(cx).sess.get_opts().debuginfo {
4293 let _: () = str::as_buf(ident, {|buf|
4294 llvm::LLVMSetValueName(r.val, buf)
4300 cx.fcx.lllocals.insert(local.node.id, local_mem(r.val));
4304 fn trans_block(bcx: @block_ctxt, b: ast::blk) -> @block_ctxt {
4305 trans_block_dps(bcx, b, ignore)
4308 fn trans_block_dps(bcx: @block_ctxt, b: ast::blk, dest: dest)
4311 block_locals(b) {|local| bcx = alloc_local(bcx, local); };
4312 for s: @ast::stmt in b.node.stmts {
4313 debuginfo::update_source_pos(bcx, b.span);
4314 bcx = trans_stmt(bcx, *s);
4318 let bt = ty::type_is_bot(bcx_tcx(bcx), ty::expr_ty(bcx_tcx(bcx), e));
4319 debuginfo::update_source_pos(bcx, e.span);
4320 bcx = trans_expr(bcx, e, bt ? ignore : dest);
4322 _ { assert dest == ignore || bcx.unreachable; }
4324 let rv = trans_block_cleanups(bcx, find_scope_cx(bcx));
4328 fn new_local_ctxt(ccx: @crate_ctxt) -> @local_ctxt {
4329 let pth: [str] = [];
4331 module_path: [ccx.link_meta.name],
4338 // Creates the standard quartet of basic blocks: static allocas, copy args,
4339 // derived tydescs, and dynamic allocas.
4340 fn mk_standard_basic_blocks(llfn: ValueRef) ->
4345 rt: BasicBlockRef} {
4347 str::as_buf("static_allocas",
4348 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4350 str::as_buf("load_env",
4351 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4353 str::as_buf("derived_tydescs",
4354 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4356 str::as_buf("dynamic_allocas",
4357 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4359 str::as_buf("return",
4360 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) })};
4364 // NB: must keep 4 fns in sync:
4367 // - create_llargs_for_fn_args.
4370 fn new_fn_ctxt_w_id(cx: @local_ctxt, sp: span, llfndecl: ValueRef,
4371 id: ast::node_id, rstyle: ast::ret_style)
4373 let llbbs = mk_standard_basic_blocks(llfndecl);
4374 ret @{llfn: llfndecl,
4375 llenv: llvm::LLVMGetParam(llfndecl, 1u),
4376 llretptr: llvm::LLVMGetParam(llfndecl, 0u),
4377 mutable llstaticallocas: llbbs.sa,
4378 mutable llloadenv: llbbs.ca,
4379 mutable llderivedtydescs_first: llbbs.dt,
4380 mutable llderivedtydescs: llbbs.dt,
4381 mutable lldynamicallocas: llbbs.da,
4382 mutable llreturn: llbbs.rt,
4383 mutable llobstacktoken: none::<ValueRef>,
4384 mutable llself: none::<val_self_pair>,
4385 llargs: new_int_hash::<local_val>(),
4386 llobjfields: new_int_hash::<ValueRef>(),
4387 lllocals: new_int_hash::<local_val>(),
4388 llupvars: new_int_hash::<ValueRef>(),
4389 mutable lltyparams: [],
4390 derived_tydescs: ty::new_ty_hash(),
4397 fn new_fn_ctxt(cx: @local_ctxt, sp: span, llfndecl: ValueRef) -> @fn_ctxt {
4398 ret new_fn_ctxt_w_id(cx, sp, llfndecl, -1, ast::return_val);
4401 // NB: must keep 4 fns in sync:
4404 // - create_llargs_for_fn_args.
4408 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
4409 // allocas created for them.
4411 // When we translate a function, we need to map its incoming arguments to the
4412 // spaces that have been created for them (by code in the llallocas field of
4413 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
4414 // field of the fn_ctxt with
4415 fn create_llargs_for_fn_args(cx: @fn_ctxt, ty_self: self_arg,
4416 args: [ast::arg], ty_params: [ast::ty_param]) {
4417 // Skip the implicit arguments 0, and 1. TODO: Pull out 2u and define
4418 // it as a constant, since we're using it in several places in trans this
4422 obj_self(tt) | impl_self(tt) {
4423 cx.llself = some({v: cx.llenv, t: tt});
4430 for tp in ty_params {
4431 let lltydesc = llvm::LLVMGetParam(cx.llfn, arg_n), dicts = none;
4433 for bound in *fcx_tcx(cx).ty_param_bounds.get(tp.id) {
4435 ty::bound_iface(_) {
4436 let dict = llvm::LLVMGetParam(cx.llfn, arg_n);
4438 dicts = some(alt dicts {
4440 some(ds) { ds + [dict] }
4446 cx.lltyparams += [{desc: lltydesc, dicts: dicts}];
4451 // Populate the llargs field of the function context with the ValueRefs
4452 // that we get from llvm::LLVMGetParam for each argument.
4453 for arg: ast::arg in args {
4454 let llarg = llvm::LLVMGetParam(cx.llfn, arg_n);
4455 assert (llarg as int != 0);
4456 // Note that this uses local_mem even for things passed by value.
4457 // copy_args_to_allocas will overwrite the table entry with local_imm
4458 // before it's actually used.
4459 cx.llargs.insert(arg.id, local_mem(llarg));
4464 fn copy_args_to_allocas(fcx: @fn_ctxt, bcx: @block_ctxt, args: [ast::arg],
4465 arg_tys: [ty::arg]) -> @block_ctxt {
4466 if fcx_ccx(fcx).sess.get_opts().extra_debuginfo {
4467 llvm::LLVMAddAttribute(llvm::LLVMGetFirstParam(fcx.llfn),
4468 lib::llvm::LLVMStructRetAttribute as
4469 lib::llvm::llvm::Attribute);
4471 let arg_n: uint = 0u, bcx = bcx;
4472 for arg in arg_tys {
4473 let id = args[arg_n].id;
4474 let argval = alt fcx.llargs.get(id) { local_mem(v) { v } };
4476 ast::by_mut_ref. { }
4477 ast::by_move. | ast::by_copy. { add_clean(bcx, argval, arg.ty); }
4479 if !ty::type_is_immediate(bcx_tcx(bcx), arg.ty) {
4480 let {bcx: cx, val: alloc} = alloc_ty(bcx, arg.ty);
4482 Store(bcx, argval, alloc);
4483 fcx.llargs.insert(id, local_mem(alloc));
4485 fcx.llargs.insert(id, local_imm(argval));
4490 if fcx_ccx(fcx).sess.get_opts().extra_debuginfo {
4491 debuginfo::create_arg(bcx, args[arg_n]);
4498 fn arg_tys_of_fn(ccx: @crate_ctxt, id: ast::node_id) -> [ty::arg] {
4499 alt ty::struct(ccx.tcx, ty::node_id_to_type(ccx.tcx, id)) {
4500 ty::ty_fn({inputs, _}) { inputs }
4504 fn populate_fn_ctxt_from_llself(fcx: @fn_ctxt, llself: val_self_pair) {
4505 let ccx = fcx_ccx(fcx);
4506 let bcx = llstaticallocas_block_ctxt(fcx);
4507 let field_tys: [ty::t] = [];
4508 for f: ast::obj_field in bcx.fcx.lcx.obj_fields {
4509 field_tys += [node_id_type(ccx, f.id)];
4511 // Synthesize a tuple type for the fields so that GEP_tup_like() can work
4514 let fields_tup_ty = ty::mk_tup(fcx.lcx.ccx.tcx, field_tys);
4515 let n_typarams = vec::len::<ast::ty_param>(bcx.fcx.lcx.obj_typarams);
4516 let llobj_box_ty: TypeRef = T_obj_ptr(ccx, n_typarams);
4517 let box_cell = GEPi(bcx, llself.v, [0, abi::obj_field_box]);
4518 let box_ptr = Load(bcx, box_cell);
4519 box_ptr = PointerCast(bcx, box_ptr, llobj_box_ty);
4521 GEPi(bcx, box_ptr, [0, abi::box_rc_field_body,
4522 abi::obj_body_elt_typarams]);
4524 // The object fields immediately follow the type parameters, so we skip
4525 // over them to get the pointer.
4527 PointerCast(bcx, GEPi(bcx, obj_typarams, [1]),
4528 T_ptr(type_of_or_i8(bcx, fields_tup_ty)));
4531 for p: ast::ty_param in fcx.lcx.obj_typarams {
4532 let lltyparam: ValueRef =
4533 GEPi(bcx, obj_typarams, [0, i]);
4534 lltyparam = Load(bcx, lltyparam);
4535 fcx.lltyparams += [{desc: lltyparam, dicts: none}];
4539 for f: ast::obj_field in fcx.lcx.obj_fields {
4540 // FIXME: silly check
4541 check type_is_tup_like(bcx, fields_tup_ty);
4542 let rslt = GEP_tup_like(bcx, fields_tup_ty, obj_fields, [0, i]);
4543 bcx = llstaticallocas_block_ctxt(fcx);
4544 let llfield = rslt.val;
4545 fcx.llobjfields.insert(f.id, llfield);
4548 fcx.llstaticallocas = bcx.llbb;
4552 // Ties up the llstaticallocas -> llloadenv -> llderivedtydescs ->
4553 // lldynamicallocas -> lltop edges, and builds the return block.
4554 fn finish_fn(fcx: @fn_ctxt, lltop: BasicBlockRef) {
4555 Br(new_raw_block_ctxt(fcx, fcx.llstaticallocas), fcx.llloadenv);
4556 Br(new_raw_block_ctxt(fcx, fcx.llloadenv), fcx.llderivedtydescs_first);
4557 Br(new_raw_block_ctxt(fcx, fcx.llderivedtydescs), fcx.lldynamicallocas);
4558 Br(new_raw_block_ctxt(fcx, fcx.lldynamicallocas), lltop);
4560 let ret_cx = new_raw_block_ctxt(fcx, fcx.llreturn);
4561 trans_fn_cleanups(fcx, ret_cx);
4565 tag self_arg { obj_self(ty::t); impl_self(ty::t); no_self; }
4567 // trans_closure: Builds an LLVM function out of a source function.
4568 // If the function closes over its environment a closure will be
4570 fn trans_closure(cx: @local_ctxt, sp: span, decl: ast::fn_decl,
4571 body: ast::blk, llfndecl: ValueRef,
4572 ty_self: self_arg, ty_params: [ast::ty_param],
4573 id: ast::node_id, maybe_load_env: block(@fn_ctxt)) {
4574 set_uwtable(llfndecl);
4576 // Set up arguments to the function.
4577 let fcx = new_fn_ctxt_w_id(cx, sp, llfndecl, id, decl.cf);
4578 create_llargs_for_fn_args(fcx, ty_self, decl.inputs, ty_params);
4581 populate_fn_ctxt_from_llself(fcx, option::get(fcx.llself));
4586 // Create the first basic block in the function and keep a handle on it to
4587 // pass to finish_fn later.
4588 let bcx = new_top_block_ctxt(fcx);
4589 let lltop = bcx.llbb;
4590 let block_ty = node_id_type(cx.ccx, body.node.id);
4592 let arg_tys = arg_tys_of_fn(fcx.lcx.ccx, id);
4593 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, arg_tys);
4595 maybe_load_env(fcx);
4597 // This call to trans_block is the place where we bridge between
4598 // translation calls that don't have a return value (trans_crate,
4599 // trans_mod, trans_item, trans_obj, et cetera) and those that do
4600 // (trans_block, trans_expr, et cetera).
4601 if ty::type_is_bot(cx.ccx.tcx, block_ty) ||
4602 ty::type_is_nil(cx.ccx.tcx, block_ty) ||
4603 option::is_none(body.node.expr) {
4604 bcx = trans_block_dps(bcx, body, ignore);
4605 } else if ty::type_is_immediate(cx.ccx.tcx, block_ty) {
4606 let cell = empty_dest_cell();
4607 bcx = trans_block_dps(bcx, body, by_val(cell));
4608 Store(bcx, *cell, fcx.llretptr);
4610 bcx = trans_block_dps(bcx, body, save_in(fcx.llretptr));
4613 // FIXME: until LLVM has a unit type, we are moving around
4614 // C_nil values rather than their void type.
4615 if !bcx.unreachable { build_return(bcx); }
4616 // Insert the mandatory first few basic blocks before lltop.
4617 finish_fn(fcx, lltop);
4620 // trans_fn: creates an LLVM function corresponding to a source language
4622 fn trans_fn(cx: @local_ctxt, sp: span, decl: ast::fn_decl, body: ast::blk,
4623 llfndecl: ValueRef, ty_self: self_arg, ty_params: [ast::ty_param],
4625 let do_time = cx.ccx.sess.get_opts().stats;
4626 let start = do_time ? time::get_time() : {sec: 0u32, usec: 0u32};
4627 let fcx = option::none;
4628 trans_closure(cx, sp, decl, body, llfndecl, ty_self, ty_params, id,
4629 {|new_fcx| fcx = option::some(new_fcx);});
4630 if cx.ccx.sess.get_opts().extra_debuginfo {
4631 debuginfo::create_function(option::get(fcx));
4634 let end = time::get_time();
4635 log_fn_time(cx.ccx, str::connect(cx.path, "::"), start, end);
4639 fn trans_res_ctor(cx: @local_ctxt, sp: span, dtor: ast::fn_decl,
4640 ctor_id: ast::node_id, ty_params: [ast::ty_param]) {
4643 // Create a function for the constructor
4645 alt ccx.item_ids.find(ctor_id) {
4646 some(x) { llctor_decl = x; }
4647 _ { ccx.sess.span_fatal(sp, "unbound ctor_id in trans_res_ctor"); }
4649 let fcx = new_fn_ctxt(cx, sp, llctor_decl);
4650 let ret_t = ty::ret_ty_of_fn(cx.ccx.tcx, ctor_id);
4651 create_llargs_for_fn_args(fcx, no_self, dtor.inputs, ty_params);
4652 let bcx = new_top_block_ctxt(fcx);
4653 let lltop = bcx.llbb;
4654 let arg_t = arg_tys_of_fn(ccx, ctor_id)[0].ty;
4655 let tup_t = ty::mk_tup(ccx.tcx, [ty::mk_int(ccx.tcx), arg_t]);
4656 let arg = alt fcx.llargs.find(dtor.inputs[0].id) {
4657 some(local_mem(x)) { x }
4659 let llretptr = fcx.llretptr;
4660 if ty::type_has_dynamic_size(ccx.tcx, ret_t) {
4661 let llret_t = T_ptr(T_struct([ccx.int_type, llvm::LLVMTypeOf(arg)]));
4662 llretptr = BitCast(bcx, llretptr, llret_t);
4665 // FIXME: silly checks
4666 check type_is_tup_like(bcx, tup_t);
4667 let {bcx, val: dst} = GEP_tup_like(bcx, tup_t, llretptr, [0, 1]);
4668 bcx = memmove_ty(bcx, dst, arg, arg_t);
4669 check type_is_tup_like(bcx, tup_t);
4670 let flag = GEP_tup_like(bcx, tup_t, llretptr, [0, 0]);
4672 // FIXME #1184: Resource flag is larger than necessary
4673 let one = C_int(ccx, 1);
4674 Store(bcx, one, flag.val);
4676 finish_fn(fcx, lltop);
4680 fn trans_tag_variant(cx: @local_ctxt, tag_id: ast::node_id,
4681 variant: ast::variant, index: int, is_degen: bool,
4682 ty_params: [ast::ty_param]) {
4685 if vec::len::<ast::variant_arg>(variant.node.args) == 0u {
4686 ret; // nullary constructors are just constants
4689 // Translate variant arguments to function arguments.
4691 let fn_args: [ast::arg] = [];
4693 for varg: ast::variant_arg in variant.node.args {
4695 [{mode: ast::by_copy,
4697 ident: "arg" + uint::to_str(i, 10u),
4700 assert (ccx.item_ids.contains_key(variant.node.id));
4701 let llfndecl: ValueRef;
4702 alt ccx.item_ids.find(variant.node.id) {
4703 some(x) { llfndecl = x; }
4705 ccx.sess.span_fatal(variant.span,
4706 "unbound variant id in trans_tag_variant");
4709 let fcx = new_fn_ctxt(cx, variant.span, llfndecl);
4710 create_llargs_for_fn_args(fcx, no_self, fn_args, ty_params);
4711 let ty_param_substs: [ty::t] = [];
4713 for tp: ast::ty_param in ty_params {
4714 ty_param_substs += [ty::mk_param(ccx.tcx, i,
4715 ast_util::local_def(tp.id))];
4718 let arg_tys = arg_tys_of_fn(ccx, variant.node.id);
4719 let bcx = new_top_block_ctxt(fcx);
4720 let lltop = bcx.llbb;
4721 bcx = copy_args_to_allocas(fcx, bcx, fn_args, arg_tys);
4723 // Cast the tag to a type we can GEP into.
4729 PointerCast(bcx, fcx.llretptr, T_opaque_tag_ptr(ccx));
4730 let lldiscrimptr = GEPi(bcx, lltagptr, [0, 0]);
4731 Store(bcx, C_int(ccx, index), lldiscrimptr);
4732 GEPi(bcx, lltagptr, [0, 1])
4735 let t_id = ast_util::local_def(tag_id);
4736 let v_id = ast_util::local_def(variant.node.id);
4737 for va: ast::variant_arg in variant.node.args {
4738 check (valid_variant_index(i, bcx, t_id, v_id));
4739 let rslt = GEP_tag(bcx, llblobptr, t_id, v_id, ty_param_substs, i);
4741 let lldestptr = rslt.val;
4742 // If this argument to this function is a tag, it'll have come in to
4743 // this function as an opaque blob due to the way that type_of()
4744 // works. So we have to cast to the destination's view of the type.
4745 let llarg = alt fcx.llargs.find(va.id) { some(local_mem(x)) { x } };
4746 let arg_ty = arg_tys[i].ty;
4747 if ty::type_contains_params(bcx_tcx(bcx), arg_ty) {
4748 lldestptr = PointerCast(bcx, lldestptr, val_ty(llarg));
4750 bcx = memmove_ty(bcx, lldestptr, llarg, arg_ty);
4754 finish_fn(fcx, lltop);
4758 // FIXME: this should do some structural hash-consing to avoid
4759 // duplicate constants. I think. Maybe LLVM has a magical mode
4760 // that does so later on?
4761 fn trans_const_expr(cx: @crate_ctxt, e: @ast::expr) -> ValueRef {
4763 ast::expr_lit(lit) { ret trans_crate_lit(cx, *lit); }
4764 ast::expr_binary(b, e1, e2) {
4765 let te1 = trans_const_expr(cx, e1);
4766 let te2 = trans_const_expr(cx, e2);
4767 /* Neither type is bottom, and we expect them to be unified already,
4768 * so the following is safe. */
4769 let ty = ty::expr_ty(ccx_tcx(cx), e1);
4770 let is_float = ty::type_is_fp(ccx_tcx(cx), ty);
4771 let signed = ty::type_is_signed(ccx_tcx(cx), ty);
4774 if is_float { llvm::LLVMConstFAdd(te1, te2) }
4775 else { llvm::LLVMConstAdd(te1, te2) }
4778 if is_float { llvm::LLVMConstFSub(te1, te2) }
4779 else { llvm::LLVMConstSub(te1, te2) }
4782 if is_float { llvm::LLVMConstFMul(te1, te2) }
4783 else { llvm::LLVMConstMul(te1, te2) }
4786 if is_float { llvm::LLVMConstFDiv(te1, te2) }
4787 else if signed { llvm::LLVMConstSDiv(te1, te2) }
4788 else { llvm::LLVMConstUDiv(te1, te2) }
4791 if is_float { llvm::LLVMConstFRem(te1, te2) }
4792 else if signed { llvm::LLVMConstSRem(te1, te2) }
4793 else { llvm::LLVMConstURem(te1, te2) }
4796 ast::or. { cx.sess.span_unimpl(e.span, "binop logic"); }
4797 ast::bitxor. { llvm::LLVMConstXor(te1, te2) }
4798 ast::bitand. { llvm::LLVMConstAnd(te1, te2) }
4799 ast::bitor. { llvm::LLVMConstOr(te1, te2) }
4800 ast::lsl. { llvm::LLVMConstShl(te1, te2) }
4801 ast::lsr. { llvm::LLVMConstLShr(te1, te2) }
4802 ast::asr. { llvm::LLVMConstAShr(te1, te2) }
4808 ast::gt. { cx.sess.span_unimpl(e.span, "binop comparator"); }
4811 ast::expr_unary(u, e) {
4812 let te = trans_const_expr(cx, e);
4813 let ty = ty::expr_ty(ccx_tcx(cx), e);
4814 let is_float = ty::type_is_fp(ccx_tcx(cx), ty);
4818 ast::deref. { cx.sess.span_bug(e.span,
4819 "bad unop type in trans_const_expr"); }
4820 ast::not. { llvm::LLVMConstNot(te) }
4822 if is_float { llvm::LLVMConstFNeg(te) }
4823 else { llvm::LLVMConstNeg(te) }
4827 _ { cx.sess.span_bug(e.span,
4828 "bad constant expression type in trans_const_expr"); }
4832 fn trans_const(cx: @crate_ctxt, e: @ast::expr, id: ast::node_id) {
4833 let v = trans_const_expr(cx, e);
4835 // The scalars come back as 1st class LLVM vals
4836 // which we have to stick into global constants.
4838 alt cx.consts.find(id) {
4840 llvm::LLVMSetInitializer(g, v);
4841 llvm::LLVMSetGlobalConstant(g, True);
4843 _ { cx.sess.span_fatal(e.span, "Unbound const in trans_const"); }
4847 type c_stack_tys = {
4851 base_fn_ty: TypeRef,
4856 fn c_stack_tys(ccx: @crate_ctxt,
4858 id: ast::node_id) -> @c_stack_tys {
4859 alt ty::struct(ccx.tcx, ty::node_id_to_type(ccx.tcx, id)) {
4860 ty::ty_native_fn(arg_tys, ret_ty) {
4862 let llargtys = type_of_explicit_args(ccx, sp, arg_tys);
4863 check non_ty_var(ccx, ret_ty); // NDM does this truly hold?
4864 let llretty = type_of_inner(ccx, sp, ret_ty);
4865 let bundle_ty = T_struct(llargtys + [T_ptr(llretty)]);
4869 ret_def: !ty::type_is_bot(tcx, ret_ty) &&
4870 !ty::type_is_nil(tcx, ret_ty),
4871 base_fn_ty: T_fn(llargtys, llretty),
4872 bundle_ty: bundle_ty,
4873 shim_fn_ty: T_fn([T_ptr(bundle_ty)], T_void())
4878 ccx.sess.span_fatal(
4880 "Non-function type for native fn");
4885 // For each native function F, we generate a wrapper function W and a shim
4886 // function S that all work together. The wrapper function W is the function
4887 // that other rust code actually invokes. Its job is to marshall the
4888 // arguments into a struct. It then uses a small bit of assembly to switch
4889 // over to the C stack and invoke the shim function. The shim function S then
4890 // unpacks the arguments from the struct and invokes the actual function F
4891 // according to its specified calling convention.
4893 // Example: Given a native c-stack function F(x: X, y: Y) -> Z,
4894 // we generate a wrapper function W that looks like:
4896 // void W(Z* dest, void *env, X x, Y y) {
4897 // struct { X x; Y y; Z *z; } args = { x, y, z };
4898 // call_on_c_stack_shim(S, &args);
4901 // The shim function S then looks something like:
4903 // void S(struct { X x; Y y; Z *z; } *args) {
4904 // *args->z = F(args->x, args->y);
4907 // However, if the return type of F is dynamically sized or of aggregate type,
4908 // the shim function looks like:
4910 // void S(struct { X x; Y y; Z *z; } *args) {
4911 // F(args->z, args->x, args->y);
4914 // Note: on i386, the layout of the args struct is generally the same as the
4915 // desired layout of the arguments on the C stack. Therefore, we could use
4916 // upcall_alloc_c_stack() to allocate the `args` structure and switch the
4917 // stack pointer appropriately to avoid a round of copies. (In fact, the shim
4918 // function itself is unnecessary). We used to do this, in fact, and will
4919 // perhaps do so in the future.
4920 fn trans_native_mod(lcx: @local_ctxt, native_mod: ast::native_mod,
4921 abi: ast::native_abi) {
4922 fn build_shim_fn(lcx: @local_ctxt,
4923 native_item: @ast::native_item,
4925 cc: uint) -> ValueRef {
4926 let lname = link_name(native_item);
4927 let ccx = lcx_ccx(lcx);
4928 let span = native_item.span;
4930 // Declare the "prototype" for the base function F:
4931 let llbasefn = decl_fn(ccx.llmod, lname, cc, tys.base_fn_ty);
4933 // Create the shim function:
4934 let shim_name = lname + "__c_stack_shim";
4935 let llshimfn = decl_internal_cdecl_fn(
4936 ccx.llmod, shim_name, tys.shim_fn_ty);
4938 // Declare the body of the shim function:
4939 let fcx = new_fn_ctxt(lcx, span, llshimfn);
4940 let bcx = new_top_block_ctxt(fcx);
4941 let lltop = bcx.llbb;
4942 let llargbundle = llvm::LLVMGetParam(llshimfn, 0u);
4943 let i = 0u, n = vec::len(tys.arg_tys);
4946 let llargval = load_inbounds(bcx, llargbundle, [0, i as int]);
4947 llargvals += [llargval];
4951 // Create the call itself and store the return value:
4952 let llretval = CallWithConv(bcx, llbasefn, llargvals, cc); // r
4954 // R** llretptr = &args->r;
4955 let llretptr = GEPi(bcx, llargbundle, [0, n as int]);
4956 // R* llretloc = *llretptr; /* (args->r) */
4957 let llretloc = Load(bcx, llretptr);
4959 Store(bcx, llretval, llretloc);
4964 finish_fn(fcx, lltop);
4969 fn build_wrap_fn(lcx: @local_ctxt,
4970 native_item: @ast::native_item,
4974 llwrapfn: ValueRef) {
4975 let span = native_item.span;
4976 let ccx = lcx_ccx(lcx);
4977 let fcx = new_fn_ctxt(lcx, span, llwrapfn);
4978 let bcx = new_top_block_ctxt(fcx);
4979 let lltop = bcx.llbb;
4981 // Allocate the struct and write the arguments into it.
4982 let llargbundle = alloca(bcx, tys.bundle_ty);
4983 let i = 0u, n = vec::len(tys.arg_tys);
4984 let implicit_args = 2u + num_tps; // ret + env
4986 let llargval = llvm::LLVMGetParam(llwrapfn, i + implicit_args);
4987 store_inbounds(bcx, llargval, llargbundle, [0, i as int]);
4990 let llretptr = llvm::LLVMGetParam(llwrapfn, 0u);
4991 store_inbounds(bcx, llretptr, llargbundle, [0, n as int]);
4993 // Create call itself.
4994 let call_shim_on_c_stack = ccx.upcalls.call_shim_on_c_stack;
4995 let llshimfnptr = PointerCast(bcx, llshimfn, T_ptr(T_i8()));
4996 let llrawargbundle = PointerCast(bcx, llargbundle, T_ptr(T_i8()));
4997 Call(bcx, call_shim_on_c_stack, [llrawargbundle, llshimfnptr]);
4999 finish_fn(fcx, lltop);
5002 let ccx = lcx_ccx(lcx);
5003 let cc: uint = lib::llvm::LLVMCCallConv;
5005 ast::native_abi_rust_intrinsic. { ret; }
5006 ast::native_abi_cdecl. { cc = lib::llvm::LLVMCCallConv; }
5007 ast::native_abi_stdcall. { cc = lib::llvm::LLVMX86StdcallCallConv; }
5010 for native_item in native_mod.items {
5011 alt native_item.node {
5012 ast::native_item_ty. {}
5013 ast::native_item_fn(fn_decl, tps) {
5014 let span = native_item.span;
5015 let id = native_item.id;
5016 let tys = c_stack_tys(ccx, span, id);
5017 alt ccx.item_ids.find(id) {
5019 let llshimfn = build_shim_fn(lcx, native_item, tys, cc);
5020 build_wrap_fn(lcx, native_item, tys,
5021 vec::len(tps), llshimfn, llwrapfn);
5025 ccx.sess.span_fatal(
5027 "unbound function item in trans_native_mod");
5035 fn trans_item(cx: @local_ctxt, item: ast::item) {
5037 ast::item_fn(decl, tps, body) {
5038 let sub_cx = extend_path(cx, item.ident);
5039 alt cx.ccx.item_ids.find(item.id) {
5041 trans_fn(sub_cx, item.span, decl, body, llfndecl, no_self, tps,
5045 cx.ccx.sess.span_fatal(item.span,
5046 "unbound function item in trans_item");
5050 ast::item_obj(ob, tps, ctor_id) {
5052 @{obj_typarams: tps, obj_fields: ob.fields
5053 with *extend_path(cx, item.ident)};
5054 trans_obj(sub_cx, item.span, ob, ctor_id, tps);
5056 ast::item_impl(tps, _, _, ms) {
5057 trans_impl::trans_impl(cx, item.ident, ms, item.id, tps);
5059 ast::item_res(decl, tps, body, dtor_id, ctor_id) {
5060 trans_res_ctor(cx, item.span, decl, ctor_id, tps);
5062 // Create a function for the destructor
5063 alt cx.ccx.item_ids.find(item.id) {
5065 trans_fn(cx, item.span, decl, body, lldtor_decl, no_self,
5069 cx.ccx.sess.span_fatal(item.span, "unbound dtor in trans_item");
5075 @{path: cx.path + [item.ident],
5076 module_path: cx.module_path + [item.ident] with *cx};
5077 trans_mod(sub_cx, m);
5079 ast::item_tag(variants, tps) {
5080 let sub_cx = extend_path(cx, item.ident);
5081 let degen = vec::len(variants) == 1u;
5083 for variant: ast::variant in variants {
5084 trans_tag_variant(sub_cx, item.id, variant, i, degen, tps);
5088 ast::item_const(_, expr) { trans_const(cx.ccx, expr, item.id); }
5089 ast::item_native_mod(native_mod) {
5090 let abi = alt attr::native_abi(item.attrs) {
5091 either::right(abi_) { abi_ }
5092 either::left(msg) { cx.ccx.sess.span_fatal(item.span, msg) }
5094 trans_native_mod(cx, native_mod, abi);
5096 _ {/* fall through */ }
5100 // Translate a module. Doing this amounts to translating the items in the
5101 // module; there ends up being no artifact (aside from linkage names) of
5102 // separate modules in the compiled program. That's because modules exist
5103 // only as a convenience for humans working with the code, to organize names
5104 // and control visibility.
5105 fn trans_mod(cx: @local_ctxt, m: ast::_mod) {
5106 for item: @ast::item in m.items { trans_item(cx, *item); }
5109 fn get_pair_fn_ty(llpairty: TypeRef) -> TypeRef {
5110 // Bit of a kludge: pick the fn typeref out of the pair.
5112 ret struct_elt(llpairty, 0u);
5115 fn register_fn(ccx: @crate_ctxt, sp: span, path: [str], flav: str,
5116 ty_params: [ast::ty_param], node_id: ast::node_id) {
5117 // FIXME: pull this out
5118 let t = node_id_type(ccx, node_id);
5119 check returns_non_ty_var(ccx, t);
5120 register_fn_full(ccx, sp, path, flav, ty_params, node_id, t);
5123 fn param_bounds(ccx: @crate_ctxt, tp: ast::ty_param) -> ty::param_bounds {
5124 ccx.tcx.ty_param_bounds.get(tp.id)
5127 fn register_fn_full(ccx: @crate_ctxt, sp: span, path: [str], _flav: str,
5128 tps: [ast::ty_param], node_id: ast::node_id,
5130 : returns_non_ty_var(ccx, node_type) {
5132 let llfty = type_of_fn_from_ty(ccx, sp, node_type,
5133 vec::map(tps, {|p| param_bounds(ccx, p)}));
5134 let ps: str = mangle_exported_name(ccx, path, node_type);
5135 let llfn: ValueRef = decl_cdecl_fn(ccx.llmod, ps, llfty);
5136 ccx.item_ids.insert(node_id, llfn);
5137 ccx.item_symbols.insert(node_id, ps);
5139 let is_main: bool = is_main_name(path) && !ccx.sess.building_library();
5140 if is_main { create_main_wrapper(ccx, sp, llfn, node_type); }
5143 // Create a _rust_main(args: [str]) function which will be called from the
5144 // runtime rust_start function
5145 fn create_main_wrapper(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,
5146 main_node_type: ty::t) {
5148 if ccx.main_fn != none::<ValueRef> {
5149 ccx.sess.span_fatal(sp, "multiple 'main' functions");
5152 let main_takes_argv =
5153 alt ty::struct(ccx.tcx, main_node_type) {
5154 ty::ty_fn({inputs, _}) { vec::len(inputs) != 0u }
5157 let llfn = create_main(ccx, sp, main_llfn, main_takes_argv);
5158 ccx.main_fn = some(llfn);
5159 create_entry_fn(ccx, llfn);
5161 fn create_main(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,
5162 takes_argv: bool) -> ValueRef {
5163 let unit_ty = ty::mk_str(ccx.tcx);
5164 let vecarg_ty: ty::arg =
5166 ty: ty::mk_vec(ccx.tcx, {ty: unit_ty, mut: ast::imm})};
5167 // FIXME: mk_nil should have a postcondition
5168 let nt = ty::mk_nil(ccx.tcx);
5169 let llfty = type_of_fn(ccx, sp, false, [vecarg_ty], nt, []);
5170 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
5171 lib::llvm::LLVMCCallConv, llfty);
5173 let fcx = new_fn_ctxt(new_local_ctxt(ccx), sp, llfdecl);
5175 let bcx = new_top_block_ctxt(fcx);
5176 let lltop = bcx.llbb;
5178 let lloutputarg = llvm::LLVMGetParam(llfdecl, 0u);
5179 let llenvarg = llvm::LLVMGetParam(llfdecl, 1u);
5180 let args = [lloutputarg, llenvarg];
5181 if takes_argv { args += [llvm::LLVMGetParam(llfdecl, 2u)]; }
5182 Call(bcx, main_llfn, args);
5185 finish_fn(fcx, lltop);
5190 fn create_entry_fn(ccx: @crate_ctxt, rust_main: ValueRef) {
5191 #[cfg(target_os = "win32")]
5192 fn main_name() -> str { ret "WinMain@16"; }
5193 #[cfg(target_os = "macos")]
5194 fn main_name() -> str { ret "main"; }
5195 #[cfg(target_os = "linux")]
5196 fn main_name() -> str { ret "main"; }
5197 #[cfg(target_os = "freebsd")]
5198 fn main_name() -> str { ret "main"; }
5199 let llfty = T_fn([ccx.int_type, ccx.int_type], ccx.int_type);
5200 let llfn = decl_cdecl_fn(ccx.llmod, main_name(), llfty);
5201 let llbb = str::as_buf("top", {|buf|
5202 llvm::LLVMAppendBasicBlock(llfn, buf)
5204 let bld = *ccx.builder;
5205 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
5206 let crate_map = ccx.crate_map;
5207 let start_ty = T_fn([val_ty(rust_main), ccx.int_type, ccx.int_type,
5208 val_ty(crate_map)], ccx.int_type);
5209 let start = str::as_buf("rust_start", {|buf|
5210 llvm::LLVMAddGlobal(ccx.llmod, start_ty, buf)
5212 let args = [rust_main, llvm::LLVMGetParam(llfn, 0u),
5213 llvm::LLVMGetParam(llfn, 1u), crate_map];
5214 let result = unsafe {
5215 llvm::LLVMBuildCall(bld, start, vec::to_ptr(args),
5216 vec::len(args), noname())
5218 llvm::LLVMBuildRet(bld, result);
5222 // Create a /real/ closure: this is like create_fn_pair, but creates a
5223 // a fn value on the stack with a specified environment (which need not be
5225 fn create_real_fn_pair(cx: @block_ctxt, llfnty: TypeRef, llfn: ValueRef,
5226 llenvptr: ValueRef) -> ValueRef {
5227 let lcx = cx.fcx.lcx;
5229 let pair = alloca(cx, T_fn_pair(lcx.ccx, llfnty));
5230 fill_fn_pair(cx, pair, llfn, llenvptr);
5234 fn fill_fn_pair(bcx: @block_ctxt, pair: ValueRef, llfn: ValueRef,
5235 llenvptr: ValueRef) {
5236 let ccx = bcx_ccx(bcx);
5237 let code_cell = GEPi(bcx, pair, [0, abi::fn_field_code]);
5238 Store(bcx, llfn, code_cell);
5239 let env_cell = GEPi(bcx, pair, [0, abi::fn_field_box]);
5241 PointerCast(bcx, llenvptr, T_opaque_cbox_ptr(ccx));
5242 Store(bcx, llenvblobptr, env_cell);
5245 // Returns the number of type parameters that the given native function has.
5246 fn native_fn_ty_param_count(cx: @crate_ctxt, id: ast::node_id) -> uint {
5249 alt cx.ast_map.find(id) { some(ast_map::node_native_item(i)) { i } };
5250 alt native_item.node {
5251 ast::native_item_ty. {
5252 cx.sess.bug("register_native_fn(): native fn isn't \
5255 ast::native_item_fn(_, tps) {
5256 count = vec::len::<ast::ty_param>(tps);
5262 fn native_fn_wrapper_type(cx: @crate_ctxt, sp: span,
5263 param_bounds: [ty::param_bounds],
5264 x: ty::t) -> TypeRef {
5265 alt ty::struct(cx.tcx, x) {
5266 ty::ty_native_fn(args, out) {
5267 ret type_of_fn(cx, sp, false, args, out, param_bounds);
5272 fn raw_native_fn_type(ccx: @crate_ctxt, sp: span, args: [ty::arg],
5273 ret_ty: ty::t) -> TypeRef {
5274 check type_has_static_size(ccx, ret_ty);
5275 ret T_fn(type_of_explicit_args(ccx, sp, args), type_of(ccx, sp, ret_ty));
5278 fn link_name(i: @ast::native_item) -> str {
5279 alt attr::get_meta_item_value_str_by_name(i.attrs, "link_name") {
5280 none. { ret i.ident; }
5281 option::some(ln) { ret ln; }
5285 fn collect_native_item(ccx: @crate_ctxt,
5286 abi: @mutable option::t<ast::native_abi>,
5287 i: @ast::native_item,
5291 ast::native_item_fn(_, tps) {
5294 let node_type = node_id_type(ccx, id);
5296 alt attr::get_meta_item_value_str_by_name(i.attrs, "abi") {
5298 // if abi isn't specified for this function, inherit from
5299 // its enclosing native module
5303 alt attr::native_abi(i.attrs) {
5304 either::right(abi_) { abi_ }
5305 either::left(msg) { ccx.sess.span_fatal(i.span, msg) }
5310 ast::native_abi_rust_intrinsic. {
5311 // For intrinsics: link the function directly to the intrinsic
5313 let fn_type = type_of_fn_from_ty(
5315 vec::map(tps, {|p| param_bounds(ccx, p)}));
5316 let ri_name = "rust_intrinsic_" + link_name(i);
5317 let llnativefn = get_extern_fn(
5318 ccx.externs, ccx.llmod, ri_name,
5319 lib::llvm::LLVMCCallConv, fn_type);
5320 ccx.item_ids.insert(id, llnativefn);
5321 ccx.item_symbols.insert(id, ri_name);
5324 ast::native_abi_cdecl. | ast::native_abi_stdcall. {
5325 // For true external functions: create a rust wrapper
5326 // and link to that. The rust wrapper will handle
5327 // switching to the C stack.
5328 let new_pt = pt + [i.ident];
5329 register_fn(ccx, i.span, new_pt, "native fn", tps, i.id);
5337 fn collect_item(ccx: @crate_ctxt, abi: @mutable option::t<ast::native_abi>,
5338 i: @ast::item, &&pt: [str], v: vt<[str]>) {
5339 let new_pt = pt + [i.ident];
5341 ast::item_const(_, _) {
5342 let typ = node_id_type(ccx, i.id);
5344 mangle_exported_name(ccx, pt + [i.ident],
5345 node_id_type(ccx, i.id));
5346 // FIXME: Could follow from a constraint on types of const
5348 let g = str::as_buf(s, {|buf|
5349 check (type_has_static_size(ccx, typ));
5350 llvm::LLVMAddGlobal(ccx.llmod, type_of(ccx, i.span, typ), buf)
5352 ccx.item_symbols.insert(i.id, s);
5353 ccx.consts.insert(i.id, g);
5355 ast::item_native_mod(native_mod) {
5356 // Propagate the native ABI down to collect_native_item(),
5357 alt attr::native_abi(i.attrs) {
5358 either::left(msg) { ccx.sess.span_fatal(i.span, msg); }
5359 either::right(abi_) {
5360 *abi = option::some(abi_);
5364 ast::item_fn(_, tps, _) {
5365 register_fn(ccx, i.span, new_pt, "fn", tps, i.id);
5367 ast::item_obj(ob, tps, ctor_id) {
5368 register_fn(ccx, i.span, new_pt, "obj_ctor", tps, ctor_id);
5370 ast::item_impl(tps, _, _, methods) {
5371 let name = i.ident + int::str(i.id);
5373 register_fn(ccx, i.span, pt + [name, m.ident],
5374 "impl_method", tps + m.tps, m.id);
5377 ast::item_res(_, tps, _, dtor_id, ctor_id) {
5378 register_fn(ccx, i.span, new_pt, "res_ctor", tps, ctor_id);
5379 // Note that the destructor is associated with the item's id, not
5380 // the dtor_id. This is a bit counter-intuitive, but simplifies
5381 // ty_res, which would have to carry around two def_ids otherwise
5382 // -- one to identify the type, and one to find the dtor symbol.
5383 let t = node_id_type(ccx, dtor_id);
5384 // FIXME: how to get rid of this check?
5385 check returns_non_ty_var(ccx, t);
5386 register_fn_full(ccx, i.span, new_pt, "res_dtor", tps, i.id, t);
5388 ast::item_tag(variants, tps) {
5389 for variant in variants {
5390 if vec::len(variant.node.args) != 0u {
5391 register_fn(ccx, i.span, new_pt + [variant.node.name],
5392 "tag", tps, variant.node.id);
5398 visit::visit_item(i, new_pt, v);
5401 fn collect_items(ccx: @crate_ctxt, crate: @ast::crate) {
5402 let abi = @mutable none::<ast::native_abi>;
5403 visit::visit_crate(*crate, [], visit::mk_vt(@{
5404 visit_native_item: bind collect_native_item(ccx, abi, _, _, _),
5405 visit_item: bind collect_item(ccx, abi, _, _, _)
5406 with *visit::default_visitor()
5410 // The constant translation pass.
5411 fn trans_constant(ccx: @crate_ctxt, it: @ast::item, &&pt: [str],
5413 let new_pt = pt + [it.ident];
5414 visit::visit_item(it, new_pt, v);
5416 ast::item_tag(variants, _) {
5418 for variant in variants {
5419 let p = new_pt + [variant.node.name, "discrim"];
5420 let s = mangle_exported_name(ccx, p, ty::mk_int(ccx.tcx));
5421 let discrim_gvar = str::as_buf(s, {|buf|
5422 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
5424 llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, i as int));
5425 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
5426 ccx.discrims.insert(
5427 ast_util::local_def(variant.node.id), discrim_gvar);
5428 ccx.discrim_symbols.insert(variant.node.id, s);
5432 ast::item_impl(tps, some(@{node: ast::ty_path(_, id), _}), _, ms) {
5433 let i_did = ast_util::def_id_of_def(ccx.tcx.def_map.get(id));
5434 let ty = ty::lookup_item_type(ccx.tcx, i_did).ty;
5435 let new_pt = pt + [it.ident + int::str(it.id), "wrap"];
5436 let extra_tps = vec::map(tps, {|p| param_bounds(ccx, p)});
5437 let tbl = C_struct(vec::map(*ty::iface_methods(ccx.tcx, i_did), {|im|
5438 alt vec::find(ms, {|m| m.ident == im.ident}) {
5440 trans_impl::trans_wrapper(ccx, new_pt, extra_tps, m)
5444 let s = mangle_exported_name(ccx, new_pt + ["!vtable"], ty);
5445 let vt_gvar = str::as_buf(s, {|buf|
5446 llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf)
5448 llvm::LLVMSetInitializer(vt_gvar, tbl);
5449 llvm::LLVMSetGlobalConstant(vt_gvar, True);
5450 ccx.item_ids.insert(it.id, vt_gvar);
5451 ccx.item_symbols.insert(it.id, s);
5457 fn trans_constants(ccx: @crate_ctxt, crate: @ast::crate) {
5459 @{visit_item: bind trans_constant(ccx, _, _, _)
5460 with *visit::default_visitor()};
5461 visit::visit_crate(*crate, [], visit::mk_vt(visitor));
5464 fn vp2i(cx: @block_ctxt, v: ValueRef) -> ValueRef {
5465 let ccx = bcx_ccx(cx);
5466 ret PtrToInt(cx, v, ccx.int_type);
5469 fn p2i(ccx: @crate_ctxt, v: ValueRef) -> ValueRef {
5470 ret llvm::LLVMConstPtrToInt(v, ccx.int_type);
5473 fn declare_intrinsics(llmod: ModuleRef) -> hashmap<str, ValueRef> {
5474 let T_memmove32_args: [TypeRef] =
5475 [T_ptr(T_i8()), T_ptr(T_i8()), T_i32(), T_i32(), T_i1()];
5476 let T_memmove64_args: [TypeRef] =
5477 [T_ptr(T_i8()), T_ptr(T_i8()), T_i64(), T_i32(), T_i1()];
5478 let T_memset32_args: [TypeRef] =
5479 [T_ptr(T_i8()), T_i8(), T_i32(), T_i32(), T_i1()];
5480 let T_memset64_args: [TypeRef] =
5481 [T_ptr(T_i8()), T_i8(), T_i64(), T_i32(), T_i1()];
5482 let T_trap_args: [TypeRef] = [];
5484 decl_cdecl_fn(llmod, "llvm.gcroot",
5485 T_fn([T_ptr(T_ptr(T_i8())), T_ptr(T_i8())], T_void()));
5487 decl_cdecl_fn(llmod, "llvm.gcread",
5488 T_fn([T_ptr(T_i8()), T_ptr(T_ptr(T_i8()))], T_void()));
5490 decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i32",
5491 T_fn(T_memmove32_args, T_void()));
5493 decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i64",
5494 T_fn(T_memmove64_args, T_void()));
5496 decl_cdecl_fn(llmod, "llvm.memset.p0i8.i32",
5497 T_fn(T_memset32_args, T_void()));
5499 decl_cdecl_fn(llmod, "llvm.memset.p0i8.i64",
5500 T_fn(T_memset64_args, T_void()));
5501 let trap = decl_cdecl_fn(llmod, "llvm.trap", T_fn(T_trap_args, T_void()));
5502 let intrinsics = new_str_hash::<ValueRef>();
5503 intrinsics.insert("llvm.gcroot", gcroot);
5504 intrinsics.insert("llvm.gcread", gcread);
5505 intrinsics.insert("llvm.memmove.p0i8.p0i8.i32", memmove32);
5506 intrinsics.insert("llvm.memmove.p0i8.p0i8.i64", memmove64);
5507 intrinsics.insert("llvm.memset.p0i8.i32", memset32);
5508 intrinsics.insert("llvm.memset.p0i8.i64", memset64);
5509 intrinsics.insert("llvm.trap", trap);
5513 fn declare_dbg_intrinsics(llmod: ModuleRef,
5514 intrinsics: hashmap<str, ValueRef>) {
5516 decl_cdecl_fn(llmod, "llvm.dbg.declare",
5517 T_fn([T_metadata(), T_metadata()], T_void()));
5519 decl_cdecl_fn(llmod, "llvm.dbg.value",
5520 T_fn([T_metadata(), T_i64(), T_metadata()], T_void()));
5521 intrinsics.insert("llvm.dbg.declare", declare);
5522 intrinsics.insert("llvm.dbg.value", value);
5525 fn trap(bcx: @block_ctxt) {
5526 let v: [ValueRef] = [];
5527 alt bcx_ccx(bcx).intrinsics.find("llvm.trap") {
5528 some(x) { Call(bcx, x, v); }
5529 _ { bcx_ccx(bcx).sess.bug("unbound llvm.trap in trap"); }
5533 fn create_module_map(ccx: @crate_ctxt) -> ValueRef {
5534 let elttype = T_struct([ccx.int_type, ccx.int_type]);
5535 let maptype = T_array(elttype, ccx.module_data.size() + 1u);
5537 str::as_buf("_rust_mod_map",
5538 {|buf| llvm::LLVMAddGlobal(ccx.llmod, maptype, buf) });
5539 llvm::LLVMSetLinkage(map,
5540 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
5541 let elts: [ValueRef] = [];
5542 ccx.module_data.items {|key, val|
5543 let elt = C_struct([p2i(ccx, C_cstr(ccx, key)),
5547 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
5549 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
5554 fn decl_crate_map(sess: session::session, mapname: str,
5555 llmod: ModuleRef) -> ValueRef {
5556 let targ_cfg = sess.get_targ_cfg();
5557 let int_type = T_int(targ_cfg);
5558 let n_subcrates = 1;
5559 let cstore = sess.get_cstore();
5560 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
5561 let mapname = sess.building_library() ? mapname : "toplevel";
5562 let sym_name = "_rust_crate_map_" + mapname;
5563 let arrtype = T_array(int_type, n_subcrates as uint);
5564 let maptype = T_struct([int_type, arrtype]);
5565 let map = str::as_buf(sym_name, {|buf|
5566 llvm::LLVMAddGlobal(llmod, maptype, buf)
5568 llvm::LLVMSetLinkage(map, lib::llvm::LLVMExternalLinkage
5573 // FIXME use hashed metadata instead of crate names once we have that
5574 fn fill_crate_map(ccx: @crate_ctxt, map: ValueRef) {
5575 let subcrates: [ValueRef] = [];
5577 let cstore = ccx.sess.get_cstore();
5578 while cstore::have_crate_data(cstore, i) {
5579 let nm = "_rust_crate_map_" + cstore::get_crate_data(cstore, i).name;
5580 let cr = str::as_buf(nm, {|buf|
5581 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
5583 subcrates += [p2i(ccx, cr)];
5586 subcrates += [C_int(ccx, 0)];
5587 llvm::LLVMSetInitializer(map, C_struct(
5588 [p2i(ccx, create_module_map(ccx)),
5589 C_array(ccx.int_type, subcrates)]));
5592 fn write_metadata(cx: @crate_ctxt, crate: @ast::crate) {
5593 if !cx.sess.building_library() { ret; }
5594 let llmeta = C_postr(metadata::encoder::encode_metadata(cx, crate));
5595 let llconst = trans_common::C_struct([llmeta]);
5597 str::as_buf("rust_metadata",
5599 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst), buf)
5601 llvm::LLVMSetInitializer(llglobal, llconst);
5603 str::as_buf(cx.sess.get_targ_cfg().target_strs.meta_sect_name,
5604 {|buf| llvm::LLVMSetSection(llglobal, buf) });
5605 llvm::LLVMSetLinkage(llglobal,
5606 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
5608 let t_ptr_i8 = T_ptr(T_i8());
5609 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8);
5611 str::as_buf("llvm.used",
5613 llvm::LLVMAddGlobal(cx.llmod, T_array(t_ptr_i8, 1u),
5616 llvm::LLVMSetLinkage(llvm_used,
5617 lib::llvm::LLVMAppendingLinkage as llvm::Linkage);
5618 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
5621 // Writes the current ABI version into the crate.
5622 fn write_abi_version(ccx: @crate_ctxt) {
5623 shape::mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version),
5627 fn trans_crate(sess: session::session, crate: @ast::crate, tcx: ty::ctxt,
5628 output: str, emap: resolve::exp_map, amap: ast_map::map,
5629 mut_map: mut::mut_map, copy_map: alias::copy_map,
5630 last_uses: last_use::last_uses, method_map: typeck::method_map,
5631 dict_map: typeck::dict_map)
5632 -> (ModuleRef, link::link_meta) {
5633 let sha = std::sha1::mk_sha1();
5634 let link_meta = link::build_link_meta(sess, *crate, output, sha);
5636 // Append ".rc" to crate name as LLVM module identifier.
5638 // LLVM code generator emits a ".file filename" directive
5639 // for ELF backends. Value of the "filename" is set as the
5640 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
5641 // crashes if the module identifer is same as other symbols
5642 // such as a function name in the module.
5643 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
5644 let llmod_id = link_meta.name + ".rc";
5646 let llmod = str::as_buf(llmod_id, {|buf|
5647 llvm::LLVMModuleCreateWithNameInContext
5648 (buf, llvm::LLVMGetGlobalContext())
5650 let data_layout = sess.get_targ_cfg().target_strs.data_layout;
5651 let targ_triple = sess.get_targ_cfg().target_strs.target_triple;
5653 str::as_buf(data_layout,
5654 {|buf| llvm::LLVMSetDataLayout(llmod, buf) });
5656 str::as_buf(targ_triple,
5657 {|buf| llvm::LLVMSetTarget(llmod, buf) });
5658 let targ_cfg = sess.get_targ_cfg();
5659 let td = mk_target_data(sess.get_targ_cfg().target_strs.data_layout);
5660 let tn = mk_type_names();
5661 let intrinsics = declare_intrinsics(llmod);
5662 if sess.get_opts().extra_debuginfo {
5663 declare_dbg_intrinsics(llmod, intrinsics);
5665 let int_type = T_int(targ_cfg);
5666 let float_type = T_float(targ_cfg);
5667 let task_type = T_task(targ_cfg);
5668 let taskptr_type = T_ptr(task_type);
5669 tn.associate("taskptr", taskptr_type);
5670 let tydesc_type = T_tydesc(targ_cfg);
5671 tn.associate("tydesc", tydesc_type);
5672 let crate_map = decl_crate_map(sess, link_meta.name, llmod);
5673 let dbg_cx = if sess.get_opts().debuginfo {
5674 option::some(@{llmetadata: map::new_int_hash(),
5684 externs: new_str_hash::<ValueRef>(),
5685 intrinsics: intrinsics,
5686 item_ids: new_int_hash::<ValueRef>(),
5689 item_symbols: new_int_hash::<str>(),
5690 mutable main_fn: none::<ValueRef>,
5691 link_meta: link_meta,
5692 tag_sizes: ty::new_ty_hash(),
5693 discrims: ast_util::new_def_id_hash::<ValueRef>(),
5694 discrim_symbols: new_int_hash::<str>(),
5695 consts: new_int_hash::<ValueRef>(),
5696 tydescs: ty::new_ty_hash(),
5697 dicts: map::mk_hashmap(hash_dict_id, {|a, b| a == b}),
5698 module_data: new_str_hash::<ValueRef>(),
5699 lltypes: ty::new_ty_hash(),
5702 type_sha1s: ty::new_ty_hash(),
5703 type_short_names: ty::new_ty_hash(),
5707 last_uses: last_uses,
5708 method_map: method_map,
5711 {mutable n_static_tydescs: 0u,
5712 mutable n_derived_tydescs: 0u,
5713 mutable n_glues_created: 0u,
5714 mutable n_null_glues: 0u,
5715 mutable n_real_glues: 0u,
5716 fn_times: @mutable []},
5718 upcall::declare_upcalls(targ_cfg, tn, tydesc_type,
5720 rust_object_type: T_rust_object(),
5721 tydesc_type: tydesc_type,
5723 float_type: float_type,
5724 task_type: task_type,
5725 opaque_vec_type: T_opaque_vec(targ_cfg),
5726 builder: BuilderRef_res(llvm::LLVMCreateBuilder()),
5727 shape_cx: shape::mk_ctxt(llmod),
5728 gc_cx: gc::mk_ctxt(),
5729 crate_map: crate_map,
5731 let cx = new_local_ctxt(ccx);
5732 collect_items(ccx, crate);
5733 trans_constants(ccx, crate);
5734 trans_mod(cx, crate.node.module);
5735 fill_crate_map(ccx, crate_map);
5737 shape::gen_shape_tables(ccx);
5738 write_abi_version(ccx);
5740 // Translate the metadata.
5741 write_metadata(cx.ccx, crate);
5742 if ccx.sess.get_opts().stats {
5743 #error("--- trans stats ---");
5744 #error("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
5745 #error("n_derived_tydescs: %u", ccx.stats.n_derived_tydescs);
5746 #error("n_glues_created: %u", ccx.stats.n_glues_created);
5747 #error("n_null_glues: %u", ccx.stats.n_null_glues);
5748 #error("n_real_glues: %u", ccx.stats.n_real_glues);
5750 for timing: {ident: str, time: int} in *ccx.stats.fn_times {
5751 #error("time: %s took %d ms", timing.ident, timing.time);
5754 ret (llmod, link_meta);
5760 // indent-tabs-mode: nil
5761 // c-basic-offset: 4
5762 // buffer-file-coding-system: utf-8-unix