]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/expr.rs
rollup merge of #19577: aidancully/master
[rust.git] / src / librustc_trans / trans / expr.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! # Translation of Expressions
12 //!
13 //! Public entry points:
14 //!
15 //! - `trans_into(bcx, expr, dest) -> bcx`: evaluates an expression,
16 //!   storing the result into `dest`. This is the preferred form, if you
17 //!   can manage it.
18 //!
19 //! - `trans(bcx, expr) -> DatumBlock`: evaluates an expression, yielding
20 //!   `Datum` with the result. You can then store the datum, inspect
21 //!   the value, etc. This may introduce temporaries if the datum is a
22 //!   structural type.
23 //!
24 //! - `trans_to_lvalue(bcx, expr, "...") -> DatumBlock`: evaluates an
25 //!   expression and ensures that the result has a cleanup associated with it,
26 //!   creating a temporary stack slot if necessary.
27 //!
28 //! - `trans_local_var -> Datum`: looks up a local variable or upvar.
29 //!
30 //! See doc.rs for more comments.
31
32 #![allow(non_camel_case_types)]
33
34 pub use self::cast_kind::*;
35 pub use self::Dest::*;
36 use self::lazy_binop_ty::*;
37
38 use back::abi;
39 use llvm::{mod, ValueRef};
40 use middle::def;
41 use middle::mem_categorization::Typer;
42 use middle::subst::{mod, Subst};
43 use trans::{_match, adt, asm, base, callee, closure, consts, controlflow};
44 use trans::base::*;
45 use trans::build::*;
46 use trans::cleanup::{mod, CleanupMethods};
47 use trans::common::*;
48 use trans::datum::*;
49 use trans::debuginfo;
50 use trans::glue;
51 use trans::machine;
52 use trans::meth;
53 use trans::inline;
54 use trans::tvec;
55 use trans::type_of;
56 use middle::ty::{struct_fields, tup_fields};
57 use middle::ty::{AdjustDerefRef, AdjustAddEnv, AutoUnsafe};
58 use middle::ty::{AutoPtr};
59 use middle::ty::{mod, Ty};
60 use middle::ty::MethodCall;
61 use util::common::indenter;
62 use util::ppaux::Repr;
63 use trans::machine::{llsize_of, llsize_of_alloc};
64 use trans::type_::Type;
65
66 use syntax::{ast, ast_util, codemap};
67 use syntax::print::pprust::{expr_to_string};
68 use syntax::ptr::P;
69 use std::rc::Rc;
70
71 // Destinations
72
73 // These are passed around by the code generating functions to track the
74 // destination of a computation's value.
75
76 #[deriving(PartialEq)]
77 pub enum Dest {
78     SaveIn(ValueRef),
79     Ignore,
80 }
81
82 impl Copy for Dest {}
83
84 impl Dest {
85     pub fn to_string(&self, ccx: &CrateContext) -> String {
86         match *self {
87             SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
88             Ignore => "Ignore".to_string()
89         }
90     }
91 }
92
93 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
94 /// better optimized LLVM code.
95 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
96                               expr: &ast::Expr,
97                               dest: Dest)
98                               -> Block<'blk, 'tcx> {
99     let mut bcx = bcx;
100
101     if bcx.tcx().adjustments.borrow().contains_key(&expr.id) {
102         // use trans, which may be less efficient but
103         // which will perform the adjustments:
104         let datum = unpack_datum!(bcx, trans(bcx, expr));
105         return datum.store_to_dest(bcx, dest, expr.id)
106     }
107
108     debug!("trans_into() expr={}", expr.repr(bcx.tcx()));
109
110     let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
111                                                                           expr.id,
112                                                                           expr.span,
113                                                                           false);
114     bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
115
116     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
117     let kind = ty::expr_kind(bcx.tcx(), expr);
118     bcx = match kind {
119         ty::LvalueExpr | ty::RvalueDatumExpr => {
120             trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
121         }
122         ty::RvalueDpsExpr => {
123             trans_rvalue_dps_unadjusted(bcx, expr, dest)
124         }
125         ty::RvalueStmtExpr => {
126             trans_rvalue_stmt_unadjusted(bcx, expr)
127         }
128     };
129
130     bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
131 }
132
133 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
134 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
135 /// stack.
136 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
137                          expr: &ast::Expr)
138                          -> DatumBlock<'blk, 'tcx, Expr> {
139     debug!("trans(expr={})", bcx.expr_to_string(expr));
140
141     let mut bcx = bcx;
142     let fcx = bcx.fcx;
143
144     let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
145                                                                           expr.id,
146                                                                           expr.span,
147                                                                           false);
148     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
149     let datum = unpack_datum!(bcx, trans_unadjusted(bcx, expr));
150     let datum = unpack_datum!(bcx, apply_adjustments(bcx, expr, datum));
151     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
152     return DatumBlock::new(bcx, datum);
153 }
154
155 pub fn get_len(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
156     GEPi(bcx, fat_ptr, &[0u, abi::FAT_PTR_EXTRA])
157 }
158
159 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
160     GEPi(bcx, fat_ptr, &[0u, abi::FAT_PTR_ADDR])
161 }
162
163 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
164 /// translation of `expr`.
165 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
166                                  expr: &ast::Expr,
167                                  datum: Datum<'tcx, Expr>)
168                                  -> DatumBlock<'blk, 'tcx, Expr> {
169     let mut bcx = bcx;
170     let mut datum = datum;
171     let adjustment = match bcx.tcx().adjustments.borrow().get(&expr.id).cloned() {
172         None => {
173             return DatumBlock::new(bcx, datum);
174         }
175         Some(adj) => { adj }
176     };
177     debug!("unadjusted datum for expr {}: {}, adjustment={}",
178            expr.repr(bcx.tcx()),
179            datum.to_string(bcx.ccx()),
180            adjustment.repr(bcx.tcx()));
181     match adjustment {
182         AdjustAddEnv(..) => {
183             datum = unpack_datum!(bcx, add_env(bcx, expr, datum));
184         }
185         AdjustDerefRef(ref adj) => {
186             let (autoderefs, use_autoref) = match adj.autoref {
187                 // Extracting a value from a box counts as a deref, but if we are
188                 // just converting Box<[T, ..n]> to Box<[T]> we aren't really doing
189                 // a deref (and wouldn't if we could treat Box like a normal struct).
190                 Some(ty::AutoUnsizeUniq(..)) => (adj.autoderefs - 1, true),
191                 // We are a bit paranoid about adjustments and thus might have a re-
192                 // borrow here which merely derefs and then refs again (it might have
193                 // a different region or mutability, but we don't care here. It might
194                 // also be just in case we need to unsize. But if there are no nested
195                 // adjustments then it should be a no-op).
196                 Some(ty::AutoPtr(_, _, None)) if adj.autoderefs == 1 => {
197                     match datum.ty.sty {
198                         // Don't skip a conversion from Box<T> to &T, etc.
199                         ty::ty_rptr(..) => {
200                             let method_call = MethodCall::autoderef(expr.id, adj.autoderefs-1);
201                             let method = bcx.tcx().method_map.borrow().get(&method_call).is_some();
202                             if method {
203                                 // Don't skip an overloaded deref.
204                                 (adj.autoderefs, true)
205                             } else {
206                                 (adj.autoderefs - 1, false)
207                             }
208                         }
209                         _ => (adj.autoderefs, true),
210                     }
211                 }
212                 _ => (adj.autoderefs, true)
213             };
214
215             if autoderefs > 0 {
216                 // Schedule cleanup.
217                 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
218                 datum = unpack_datum!(
219                     bcx, deref_multiple(bcx, expr, lval.to_expr_datum(), autoderefs));
220             }
221
222             // (You might think there is a more elegant way to do this than a
223             // use_autoref bool, but then you remember that the borrow checker exists).
224             if let (true, &Some(ref a)) = (use_autoref, &adj.autoref) {
225                 datum = unpack_datum!(bcx, apply_autoref(a,
226                                                          bcx,
227                                                          expr,
228                                                          datum));
229             }
230         }
231     }
232     debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
233     return DatumBlock::new(bcx, datum);
234
235     fn apply_autoref<'blk, 'tcx>(autoref: &ty::AutoRef<'tcx>,
236                                  bcx: Block<'blk, 'tcx>,
237                                  expr: &ast::Expr,
238                                  datum: Datum<'tcx, Expr>)
239                                  -> DatumBlock<'blk, 'tcx, Expr> {
240         let mut bcx = bcx;
241         let mut datum = datum;
242
243         let datum = match autoref {
244             &AutoPtr(_, _, ref a) | &AutoUnsafe(_, ref a) => {
245                 debug!("  AutoPtr");
246                 match a {
247                     &Some(box ref a) => {
248                         datum = unpack_datum!(bcx, apply_autoref(a, bcx, expr, datum));
249                     }
250                     &None => {}
251                 }
252                 unpack_datum!(bcx, ref_ptr(bcx, expr, datum))
253             }
254             &ty::AutoUnsize(ref k) => {
255                 debug!("  AutoUnsize");
256                 unpack_datum!(bcx, unsize_expr(bcx, expr, datum, k))
257             }
258
259             &ty::AutoUnsizeUniq(ty::UnsizeLength(len)) => {
260                 debug!("  AutoUnsizeUniq(UnsizeLength)");
261                 unpack_datum!(bcx, unsize_unique_vec(bcx, expr, datum, len))
262             }
263             &ty::AutoUnsizeUniq(ref k) => {
264                 debug!("  AutoUnsizeUniq");
265                 unpack_datum!(bcx, unsize_unique_expr(bcx, expr, datum, k))
266             }
267         };
268
269         DatumBlock::new(bcx, datum)
270     }
271
272     fn ref_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
273                            expr: &ast::Expr,
274                            datum: Datum<'tcx, Expr>)
275                            -> DatumBlock<'blk, 'tcx, Expr> {
276         debug!("ref_ptr(expr={}, datum={})",
277                expr.repr(bcx.tcx()),
278                datum.to_string(bcx.ccx()));
279
280         if !ty::type_is_sized(bcx.tcx(), datum.ty) {
281             debug!("Taking address of unsized type {}",
282                    bcx.ty_to_string(datum.ty));
283             ref_fat_ptr(bcx, expr, datum)
284         } else {
285             debug!("Taking address of sized type {}",
286                    bcx.ty_to_string(datum.ty));
287             auto_ref(bcx, datum, expr)
288         }
289     }
290
291     // Retrieve the information we are losing (making dynamic) in an unsizing
292     // adjustment.
293     // When making a dtor, we need to do different things depending on the
294     // ownership of the object.. mk_ty is a function for turning `unadjusted_ty`
295     // into a type to be destructed. If we want to end up with a Box pointer,
296     // then mk_ty should make a Box pointer (T -> Box<T>), if we want a
297     // borrowed reference then it should be T -> &T.
298     fn unsized_info<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
299                                 kind: &ty::UnsizeKind<'tcx>,
300                                 id: ast::NodeId,
301                                 unadjusted_ty: Ty<'tcx>,
302                                 mk_ty: |Ty<'tcx>| -> Ty<'tcx>) -> ValueRef {
303         debug!("unsized_info(kind={}, id={}, unadjusted_ty={})",
304                kind, id, unadjusted_ty.repr(bcx.tcx()));
305         match kind {
306             &ty::UnsizeLength(len) => C_uint(bcx.ccx(), len),
307             &ty::UnsizeStruct(box ref k, tp_index) => match unadjusted_ty.sty {
308                 ty::ty_struct(_, ref substs) => {
309                     let ty_substs = substs.types.get_slice(subst::TypeSpace);
310                     // The dtor for a field treats it like a value, so mk_ty
311                     // should just be the identity function.
312                     unsized_info(bcx, k, id, ty_substs[tp_index], |t| t)
313                 }
314                 _ => bcx.sess().bug(format!("UnsizeStruct with bad sty: {}",
315                                           bcx.ty_to_string(unadjusted_ty)).as_slice())
316             },
317             &ty::UnsizeVtable(ty::TyTrait { ref principal, .. }, _) => {
318                 let substs = principal.substs.with_self_ty(unadjusted_ty).erase_regions();
319                 let trait_ref =
320                     Rc::new(ty::TraitRef { def_id: principal.def_id,
321                                            substs: substs });
322                 let trait_ref = trait_ref.subst(bcx.tcx(), bcx.fcx.param_substs);
323                 let box_ty = mk_ty(unadjusted_ty);
324                 PointerCast(bcx,
325                             meth::get_vtable(bcx, box_ty, trait_ref),
326                             Type::vtable_ptr(bcx.ccx()))
327             }
328         }
329     }
330
331     fn unsize_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
332                                expr: &ast::Expr,
333                                datum: Datum<'tcx, Expr>,
334                                k: &ty::UnsizeKind<'tcx>)
335                                -> DatumBlock<'blk, 'tcx, Expr> {
336         let tcx = bcx.tcx();
337         let datum_ty = datum.ty;
338         let unsized_ty = ty::unsize_ty(tcx, datum_ty, k, expr.span);
339         debug!("unsized_ty={}", unsized_ty.repr(bcx.tcx()));
340         let dest_ty = ty::mk_open(tcx, unsized_ty);
341         debug!("dest_ty={}", unsized_ty.repr(bcx.tcx()));
342         // Closures for extracting and manipulating the data and payload parts of
343         // the fat pointer.
344         let base = match k {
345             &ty::UnsizeStruct(..) =>
346                 |bcx, val| PointerCast(bcx,
347                                        val,
348                                        type_of::type_of(bcx.ccx(), unsized_ty).ptr_to()),
349             &ty::UnsizeLength(..) =>
350                 |bcx, val| GEPi(bcx, val, &[0u, 0u]),
351             &ty::UnsizeVtable(..) =>
352                 |_bcx, val| PointerCast(bcx, val, Type::i8p(bcx.ccx()))
353         };
354         let info = |bcx, _val| unsized_info(bcx,
355                                             k,
356                                             expr.id,
357                                             datum_ty,
358                                             |t| ty::mk_rptr(tcx,
359                                                             ty::ReStatic,
360                                                             ty::mt{
361                                                                 ty: t,
362                                                                 mutbl: ast::MutImmutable
363                                                             }));
364         into_fat_ptr(bcx, expr, datum, dest_ty, base, info)
365     }
366
367     fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
368                                expr: &ast::Expr,
369                                datum: Datum<'tcx, Expr>)
370                                -> DatumBlock<'blk, 'tcx, Expr> {
371         let tcx = bcx.tcx();
372         let dest_ty = ty::close_type(tcx, datum.ty);
373         let base = |bcx, val| Load(bcx, get_dataptr(bcx, val));
374         let len = |bcx, val| Load(bcx, get_len(bcx, val));
375         into_fat_ptr(bcx, expr, datum, dest_ty, base, len)
376     }
377
378     fn into_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
379                                 expr: &ast::Expr,
380                                 datum: Datum<'tcx, Expr>,
381                                 dest_ty: Ty<'tcx>,
382                                 base: |Block<'blk, 'tcx>, ValueRef| -> ValueRef,
383                                 info: |Block<'blk, 'tcx>, ValueRef| -> ValueRef)
384                                 -> DatumBlock<'blk, 'tcx, Expr> {
385         let mut bcx = bcx;
386
387         // Arrange cleanup
388         let lval = unpack_datum!(bcx,
389                                  datum.to_lvalue_datum(bcx, "into_fat_ptr", expr.id));
390         let base = base(bcx, lval.val);
391         let info = info(bcx, lval.val);
392
393         let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
394         Store(bcx, base, get_dataptr(bcx, scratch.val));
395         Store(bcx, info, get_len(bcx, scratch.val));
396
397         DatumBlock::new(bcx, scratch.to_expr_datum())
398     }
399
400     fn unsize_unique_vec<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
401                                      expr: &ast::Expr,
402                                      datum: Datum<'tcx, Expr>,
403                                      len: uint)
404                                      -> DatumBlock<'blk, 'tcx, Expr> {
405         let mut bcx = bcx;
406         let tcx = bcx.tcx();
407
408         let datum_ty = datum.ty;
409         // Arrange cleanup
410         let lval = unpack_datum!(bcx,
411                                  datum.to_lvalue_datum(bcx, "unsize_unique_vec", expr.id));
412
413         let ll_len = C_uint(bcx.ccx(), len);
414         let unit_ty = ty::sequence_element_type(tcx, ty::type_content(datum_ty));
415         let vec_ty = ty::mk_uniq(tcx, ty::mk_vec(tcx, unit_ty, None));
416         let scratch = rvalue_scratch_datum(bcx, vec_ty, "__unsize_unique");
417
418         let base = get_dataptr(bcx, scratch.val);
419         let base = PointerCast(bcx,
420                                base,
421                                type_of::type_of(bcx.ccx(), datum_ty).ptr_to());
422         bcx = lval.store_to(bcx, base);
423
424         Store(bcx, ll_len, get_len(bcx, scratch.val));
425         DatumBlock::new(bcx, scratch.to_expr_datum())
426     }
427
428     fn unsize_unique_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
429                                       expr: &ast::Expr,
430                                       datum: Datum<'tcx, Expr>,
431                                       k: &ty::UnsizeKind<'tcx>)
432                                       -> DatumBlock<'blk, 'tcx, Expr> {
433         let mut bcx = bcx;
434         let tcx = bcx.tcx();
435
436         let datum_ty = datum.ty;
437         let unboxed_ty = match datum_ty.sty {
438             ty::ty_uniq(t) => t,
439             _ => bcx.sess().bug(format!("Expected ty_uniq, found {}",
440                                         bcx.ty_to_string(datum_ty)).as_slice())
441         };
442         let result_ty = ty::mk_uniq(tcx, ty::unsize_ty(tcx, unboxed_ty, k, expr.span));
443
444         let lval = unpack_datum!(bcx,
445                                  datum.to_lvalue_datum(bcx, "unsize_unique_expr", expr.id));
446
447         let scratch = rvalue_scratch_datum(bcx, result_ty, "__uniq_fat_ptr");
448         let llbox_ty = type_of::type_of(bcx.ccx(), datum_ty);
449         let base = PointerCast(bcx, get_dataptr(bcx, scratch.val), llbox_ty.ptr_to());
450         bcx = lval.store_to(bcx, base);
451
452         let info = unsized_info(bcx, k, expr.id, unboxed_ty, |t| ty::mk_uniq(tcx, t));
453         Store(bcx, info, get_len(bcx, scratch.val));
454
455         let scratch = unpack_datum!(bcx,
456                                     scratch.to_expr_datum().to_lvalue_datum(bcx,
457                                                                             "fresh_uniq_fat_ptr",
458                                                                             expr.id));
459
460         DatumBlock::new(bcx, scratch.to_expr_datum())
461     }
462
463     fn add_env<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
464                            expr: &ast::Expr,
465                            datum: Datum<'tcx, Expr>)
466                            -> DatumBlock<'blk, 'tcx, Expr> {
467         // This is not the most efficient thing possible; since closures
468         // are two words it'd be better if this were compiled in
469         // 'dest' mode, but I can't find a nice way to structure the
470         // code and keep it DRY that accommodates that use case at the
471         // moment.
472
473         let closure_ty = expr_ty_adjusted(bcx, expr);
474         let fn_ptr = datum.to_llscalarish(bcx);
475         let def = ty::resolve_expr(bcx.tcx(), expr);
476         closure::make_closure_from_bare_fn(bcx, closure_ty, def, fn_ptr)
477     }
478 }
479
480 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
481 /// that the expr represents.
482 ///
483 /// If this expression is an rvalue, this implies introducing a temporary.  In other words,
484 /// something like `x().f` is translated into roughly the equivalent of
485 ///
486 ///   { tmp = x(); tmp.f }
487 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
488                                    expr: &ast::Expr,
489                                    name: &str)
490                                    -> DatumBlock<'blk, 'tcx, Lvalue> {
491     let mut bcx = bcx;
492     let datum = unpack_datum!(bcx, trans(bcx, expr));
493     return datum.to_lvalue_datum(bcx, name, expr.id);
494 }
495
496 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
497 /// directly.
498 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
499                                 expr: &ast::Expr)
500                                 -> DatumBlock<'blk, 'tcx, Expr> {
501     let mut bcx = bcx;
502
503     debug!("trans_unadjusted(expr={})", bcx.expr_to_string(expr));
504     let _indenter = indenter();
505
506     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
507
508     return match ty::expr_kind(bcx.tcx(), expr) {
509         ty::LvalueExpr | ty::RvalueDatumExpr => {
510             let datum = unpack_datum!(bcx, {
511                 trans_datum_unadjusted(bcx, expr)
512             });
513
514             DatumBlock {bcx: bcx, datum: datum}
515         }
516
517         ty::RvalueStmtExpr => {
518             bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
519             nil(bcx, expr_ty(bcx, expr))
520         }
521
522         ty::RvalueDpsExpr => {
523             let ty = expr_ty(bcx, expr);
524             if type_is_zero_size(bcx.ccx(), ty) {
525                 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
526                 nil(bcx, ty)
527             } else {
528                 let scratch = rvalue_scratch_datum(bcx, ty, "");
529                 bcx = trans_rvalue_dps_unadjusted(
530                     bcx, expr, SaveIn(scratch.val));
531
532                 // Note: this is not obviously a good idea.  It causes
533                 // immediate values to be loaded immediately after a
534                 // return from a call or other similar expression,
535                 // which in turn leads to alloca's having shorter
536                 // lifetimes and hence larger stack frames.  However,
537                 // in turn it can lead to more register pressure.
538                 // Still, in practice it seems to increase
539                 // performance, since we have fewer problems with
540                 // morestack churn.
541                 let scratch = unpack_datum!(
542                     bcx, scratch.to_appropriate_datum(bcx));
543
544                 DatumBlock::new(bcx, scratch.to_expr_datum())
545             }
546         }
547     };
548
549     fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
550                        -> DatumBlock<'blk, 'tcx, Expr> {
551         let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
552         let datum = immediate_rvalue(llval, ty);
553         DatumBlock::new(bcx, datum.to_expr_datum())
554     }
555 }
556
557 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
558                                       expr: &ast::Expr)
559                                       -> DatumBlock<'blk, 'tcx, Expr> {
560     let mut bcx = bcx;
561     let fcx = bcx.fcx;
562     let _icx = push_ctxt("trans_datum_unadjusted");
563
564     match expr.node {
565         ast::ExprParen(ref e) => {
566             trans(bcx, &**e)
567         }
568         ast::ExprPath(_) => {
569             trans_def(bcx, expr, bcx.def(expr.id))
570         }
571         ast::ExprField(ref base, ident) => {
572             trans_rec_field(bcx, &**base, ident.node)
573         }
574         ast::ExprTupField(ref base, idx) => {
575             trans_rec_tup_field(bcx, &**base, idx.node)
576         }
577         ast::ExprIndex(ref base, ref idx) => {
578             trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
579         }
580         ast::ExprSlice(ref base, ref start, ref end, _) => {
581             let _icx = push_ctxt("trans_slice");
582             let ccx = bcx.ccx();
583
584             let method_call = MethodCall::expr(expr.id);
585             let method_ty = ccx.tcx()
586                                .method_map
587                                .borrow()
588                                .get(&method_call)
589                                .map(|method| method.ty);
590             let base_datum = unpack_datum!(bcx, trans(bcx, &**base));
591
592             let mut args = vec![];
593             start.as_ref().map(|e| args.push((unpack_datum!(bcx, trans(bcx, &**e)), e.id)));
594             end.as_ref().map(|e| args.push((unpack_datum!(bcx, trans(bcx, &**e)), e.id)));
595
596             let result_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty.unwrap())).unwrap();
597             let scratch = rvalue_scratch_datum(bcx, result_ty, "trans_slice");
598
599             unpack_result!(bcx,
600                            trans_overloaded_op(bcx,
601                                                expr,
602                                                method_call,
603                                                base_datum,
604                                                args,
605                                                Some(SaveIn(scratch.val))));
606             DatumBlock::new(bcx, scratch.to_expr_datum())
607         }
608         ast::ExprBox(_, ref contents) => {
609             // Special case for `Box<T>`
610             let box_ty = expr_ty(bcx, expr);
611             let contents_ty = expr_ty(bcx, &**contents);
612             match box_ty.sty {
613                 ty::ty_uniq(..) => {
614                     trans_uniq_expr(bcx, box_ty, &**contents, contents_ty)
615                 }
616                 _ => bcx.sess().span_bug(expr.span,
617                                          "expected unique box")
618             }
619
620         }
621         ast::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
622         ast::ExprBinary(op, ref lhs, ref rhs) => {
623             trans_binary(bcx, expr, op, &**lhs, &**rhs)
624         }
625         ast::ExprUnary(op, ref x) => {
626             trans_unary(bcx, expr, op, &**x)
627         }
628         ast::ExprAddrOf(_, ref x) => {
629             match x.node {
630                 ast::ExprRepeat(..) | ast::ExprVec(..) => {
631                     // Special case for slices.
632                     let cleanup_debug_loc =
633                         debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
634                                                                       x.id,
635                                                                       x.span,
636                                                                       false);
637                     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
638                     let datum = unpack_datum!(
639                         bcx, tvec::trans_slice_vec(bcx, expr, &**x));
640                     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
641                     DatumBlock::new(bcx, datum)
642                 }
643                 _ => {
644                     trans_addr_of(bcx, expr, &**x)
645                 }
646             }
647         }
648         ast::ExprCast(ref val, _) => {
649             // Datum output mode means this is a scalar cast:
650             trans_imm_cast(bcx, &**val, expr.id)
651         }
652         _ => {
653             bcx.tcx().sess.span_bug(
654                 expr.span,
655                 format!("trans_rvalue_datum_unadjusted reached \
656                          fall-through case: {}",
657                         expr.node).as_slice());
658         }
659     }
660 }
661
662 fn trans_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
663                            base: &ast::Expr,
664                            get_idx: |&'blk ty::ctxt<'tcx>, &[ty::field<'tcx>]| -> uint)
665                            -> DatumBlock<'blk, 'tcx, Expr> {
666     let mut bcx = bcx;
667     let _icx = push_ctxt("trans_rec_field");
668
669     let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
670     let bare_ty = ty::unopen_type(base_datum.ty);
671     let repr = adt::represent_type(bcx.ccx(), bare_ty);
672     with_field_tys(bcx.tcx(), bare_ty, None, |discr, field_tys| {
673         let ix = get_idx(bcx.tcx(), field_tys);
674         let d = base_datum.get_element(
675             bcx,
676             field_tys[ix].mt.ty,
677             |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, ix));
678
679         if ty::type_is_sized(bcx.tcx(), d.ty) {
680             DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
681         } else {
682             let scratch = rvalue_scratch_datum(bcx, ty::mk_open(bcx.tcx(), d.ty), "");
683             Store(bcx, d.val, get_dataptr(bcx, scratch.val));
684             let info = Load(bcx, get_len(bcx, base_datum.val));
685             Store(bcx, info, get_len(bcx, scratch.val));
686
687             DatumBlock::new(bcx, scratch.to_expr_datum())
688
689         }
690     })
691
692 }
693
694 /// Translates `base.field`.
695 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
696                                base: &ast::Expr,
697                                field: ast::Ident)
698                                -> DatumBlock<'blk, 'tcx, Expr> {
699     trans_field(bcx, base, |tcx, field_tys| ty::field_idx_strict(tcx, field.name, field_tys))
700 }
701
702 /// Translates `base.<idx>`.
703 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
704                                    base: &ast::Expr,
705                                    idx: uint)
706                                    -> DatumBlock<'blk, 'tcx, Expr> {
707     trans_field(bcx, base, |_, _| idx)
708 }
709
710 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
711                            index_expr: &ast::Expr,
712                            base: &ast::Expr,
713                            idx: &ast::Expr,
714                            method_call: MethodCall)
715                            -> DatumBlock<'blk, 'tcx, Expr> {
716     //! Translates `base[idx]`.
717
718     let _icx = push_ctxt("trans_index");
719     let ccx = bcx.ccx();
720     let mut bcx = bcx;
721
722     // Check for overloaded index.
723     let method_ty = ccx.tcx()
724                        .method_map
725                        .borrow()
726                        .get(&method_call)
727                        .map(|method| method.ty);
728     let elt_datum = match method_ty {
729         Some(method_ty) => {
730             let base_datum = unpack_datum!(bcx, trans(bcx, base));
731
732             // Translate index expression.
733             let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
734
735             let ref_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty)).unwrap();
736             let elt_ty = match ty::deref(ref_ty, true) {
737                 None => {
738                     bcx.tcx().sess.span_bug(index_expr.span,
739                                             "index method didn't return a \
740                                              dereferenceable type?!")
741                 }
742                 Some(elt_tm) => elt_tm.ty,
743             };
744
745             // Overloaded. Evaluate `trans_overloaded_op`, which will
746             // invoke the user's index() method, which basically yields
747             // a `&T` pointer.  We can then proceed down the normal
748             // path (below) to dereference that `&T`.
749             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
750             unpack_result!(bcx,
751                            trans_overloaded_op(bcx,
752                                                index_expr,
753                                                method_call,
754                                                base_datum,
755                                                vec![(ix_datum, idx.id)],
756                                                Some(SaveIn(scratch.val))));
757             let datum = scratch.to_expr_datum();
758             if ty::type_is_sized(bcx.tcx(), elt_ty) {
759                 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr)
760             } else {
761                 Datum::new(datum.val, ty::mk_open(bcx.tcx(), elt_ty), LvalueExpr)
762             }
763         }
764         None => {
765             let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
766                                                                 base,
767                                                                 "index"));
768
769             // Translate index expression and cast to a suitable LLVM integer.
770             // Rust is less strict than LLVM in this regard.
771             let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
772             let ix_val = ix_datum.to_llscalarish(bcx);
773             let ix_size = machine::llbitsize_of_real(bcx.ccx(),
774                                                      val_ty(ix_val));
775             let int_size = machine::llbitsize_of_real(bcx.ccx(),
776                                                       ccx.int_type());
777             let ix_val = {
778                 if ix_size < int_size {
779                     if ty::type_is_signed(expr_ty(bcx, idx)) {
780                         SExt(bcx, ix_val, ccx.int_type())
781                     } else { ZExt(bcx, ix_val, ccx.int_type()) }
782                 } else if ix_size > int_size {
783                     Trunc(bcx, ix_val, ccx.int_type())
784                 } else {
785                     ix_val
786                 }
787             };
788
789             let vt =
790                 tvec::vec_types(bcx,
791                                 ty::sequence_element_type(bcx.tcx(),
792                                                           base_datum.ty));
793             base::maybe_name_value(bcx.ccx(), vt.llunit_size, "unit_sz");
794
795             let (base, len) = base_datum.get_vec_base_and_len(bcx);
796
797             debug!("trans_index: base {}", bcx.val_to_string(base));
798             debug!("trans_index: len {}", bcx.val_to_string(len));
799
800             let bounds_check = ICmp(bcx, llvm::IntUGE, ix_val, len);
801             let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
802             let expected = Call(bcx,
803                                 expect,
804                                 &[bounds_check, C_bool(ccx, false)],
805                                 None);
806             bcx = with_cond(bcx, expected, |bcx| {
807                 controlflow::trans_fail_bounds_check(bcx,
808                                                      index_expr.span,
809                                                      ix_val,
810                                                      len)
811             });
812             let elt = InBoundsGEP(bcx, base, &[ix_val]);
813             let elt = PointerCast(bcx, elt, vt.llunit_ty.ptr_to());
814             Datum::new(elt, vt.unit_ty, LvalueExpr)
815         }
816     };
817
818     DatumBlock::new(bcx, elt_datum)
819 }
820
821 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
822                          ref_expr: &ast::Expr,
823                          def: def::Def)
824                          -> DatumBlock<'blk, 'tcx, Expr> {
825     //! Translates a reference to a path.
826
827     let _icx = push_ctxt("trans_def_lvalue");
828     match def {
829         def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) |
830         def::DefStruct(_) | def::DefVariant(..) => {
831             trans_def_fn_unadjusted(bcx, ref_expr, def)
832         }
833         def::DefStatic(did, _) => {
834             // There are two things that may happen here:
835             //  1) If the static item is defined in this crate, it will be
836             //     translated using `get_item_val`, and we return a pointer to
837             //     the result.
838             //  2) If the static item is defined in another crate then we add
839             //     (or reuse) a declaration of an external global, and return a
840             //     pointer to that.
841             let const_ty = expr_ty(bcx, ref_expr);
842
843             fn get_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, did: ast::DefId,
844                                    const_ty: Ty<'tcx>) -> ValueRef {
845                 // For external constants, we don't inline.
846                 if did.krate == ast::LOCAL_CRATE {
847                     // Case 1.
848
849                     // The LLVM global has the type of its initializer,
850                     // which may not be equal to the enum's type for
851                     // non-C-like enums.
852                     let val = base::get_item_val(bcx.ccx(), did.node);
853                     let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
854                     PointerCast(bcx, val, pty)
855                 } else {
856                     // Case 2.
857                     base::get_extern_const(bcx.ccx(), did, const_ty)
858                 }
859             }
860             let val = get_val(bcx, did, const_ty);
861             DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr))
862         }
863         def::DefConst(did) => {
864             // First, inline any external constants into the local crate so we
865             // can be sure to get the LLVM value corresponding to it.
866             let did = inline::maybe_instantiate_inline(bcx.ccx(), did);
867             if did.krate != ast::LOCAL_CRATE {
868                 bcx.tcx().sess.span_bug(ref_expr.span,
869                                         "cross crate constant could not \
870                                          be inlined");
871             }
872             let val = base::get_item_val(bcx.ccx(), did.node);
873
874             // Next, we need to crate a ByRef rvalue datum to return. We can't
875             // use the normal .to_ref_datum() function because the type of
876             // `val` is not actually the same as `const_ty`.
877             //
878             // To get around this, we make a custom alloca slot with the
879             // appropriate type (const_ty), and then we cast it to a pointer of
880             // typeof(val), store the value, and then hand this slot over to
881             // the datum infrastructure.
882             let const_ty = expr_ty(bcx, ref_expr);
883             let llty = type_of::type_of(bcx.ccx(), const_ty);
884             let slot = alloca(bcx, llty, "const");
885             let pty = Type::from_ref(unsafe { llvm::LLVMTypeOf(val) }).ptr_to();
886             Store(bcx, val, PointerCast(bcx, slot, pty));
887
888             let datum = Datum::new(slot, const_ty, Rvalue::new(ByRef));
889             DatumBlock::new(bcx, datum.to_expr_datum())
890         }
891         _ => {
892             DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
893         }
894     }
895 }
896
897 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
898                                             expr: &ast::Expr)
899                                             -> Block<'blk, 'tcx> {
900     let mut bcx = bcx;
901     let _icx = push_ctxt("trans_rvalue_stmt");
902
903     if bcx.unreachable.get() {
904         return bcx;
905     }
906
907     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
908
909     match expr.node {
910         ast::ExprParen(ref e) => {
911             trans_into(bcx, &**e, Ignore)
912         }
913         ast::ExprBreak(label_opt) => {
914             controlflow::trans_break(bcx, expr.id, label_opt)
915         }
916         ast::ExprAgain(label_opt) => {
917             controlflow::trans_cont(bcx, expr.id, label_opt)
918         }
919         ast::ExprRet(ref ex) => {
920             controlflow::trans_ret(bcx, ex.as_ref().map(|e| &**e))
921         }
922         ast::ExprWhile(ref cond, ref body, _) => {
923             controlflow::trans_while(bcx, expr.id, &**cond, &**body)
924         }
925         ast::ExprForLoop(ref pat, ref head, ref body, _) => {
926             controlflow::trans_for(bcx,
927                                    expr_info(expr),
928                                    &**pat,
929                                    &**head,
930                                    &**body)
931         }
932         ast::ExprLoop(ref body, _) => {
933             controlflow::trans_loop(bcx, expr.id, &**body)
934         }
935         ast::ExprAssign(ref dst, ref src) => {
936             let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
937             let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
938
939             if ty::type_needs_drop(bcx.tcx(), dst_datum.ty) {
940                 // If there are destructors involved, make sure we
941                 // are copying from an rvalue, since that cannot possible
942                 // alias an lvalue. We are concerned about code like:
943                 //
944                 //   a = a
945                 //
946                 // but also
947                 //
948                 //   a = a.b
949                 //
950                 // where e.g. a : Option<Foo> and a.b :
951                 // Option<Foo>. In that case, freeing `a` before the
952                 // assignment may also free `a.b`!
953                 //
954                 // We could avoid this intermediary with some analysis
955                 // to determine whether `dst` may possibly own `src`.
956                 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
957                 let src_datum = unpack_datum!(
958                     bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
959                 bcx = glue::drop_ty(bcx,
960                                     dst_datum.val,
961                                     dst_datum.ty,
962                                     Some(NodeInfo { id: expr.id, span: expr.span }));
963                 src_datum.store_to(bcx, dst_datum.val)
964             } else {
965                 src_datum.store_to(bcx, dst_datum.val)
966             }
967         }
968         ast::ExprAssignOp(op, ref dst, ref src) => {
969             trans_assign_op(bcx, expr, op, &**dst, &**src)
970         }
971         ast::ExprInlineAsm(ref a) => {
972             asm::trans_inline_asm(bcx, a)
973         }
974         _ => {
975             bcx.tcx().sess.span_bug(
976                 expr.span,
977                 format!("trans_rvalue_stmt_unadjusted reached \
978                          fall-through case: {}",
979                         expr.node).as_slice());
980         }
981     }
982 }
983
984 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
985                                            expr: &ast::Expr,
986                                            dest: Dest)
987                                            -> Block<'blk, 'tcx> {
988     let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
989     let mut bcx = bcx;
990     let tcx = bcx.tcx();
991
992     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
993
994     match expr.node {
995         ast::ExprParen(ref e) => {
996             trans_into(bcx, &**e, dest)
997         }
998         ast::ExprPath(_) => {
999             trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1000         }
1001         ast::ExprIf(ref cond, ref thn, ref els) => {
1002             controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1003         }
1004         ast::ExprMatch(ref discr, ref arms, _) => {
1005             _match::trans_match(bcx, expr, &**discr, arms.as_slice(), dest)
1006         }
1007         ast::ExprBlock(ref blk) => {
1008             controlflow::trans_block(bcx, &**blk, dest)
1009         }
1010         ast::ExprStruct(_, ref fields, ref base) => {
1011             trans_struct(bcx,
1012                          fields.as_slice(),
1013                          base.as_ref().map(|e| &**e),
1014                          expr.span,
1015                          expr.id,
1016                          dest)
1017         }
1018         ast::ExprTup(ref args) => {
1019             let numbered_fields: Vec<(uint, &ast::Expr)> =
1020                 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1021             trans_adt(bcx,
1022                       expr_ty(bcx, expr),
1023                       0,
1024                       numbered_fields.as_slice(),
1025                       None,
1026                       dest,
1027                       Some(NodeInfo { id: expr.id, span: expr.span }))
1028         }
1029         ast::ExprLit(ref lit) => {
1030             match lit.node {
1031                 ast::LitStr(ref s, _) => {
1032                     tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1033                 }
1034                 _ => {
1035                     bcx.tcx()
1036                        .sess
1037                        .span_bug(expr.span,
1038                                  "trans_rvalue_dps_unadjusted shouldn't be \
1039                                   translating this type of literal")
1040                 }
1041             }
1042         }
1043         ast::ExprVec(..) | ast::ExprRepeat(..) => {
1044             tvec::trans_fixed_vstore(bcx, expr, dest)
1045         }
1046         ast::ExprClosure(_, _, ref decl, ref body) |
1047         ast::ExprProc(ref decl, ref body) => {
1048             // Check the side-table to see whether this is an unboxed
1049             // closure or an older, legacy style closure. Store this
1050             // into a variable to ensure the the RefCell-lock is
1051             // released before we recurse.
1052             let is_unboxed_closure =
1053                 bcx.tcx().unboxed_closures.borrow().contains_key(&ast_util::local_def(expr.id));
1054             if is_unboxed_closure {
1055                 closure::trans_unboxed_closure(bcx, &**decl, &**body, expr.id, dest)
1056             } else {
1057                 let expr_ty = expr_ty(bcx, expr);
1058                 let store = ty::ty_closure_store(expr_ty);
1059                 debug!("translating block function {} with type {}",
1060                        expr_to_string(expr), expr_ty.repr(tcx));
1061                 closure::trans_expr_fn(bcx, store, &**decl, &**body, expr.id, dest)
1062             }
1063         }
1064         ast::ExprCall(ref f, ref args) => {
1065             if bcx.tcx().is_method_call(expr.id) {
1066                 trans_overloaded_call(bcx,
1067                                       expr,
1068                                       &**f,
1069                                       args.as_slice(),
1070                                       Some(dest))
1071             } else {
1072                 callee::trans_call(bcx,
1073                                    expr,
1074                                    &**f,
1075                                    callee::ArgExprs(args.as_slice()),
1076                                    dest)
1077             }
1078         }
1079         ast::ExprMethodCall(_, _, ref args) => {
1080             callee::trans_method_call(bcx,
1081                                       expr,
1082                                       &*args[0],
1083                                       callee::ArgExprs(args.as_slice()),
1084                                       dest)
1085         }
1086         ast::ExprBinary(_, ref lhs, ref rhs) => {
1087             // if not overloaded, would be RvalueDatumExpr
1088             let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1089             let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1090             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1091                                 vec![(rhs_datum, rhs.id)], Some(dest)).bcx
1092         }
1093         ast::ExprUnary(_, ref subexpr) => {
1094             // if not overloaded, would be RvalueDatumExpr
1095             let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1096             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1097                                 arg, Vec::new(), Some(dest)).bcx
1098         }
1099         ast::ExprIndex(ref base, ref idx) => {
1100             // if not overloaded, would be RvalueDatumExpr
1101             let base = unpack_datum!(bcx, trans(bcx, &**base));
1102             let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1103             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1104                                 vec![(idx_datum, idx.id)], Some(dest)).bcx
1105         }
1106         ast::ExprCast(ref val, _) => {
1107             // DPS output mode means this is a trait cast:
1108             if ty::type_is_trait(node_id_type(bcx, expr.id)) {
1109                 let trait_ref =
1110                     bcx.tcx().object_cast_map.borrow()
1111                                              .get(&expr.id)
1112                                              .map(|t| (*t).clone())
1113                                              .unwrap();
1114                 let trait_ref = trait_ref.subst(bcx.tcx(), bcx.fcx.param_substs);
1115                 let datum = unpack_datum!(bcx, trans(bcx, &**val));
1116                 meth::trans_trait_cast(bcx, datum, expr.id,
1117                                        trait_ref, dest)
1118             } else {
1119                 bcx.tcx().sess.span_bug(expr.span,
1120                                         "expr_cast of non-trait");
1121             }
1122         }
1123         ast::ExprAssignOp(op, ref dst, ref src) => {
1124             trans_assign_op(bcx, expr, op, &**dst, &**src)
1125         }
1126         _ => {
1127             bcx.tcx().sess.span_bug(
1128                 expr.span,
1129                 format!("trans_rvalue_dps_unadjusted reached fall-through \
1130                          case: {}",
1131                         expr.node).as_slice());
1132         }
1133     }
1134 }
1135
1136 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1137                                         ref_expr: &ast::Expr,
1138                                         def: def::Def,
1139                                         dest: Dest)
1140                                         -> Block<'blk, 'tcx> {
1141     let _icx = push_ctxt("trans_def_dps_unadjusted");
1142
1143     let lldest = match dest {
1144         SaveIn(lldest) => lldest,
1145         Ignore => { return bcx; }
1146     };
1147
1148     match def {
1149         def::DefVariant(tid, vid, _) => {
1150             let variant_info = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
1151             if variant_info.args.len() > 0u {
1152                 // N-ary variant.
1153                 let llfn = callee::trans_fn_ref(bcx, vid, ExprId(ref_expr.id));
1154                 Store(bcx, llfn, lldest);
1155                 return bcx;
1156             } else {
1157                 // Nullary variant.
1158                 let ty = expr_ty(bcx, ref_expr);
1159                 let repr = adt::represent_type(bcx.ccx(), ty);
1160                 adt::trans_set_discr(bcx, &*repr, lldest,
1161                                      variant_info.disr_val);
1162                 return bcx;
1163             }
1164         }
1165         def::DefStruct(_) => {
1166             let ty = expr_ty(bcx, ref_expr);
1167             match ty.sty {
1168                 ty::ty_struct(did, _) if ty::has_dtor(bcx.tcx(), did) => {
1169                     let repr = adt::represent_type(bcx.ccx(), ty);
1170                     adt::trans_set_discr(bcx, &*repr, lldest, 0);
1171                 }
1172                 _ => {}
1173             }
1174             bcx
1175         }
1176         _ => {
1177             bcx.tcx().sess.span_bug(ref_expr.span, format!(
1178                 "Non-DPS def {} referened by {}",
1179                 def, bcx.node_id_to_string(ref_expr.id)).as_slice());
1180         }
1181     }
1182 }
1183
1184 fn trans_def_fn_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1185                                        ref_expr: &ast::Expr,
1186                                        def: def::Def)
1187                                        -> DatumBlock<'blk, 'tcx, Expr> {
1188     let _icx = push_ctxt("trans_def_datum_unadjusted");
1189
1190     let llfn = match def {
1191         def::DefFn(did, _) |
1192         def::DefStruct(did) | def::DefVariant(_, did, _) |
1193         def::DefStaticMethod(did, def::FromImpl(_)) |
1194         def::DefMethod(did, _, def::FromImpl(_)) => {
1195             callee::trans_fn_ref(bcx, did, ExprId(ref_expr.id))
1196         }
1197         def::DefStaticMethod(impl_did, def::FromTrait(trait_did)) |
1198         def::DefMethod(impl_did, _, def::FromTrait(trait_did)) => {
1199             meth::trans_static_method_callee(bcx, impl_did,
1200                                              trait_did, ref_expr.id)
1201         }
1202         _ => {
1203             bcx.tcx().sess.span_bug(ref_expr.span, format!(
1204                     "trans_def_fn_unadjusted invoked on: {} for {}",
1205                     def,
1206                     ref_expr.repr(bcx.tcx())).as_slice());
1207         }
1208     };
1209
1210     let fn_ty = expr_ty(bcx, ref_expr);
1211     DatumBlock::new(bcx, Datum::new(llfn, fn_ty, RvalueExpr(Rvalue::new(ByValue))))
1212 }
1213
1214 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1215 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1216                                    def: def::Def)
1217                                    -> Datum<'tcx, Lvalue> {
1218     let _icx = push_ctxt("trans_local_var");
1219
1220     match def {
1221         def::DefUpvar(nid, _, _) => {
1222             // Can't move upvars, so this is never a ZeroMemLastUse.
1223             let local_ty = node_id_type(bcx, nid);
1224             match bcx.fcx.llupvars.borrow().get(&nid) {
1225                 Some(&val) => Datum::new(val, local_ty, Lvalue),
1226                 None => {
1227                     bcx.sess().bug(format!(
1228                         "trans_local_var: no llval for upvar {} found",
1229                         nid).as_slice());
1230                 }
1231             }
1232         }
1233         def::DefLocal(nid) => {
1234             let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1235                 Some(&v) => v,
1236                 None => {
1237                     bcx.sess().bug(format!(
1238                         "trans_local_var: no datum for local/arg {} found",
1239                         nid).as_slice());
1240                 }
1241             };
1242             debug!("take_local(nid={}, v={}, ty={})",
1243                    nid, bcx.val_to_string(datum.val), bcx.ty_to_string(datum.ty));
1244             datum
1245         }
1246         _ => {
1247             bcx.sess().unimpl(format!(
1248                 "unsupported def type in trans_local_var: {}",
1249                 def).as_slice());
1250         }
1251     }
1252 }
1253
1254 /// Helper for enumerating the field types of structs, enums, or records. The optional node ID here
1255 /// is the node ID of the path identifying the enum variant in use. If none, this cannot possibly
1256 /// an enum variant (so, if it is and `node_id_opt` is none, this function panics).
1257 pub fn with_field_tys<'tcx, R>(tcx: &ty::ctxt<'tcx>,
1258                                ty: Ty<'tcx>,
1259                                node_id_opt: Option<ast::NodeId>,
1260                                op: |ty::Disr, (&[ty::field<'tcx>])| -> R)
1261                                -> R {
1262     match ty.sty {
1263         ty::ty_struct(did, ref substs) => {
1264             op(0, struct_fields(tcx, did, substs).as_slice())
1265         }
1266
1267         ty::ty_tup(ref v) => {
1268             op(0, tup_fields(v.as_slice()).as_slice())
1269         }
1270
1271         ty::ty_enum(_, ref substs) => {
1272             // We want the *variant* ID here, not the enum ID.
1273             match node_id_opt {
1274                 None => {
1275                     tcx.sess.bug(format!(
1276                         "cannot get field types from the enum type {} \
1277                          without a node ID",
1278                         ty.repr(tcx)).as_slice());
1279                 }
1280                 Some(node_id) => {
1281                     let def = tcx.def_map.borrow()[node_id].clone();
1282                     match def {
1283                         def::DefVariant(enum_id, variant_id, _) => {
1284                             let variant_info = ty::enum_variant_with_id(
1285                                 tcx, enum_id, variant_id);
1286                             op(variant_info.disr_val,
1287                                struct_fields(tcx,
1288                                              variant_id,
1289                                              substs).as_slice())
1290                         }
1291                         _ => {
1292                             tcx.sess.bug("resolve didn't map this expr to a \
1293                                           variant ID")
1294                         }
1295                     }
1296                 }
1297             }
1298         }
1299
1300         _ => {
1301             tcx.sess.bug(format!(
1302                 "cannot get field types from the type {}",
1303                 ty.repr(tcx)).as_slice());
1304         }
1305     }
1306 }
1307
1308 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1309                             fields: &[ast::Field],
1310                             base: Option<&ast::Expr>,
1311                             expr_span: codemap::Span,
1312                             expr_id: ast::NodeId,
1313                             dest: Dest) -> Block<'blk, 'tcx> {
1314     let _icx = push_ctxt("trans_rec");
1315
1316     let ty = node_id_type(bcx, expr_id);
1317     let tcx = bcx.tcx();
1318     with_field_tys(tcx, ty, Some(expr_id), |discr, field_tys| {
1319         let mut need_base = Vec::from_elem(field_tys.len(), true);
1320
1321         let numbered_fields = fields.iter().map(|field| {
1322             let opt_pos =
1323                 field_tys.iter().position(|field_ty|
1324                                           field_ty.name == field.ident.node.name);
1325             match opt_pos {
1326                 Some(i) => {
1327                     need_base[i] = false;
1328                     (i, &*field.expr)
1329                 }
1330                 None => {
1331                     tcx.sess.span_bug(field.span,
1332                                       "Couldn't find field in struct type")
1333                 }
1334             }
1335         }).collect::<Vec<_>>();
1336         let optbase = match base {
1337             Some(base_expr) => {
1338                 let mut leftovers = Vec::new();
1339                 for (i, b) in need_base.iter().enumerate() {
1340                     if *b {
1341                         leftovers.push((i, field_tys[i].mt.ty))
1342                     }
1343                 }
1344                 Some(StructBaseInfo {expr: base_expr,
1345                                      fields: leftovers })
1346             }
1347             None => {
1348                 if need_base.iter().any(|b| *b) {
1349                     tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1350                 }
1351                 None
1352             }
1353         };
1354
1355         trans_adt(bcx,
1356                   ty,
1357                   discr,
1358                   numbered_fields.as_slice(),
1359                   optbase,
1360                   dest,
1361                   Some(NodeInfo { id: expr_id, span: expr_span }))
1362     })
1363 }
1364
1365 /// Information that `trans_adt` needs in order to fill in the fields
1366 /// of a struct copied from a base struct (e.g., from an expression
1367 /// like `Foo { a: b, ..base }`.
1368 ///
1369 /// Note that `fields` may be empty; the base expression must always be
1370 /// evaluated for side-effects.
1371 pub struct StructBaseInfo<'a, 'tcx> {
1372     /// The base expression; will be evaluated after all explicit fields.
1373     expr: &'a ast::Expr,
1374     /// The indices of fields to copy paired with their types.
1375     fields: Vec<(uint, Ty<'tcx>)>
1376 }
1377
1378 /// Constructs an ADT instance:
1379 ///
1380 /// - `fields` should be a list of field indices paired with the
1381 /// expression to store into that field.  The initializers will be
1382 /// evaluated in the order specified by `fields`.
1383 ///
1384 /// - `optbase` contains information on the base struct (if any) from
1385 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1386 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1387                                  ty: Ty<'tcx>,
1388                                  discr: ty::Disr,
1389                                  fields: &[(uint, &ast::Expr)],
1390                                  optbase: Option<StructBaseInfo<'a, 'tcx>>,
1391                                  dest: Dest,
1392                                  source_location: Option<NodeInfo>)
1393                                  -> Block<'blk, 'tcx> {
1394     let _icx = push_ctxt("trans_adt");
1395     let fcx = bcx.fcx;
1396     let repr = adt::represent_type(bcx.ccx(), ty);
1397
1398     match source_location {
1399         Some(src_loc) => debuginfo::set_source_location(bcx.fcx,
1400                                                         src_loc.id,
1401                                                         src_loc.span),
1402         None => {}
1403     };
1404
1405     // If we don't care about the result, just make a
1406     // temporary stack slot
1407     let addr = match dest {
1408         SaveIn(pos) => pos,
1409         Ignore => alloc_ty(bcx, ty, "temp"),
1410     };
1411
1412     // This scope holds intermediates that must be cleaned should
1413     // panic occur before the ADT as a whole is ready.
1414     let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1415
1416     // First we trans the base, if we have one, to the dest
1417     for base in optbase.iter() {
1418         assert_eq!(discr, 0);
1419
1420         match ty::expr_kind(bcx.tcx(), &*base.expr) {
1421             ty::RvalueDpsExpr | ty::RvalueDatumExpr if !ty::type_needs_drop(bcx.tcx(), ty) => {
1422                 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1423             },
1424             ty::RvalueStmtExpr => bcx.tcx().sess.bug("unexpected expr kind for struct base expr"),
1425             _ => {
1426                 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1427                 for &(i, t) in base.fields.iter() {
1428                     let datum = base_datum.get_element(
1429                             bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1430                     assert!(ty::type_is_sized(bcx.tcx(), datum.ty));
1431                     let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1432                     bcx = datum.store_to(bcx, dest);
1433                 }
1434             }
1435         }
1436     }
1437
1438     match source_location {
1439         Some(src_loc) => debuginfo::set_source_location(bcx.fcx,
1440                                                         src_loc.id,
1441                                                         src_loc.span),
1442         None => {}
1443     };
1444
1445     if ty::type_is_simd(bcx.tcx(), ty) {
1446         // This is the constructor of a SIMD type, such types are
1447         // always primitive machine types and so do not have a
1448         // destructor or require any clean-up.
1449         let llty = type_of::type_of(bcx.ccx(), ty);
1450
1451         // keep a vector as a register, and running through the field
1452         // `insertelement`ing them directly into that register
1453         // (i.e. avoid GEPi and `store`s to an alloca) .
1454         let mut vec_val = C_undef(llty);
1455
1456         for &(i, ref e) in fields.iter() {
1457             let block_datum = trans(bcx, &**e);
1458             bcx = block_datum.bcx;
1459             let position = C_uint(bcx.ccx(), i);
1460             let value = block_datum.datum.to_llscalarish(bcx);
1461             vec_val = InsertElement(bcx, vec_val, value, position);
1462         }
1463         Store(bcx, vec_val, addr);
1464     } else {
1465         // Now, we just overwrite the fields we've explicitly specified
1466         for &(i, ref e) in fields.iter() {
1467             let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1468             let e_ty = expr_ty_adjusted(bcx, &**e);
1469             bcx = trans_into(bcx, &**e, SaveIn(dest));
1470             let scope = cleanup::CustomScope(custom_cleanup_scope);
1471             fcx.schedule_lifetime_end(scope, dest);
1472             fcx.schedule_drop_mem(scope, dest, e_ty);
1473         }
1474     }
1475
1476     adt::trans_set_discr(bcx, &*repr, addr, discr);
1477
1478     fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1479
1480     // If we don't care about the result drop the temporary we made
1481     match dest {
1482         SaveIn(_) => bcx,
1483         Ignore => {
1484             bcx = glue::drop_ty(bcx, addr, ty, source_location);
1485             base::call_lifetime_end(bcx, addr);
1486             bcx
1487         }
1488     }
1489 }
1490
1491
1492 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1493                                    expr: &ast::Expr,
1494                                    lit: &ast::Lit)
1495                                    -> DatumBlock<'blk, 'tcx, Expr> {
1496     // must not be a string constant, that is a RvalueDpsExpr
1497     let _icx = push_ctxt("trans_immediate_lit");
1498     let ty = expr_ty(bcx, expr);
1499     let v = consts::const_lit(bcx.ccx(), expr, lit);
1500     immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1501 }
1502
1503 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1504                            expr: &ast::Expr,
1505                            op: ast::UnOp,
1506                            sub_expr: &ast::Expr)
1507                            -> DatumBlock<'blk, 'tcx, Expr> {
1508     let ccx = bcx.ccx();
1509     let mut bcx = bcx;
1510     let _icx = push_ctxt("trans_unary_datum");
1511
1512     let method_call = MethodCall::expr(expr.id);
1513
1514     // The only overloaded operator that is translated to a datum
1515     // is an overloaded deref, since it is always yields a `&T`.
1516     // Otherwise, we should be in the RvalueDpsExpr path.
1517     assert!(
1518         op == ast::UnDeref ||
1519         !ccx.tcx().method_map.borrow().contains_key(&method_call));
1520
1521     let un_ty = expr_ty(bcx, expr);
1522
1523     match op {
1524         ast::UnNot => {
1525             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1526             let llresult = Not(bcx, datum.to_llscalarish(bcx));
1527             immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1528         }
1529         ast::UnNeg => {
1530             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1531             let val = datum.to_llscalarish(bcx);
1532             let llneg = {
1533                 if ty::type_is_fp(un_ty) {
1534                     FNeg(bcx, val)
1535                 } else {
1536                     Neg(bcx, val)
1537                 }
1538             };
1539             immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1540         }
1541         ast::UnUniq => {
1542             trans_uniq_expr(bcx, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1543         }
1544         ast::UnDeref => {
1545             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1546             deref_once(bcx, expr, datum, method_call)
1547         }
1548     }
1549 }
1550
1551 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1552                                box_ty: Ty<'tcx>,
1553                                contents: &ast::Expr,
1554                                contents_ty: Ty<'tcx>)
1555                                -> DatumBlock<'blk, 'tcx, Expr> {
1556     let _icx = push_ctxt("trans_uniq_expr");
1557     let fcx = bcx.fcx;
1558     assert!(ty::type_is_sized(bcx.tcx(), contents_ty));
1559     let llty = type_of::type_of(bcx.ccx(), contents_ty);
1560     let size = llsize_of(bcx.ccx(), llty);
1561     let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1562     let llty_ptr = llty.ptr_to();
1563     let Result { bcx, val } = malloc_raw_dyn(bcx, llty_ptr, box_ty, size, align);
1564     // Unique boxes do not allocate for zero-size types. The standard library
1565     // may assume that `free` is never called on the pointer returned for
1566     // `Box<ZeroSizeType>`.
1567     let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1568         trans_into(bcx, contents, SaveIn(val))
1569     } else {
1570         let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1571         fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1572                                 val, cleanup::HeapExchange, contents_ty);
1573         let bcx = trans_into(bcx, contents, SaveIn(val));
1574         fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1575         bcx
1576     };
1577     immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1578 }
1579
1580 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1581                              expr: &ast::Expr,
1582                              subexpr: &ast::Expr)
1583                              -> DatumBlock<'blk, 'tcx, Expr> {
1584     let _icx = push_ctxt("trans_addr_of");
1585     let mut bcx = bcx;
1586     let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1587     match sub_datum.ty.sty {
1588         ty::ty_open(_) => {
1589             // Opened DST value, close to a fat pointer
1590             debug!("Closing fat pointer {}", bcx.ty_to_string(sub_datum.ty));
1591
1592             let scratch = rvalue_scratch_datum(bcx,
1593                                                ty::close_type(bcx.tcx(), sub_datum.ty),
1594                                                "fat_addr_of");
1595             let base = Load(bcx, get_dataptr(bcx, sub_datum.val));
1596             Store(bcx, base, get_dataptr(bcx, scratch.val));
1597
1598             let len = Load(bcx, get_len(bcx, sub_datum.val));
1599             Store(bcx, len, get_len(bcx, scratch.val));
1600
1601             DatumBlock::new(bcx, scratch.to_expr_datum())
1602         }
1603         _ => {
1604             // Sized value, ref to a thin pointer
1605             let ty = expr_ty(bcx, expr);
1606             immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1607         }
1608     }
1609 }
1610
1611 // Important to get types for both lhs and rhs, because one might be _|_
1612 // and the other not.
1613 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1614                                  binop_expr: &ast::Expr,
1615                                  binop_ty: Ty<'tcx>,
1616                                  op: ast::BinOp,
1617                                  lhs_t: Ty<'tcx>,
1618                                  lhs: ValueRef,
1619                                  rhs_t: Ty<'tcx>,
1620                                  rhs: ValueRef)
1621                                  -> DatumBlock<'blk, 'tcx, Expr> {
1622     let _icx = push_ctxt("trans_eager_binop");
1623
1624     let tcx = bcx.tcx();
1625     let is_simd = ty::type_is_simd(tcx, lhs_t);
1626     let intype = {
1627         if is_simd { ty::simd_type(tcx, lhs_t) }
1628         else { lhs_t }
1629     };
1630     let is_float = ty::type_is_fp(intype);
1631     let is_signed = ty::type_is_signed(intype);
1632
1633     let rhs = base::cast_shift_expr_rhs(bcx, op, lhs, rhs);
1634
1635     let mut bcx = bcx;
1636     let val = match op {
1637       ast::BiAdd => {
1638         if is_float { FAdd(bcx, lhs, rhs) }
1639         else { Add(bcx, lhs, rhs) }
1640       }
1641       ast::BiSub => {
1642         if is_float { FSub(bcx, lhs, rhs) }
1643         else { Sub(bcx, lhs, rhs) }
1644       }
1645       ast::BiMul => {
1646         if is_float { FMul(bcx, lhs, rhs) }
1647         else { Mul(bcx, lhs, rhs) }
1648       }
1649       ast::BiDiv => {
1650         if is_float {
1651             FDiv(bcx, lhs, rhs)
1652         } else {
1653             // Only zero-check integers; fp /0 is NaN
1654             bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1655                                                   op, lhs, rhs, rhs_t);
1656             if is_signed {
1657                 SDiv(bcx, lhs, rhs)
1658             } else {
1659                 UDiv(bcx, lhs, rhs)
1660             }
1661         }
1662       }
1663       ast::BiRem => {
1664         if is_float {
1665             FRem(bcx, lhs, rhs)
1666         } else {
1667             // Only zero-check integers; fp %0 is NaN
1668             bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1669                                                   op, lhs, rhs, rhs_t);
1670             if is_signed {
1671                 SRem(bcx, lhs, rhs)
1672             } else {
1673                 URem(bcx, lhs, rhs)
1674             }
1675         }
1676       }
1677       ast::BiBitOr => Or(bcx, lhs, rhs),
1678       ast::BiBitAnd => And(bcx, lhs, rhs),
1679       ast::BiBitXor => Xor(bcx, lhs, rhs),
1680       ast::BiShl => Shl(bcx, lhs, rhs),
1681       ast::BiShr => {
1682         if is_signed {
1683             AShr(bcx, lhs, rhs)
1684         } else { LShr(bcx, lhs, rhs) }
1685       }
1686       ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1687         if ty::type_is_scalar(rhs_t) {
1688             unpack_result!(bcx, base::compare_scalar_types(bcx, lhs, rhs, rhs_t, op))
1689         } else if is_simd {
1690             base::compare_simd_types(bcx, lhs, rhs, intype, ty::simd_size(tcx, lhs_t), op)
1691         } else {
1692             bcx.tcx().sess.span_bug(binop_expr.span, "comparison operator unsupported for type")
1693         }
1694       }
1695       _ => {
1696         bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1697       }
1698     };
1699
1700     immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1701 }
1702
1703 // refinement types would obviate the need for this
1704 enum lazy_binop_ty {
1705     lazy_and,
1706     lazy_or,
1707 }
1708
1709 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1710                                 binop_expr: &ast::Expr,
1711                                 op: lazy_binop_ty,
1712                                 a: &ast::Expr,
1713                                 b: &ast::Expr)
1714                                 -> DatumBlock<'blk, 'tcx, Expr> {
1715     let _icx = push_ctxt("trans_lazy_binop");
1716     let binop_ty = expr_ty(bcx, binop_expr);
1717     let fcx = bcx.fcx;
1718
1719     let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1720     let lhs = lhs.to_llscalarish(past_lhs);
1721
1722     if past_lhs.unreachable.get() {
1723         return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1724     }
1725
1726     let join = fcx.new_id_block("join", binop_expr.id);
1727     let before_rhs = fcx.new_id_block("before_rhs", b.id);
1728
1729     match op {
1730       lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb),
1731       lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb)
1732     }
1733
1734     let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1735     let rhs = rhs.to_llscalarish(past_rhs);
1736
1737     if past_rhs.unreachable.get() {
1738         return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1739     }
1740
1741     Br(past_rhs, join.llbb);
1742     let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1743                   &[past_lhs.llbb, past_rhs.llbb]);
1744
1745     return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1746 }
1747
1748 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1749                             expr: &ast::Expr,
1750                             op: ast::BinOp,
1751                             lhs: &ast::Expr,
1752                             rhs: &ast::Expr)
1753                             -> DatumBlock<'blk, 'tcx, Expr> {
1754     let _icx = push_ctxt("trans_binary");
1755     let ccx = bcx.ccx();
1756
1757     // if overloaded, would be RvalueDpsExpr
1758     assert!(!ccx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
1759
1760     match op {
1761         ast::BiAnd => {
1762             trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1763         }
1764         ast::BiOr => {
1765             trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1766         }
1767         _ => {
1768             let mut bcx = bcx;
1769             let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1770             let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1771             let binop_ty = expr_ty(bcx, expr);
1772
1773             debug!("trans_binary (expr {}): lhs_datum={}",
1774                    expr.id,
1775                    lhs_datum.to_string(ccx));
1776             let lhs_ty = lhs_datum.ty;
1777             let lhs = lhs_datum.to_llscalarish(bcx);
1778
1779             debug!("trans_binary (expr {}): rhs_datum={}",
1780                    expr.id,
1781                    rhs_datum.to_string(ccx));
1782             let rhs_ty = rhs_datum.ty;
1783             let rhs = rhs_datum.to_llscalarish(bcx);
1784             trans_eager_binop(bcx, expr, binop_ty, op,
1785                               lhs_ty, lhs, rhs_ty, rhs)
1786         }
1787     }
1788 }
1789
1790 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1791                                    expr: &ast::Expr,
1792                                    method_call: MethodCall,
1793                                    lhs: Datum<'tcx, Expr>,
1794                                    rhs: Vec<(Datum<'tcx, Expr>, ast::NodeId)>,
1795                                    dest: Option<Dest>)
1796                                    -> Result<'blk, 'tcx> {
1797     let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
1798     callee::trans_call_inner(bcx,
1799                              Some(expr_info(expr)),
1800                              monomorphize_type(bcx, method_ty),
1801                              |bcx, arg_cleanup_scope| {
1802                                 meth::trans_method_callee(bcx,
1803                                                           method_call,
1804                                                           None,
1805                                                           arg_cleanup_scope)
1806                              },
1807                              callee::ArgOverloadedOp(lhs, rhs),
1808                              dest)
1809 }
1810
1811 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1812                                          expr: &ast::Expr,
1813                                          callee: &'a ast::Expr,
1814                                          args: &'a [P<ast::Expr>],
1815                                          dest: Option<Dest>)
1816                                          -> Block<'blk, 'tcx> {
1817     let method_call = MethodCall::expr(expr.id);
1818     let method_type = (*bcx.tcx()
1819                            .method_map
1820                            .borrow())[method_call]
1821                            .ty;
1822     let mut all_args = vec!(callee);
1823     all_args.extend(args.iter().map(|e| &**e));
1824     unpack_result!(bcx,
1825                    callee::trans_call_inner(bcx,
1826                                             Some(expr_info(expr)),
1827                                             monomorphize_type(bcx,
1828                                                               method_type),
1829                                             |bcx, arg_cleanup_scope| {
1830                                                 meth::trans_method_callee(
1831                                                     bcx,
1832                                                     method_call,
1833                                                     None,
1834                                                     arg_cleanup_scope)
1835                                             },
1836                                             callee::ArgOverloadedCall(all_args),
1837                                             dest));
1838     bcx
1839 }
1840
1841 fn int_cast(bcx: Block,
1842             lldsttype: Type,
1843             llsrctype: Type,
1844             llsrc: ValueRef,
1845             signed: bool)
1846             -> ValueRef {
1847     let _icx = push_ctxt("int_cast");
1848     unsafe {
1849         let srcsz = llvm::LLVMGetIntTypeWidth(llsrctype.to_ref());
1850         let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype.to_ref());
1851         return if dstsz == srcsz {
1852             BitCast(bcx, llsrc, lldsttype)
1853         } else if srcsz > dstsz {
1854             TruncOrBitCast(bcx, llsrc, lldsttype)
1855         } else if signed {
1856             SExtOrBitCast(bcx, llsrc, lldsttype)
1857         } else {
1858             ZExtOrBitCast(bcx, llsrc, lldsttype)
1859         };
1860     }
1861 }
1862
1863 fn float_cast(bcx: Block,
1864               lldsttype: Type,
1865               llsrctype: Type,
1866               llsrc: ValueRef)
1867               -> ValueRef {
1868     let _icx = push_ctxt("float_cast");
1869     let srcsz = llsrctype.float_width();
1870     let dstsz = lldsttype.float_width();
1871     return if dstsz > srcsz {
1872         FPExt(bcx, llsrc, lldsttype)
1873     } else if srcsz > dstsz {
1874         FPTrunc(bcx, llsrc, lldsttype)
1875     } else { llsrc };
1876 }
1877
1878 #[deriving(PartialEq, Show)]
1879 pub enum cast_kind {
1880     cast_pointer,
1881     cast_integral,
1882     cast_float,
1883     cast_enum,
1884     cast_other,
1885 }
1886
1887 impl Copy for cast_kind {}
1888
1889 pub fn cast_type_kind<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> cast_kind {
1890     match t.sty {
1891         ty::ty_char        => cast_integral,
1892         ty::ty_float(..)   => cast_float,
1893         ty::ty_rptr(_, mt) | ty::ty_ptr(mt) => {
1894             if ty::type_is_sized(tcx, mt.ty) {
1895                 cast_pointer
1896             } else {
1897                 cast_other
1898             }
1899         }
1900         ty::ty_bare_fn(..) => cast_pointer,
1901         ty::ty_int(..)     => cast_integral,
1902         ty::ty_uint(..)    => cast_integral,
1903         ty::ty_bool        => cast_integral,
1904         ty::ty_enum(..)    => cast_enum,
1905         _                  => cast_other
1906     }
1907 }
1908
1909 fn cast_is_noop<'tcx>(t_in: Ty<'tcx>, t_out: Ty<'tcx>) -> bool {
1910     match (ty::deref(t_in, true), ty::deref(t_out, true)) {
1911         (Some(ty::mt{ ty: t_in, .. }), Some(ty::mt{ ty: t_out, .. })) => {
1912             t_in == t_out
1913         }
1914         _ => false
1915     }
1916 }
1917
1918 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1919                               expr: &ast::Expr,
1920                               id: ast::NodeId)
1921                               -> DatumBlock<'blk, 'tcx, Expr> {
1922     let _icx = push_ctxt("trans_cast");
1923     let mut bcx = bcx;
1924     let ccx = bcx.ccx();
1925
1926     let t_in = expr_ty(bcx, expr);
1927     let t_out = node_id_type(bcx, id);
1928     let k_in = cast_type_kind(bcx.tcx(), t_in);
1929     let k_out = cast_type_kind(bcx.tcx(), t_out);
1930     let s_in = k_in == cast_integral && ty::type_is_signed(t_in);
1931     let ll_t_in = type_of::arg_type_of(ccx, t_in);
1932     let ll_t_out = type_of::arg_type_of(ccx, t_out);
1933
1934     // Convert the value to be cast into a ValueRef, either by-ref or
1935     // by-value as appropriate given its type:
1936     let mut datum = unpack_datum!(bcx, trans(bcx, expr));
1937
1938     if cast_is_noop(datum.ty, t_out) {
1939         datum.ty = t_out;
1940         return DatumBlock::new(bcx, datum);
1941     }
1942
1943     let newval = match (k_in, k_out) {
1944         (cast_integral, cast_integral) => {
1945             let llexpr = datum.to_llscalarish(bcx);
1946             int_cast(bcx, ll_t_out, ll_t_in, llexpr, s_in)
1947         }
1948         (cast_float, cast_float) => {
1949             let llexpr = datum.to_llscalarish(bcx);
1950             float_cast(bcx, ll_t_out, ll_t_in, llexpr)
1951         }
1952         (cast_integral, cast_float) => {
1953             let llexpr = datum.to_llscalarish(bcx);
1954             if s_in {
1955                 SIToFP(bcx, llexpr, ll_t_out)
1956             } else { UIToFP(bcx, llexpr, ll_t_out) }
1957         }
1958         (cast_float, cast_integral) => {
1959             let llexpr = datum.to_llscalarish(bcx);
1960             if ty::type_is_signed(t_out) {
1961                 FPToSI(bcx, llexpr, ll_t_out)
1962             } else { FPToUI(bcx, llexpr, ll_t_out) }
1963         }
1964         (cast_integral, cast_pointer) => {
1965             let llexpr = datum.to_llscalarish(bcx);
1966             IntToPtr(bcx, llexpr, ll_t_out)
1967         }
1968         (cast_pointer, cast_integral) => {
1969             let llexpr = datum.to_llscalarish(bcx);
1970             PtrToInt(bcx, llexpr, ll_t_out)
1971         }
1972         (cast_pointer, cast_pointer) => {
1973             let llexpr = datum.to_llscalarish(bcx);
1974             PointerCast(bcx, llexpr, ll_t_out)
1975         }
1976         (cast_enum, cast_integral) |
1977         (cast_enum, cast_float) => {
1978             let mut bcx = bcx;
1979             let repr = adt::represent_type(ccx, t_in);
1980             let datum = unpack_datum!(
1981                 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
1982             let llexpr_ptr = datum.to_llref();
1983             let lldiscrim_a =
1984                 adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
1985             match k_out {
1986                 cast_integral => int_cast(bcx, ll_t_out,
1987                                           val_ty(lldiscrim_a),
1988                                           lldiscrim_a, true),
1989                 cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out),
1990                 _ => {
1991                     ccx.sess().bug(format!("translating unsupported cast: \
1992                                             {} ({}) -> {} ({})",
1993                                             t_in.repr(bcx.tcx()),
1994                                             k_in,
1995                                             t_out.repr(bcx.tcx()),
1996                                             k_out).as_slice())
1997                 }
1998             }
1999         }
2000         _ => ccx.sess().bug(format!("translating unsupported cast: \
2001                                     {} ({}) -> {} ({})",
2002                                     t_in.repr(bcx.tcx()),
2003                                     k_in,
2004                                     t_out.repr(bcx.tcx()),
2005                                     k_out).as_slice())
2006     };
2007     return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2008 }
2009
2010 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2011                                expr: &ast::Expr,
2012                                op: ast::BinOp,
2013                                dst: &ast::Expr,
2014                                src: &ast::Expr)
2015                                -> Block<'blk, 'tcx> {
2016     let _icx = push_ctxt("trans_assign_op");
2017     let mut bcx = bcx;
2018
2019     debug!("trans_assign_op(expr={})", bcx.expr_to_string(expr));
2020
2021     // User-defined operator methods cannot be used with `+=` etc right now
2022     assert!(!bcx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
2023
2024     // Evaluate LHS (destination), which should be an lvalue
2025     let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2026     assert!(!ty::type_needs_drop(bcx.tcx(), dst_datum.ty));
2027     let dst_ty = dst_datum.ty;
2028     let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2029
2030     // Evaluate RHS
2031     let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2032     let rhs_ty = rhs_datum.ty;
2033     let rhs = rhs_datum.to_llscalarish(bcx);
2034
2035     // Perform computation and store the result
2036     let result_datum = unpack_datum!(
2037         bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2038                                dst_ty, dst, rhs_ty, rhs));
2039     return result_datum.store_to(bcx, dst_datum.val);
2040 }
2041
2042 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2043                         datum: Datum<'tcx, Expr>,
2044                         expr: &ast::Expr)
2045                         -> DatumBlock<'blk, 'tcx, Expr> {
2046     let mut bcx = bcx;
2047
2048     // Ensure cleanup of `datum` if not already scheduled and obtain
2049     // a "by ref" pointer.
2050     let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2051
2052     // Compute final type. Note that we are loose with the region and
2053     // mutability, since those things don't matter in trans.
2054     let referent_ty = lv_datum.ty;
2055     let ptr_ty = ty::mk_imm_rptr(bcx.tcx(), ty::ReStatic, referent_ty);
2056
2057     // Get the pointer.
2058     let llref = lv_datum.to_llref();
2059
2060     // Construct the resulting datum, using what was the "by ref"
2061     // ValueRef of type `referent_ty` to be the "by value" ValueRef
2062     // of type `&referent_ty`.
2063     DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(ByValue))))
2064 }
2065
2066 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2067                               expr: &ast::Expr,
2068                               datum: Datum<'tcx, Expr>,
2069                               times: uint)
2070                               -> DatumBlock<'blk, 'tcx, Expr> {
2071     let mut bcx = bcx;
2072     let mut datum = datum;
2073     for i in range(0, times) {
2074         let method_call = MethodCall::autoderef(expr.id, i);
2075         datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2076     }
2077     DatumBlock { bcx: bcx, datum: datum }
2078 }
2079
2080 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2081                           expr: &ast::Expr,
2082                           datum: Datum<'tcx, Expr>,
2083                           method_call: MethodCall)
2084                           -> DatumBlock<'blk, 'tcx, Expr> {
2085     let ccx = bcx.ccx();
2086
2087     debug!("deref_once(expr={}, datum={}, method_call={})",
2088            expr.repr(bcx.tcx()),
2089            datum.to_string(ccx),
2090            method_call);
2091
2092     let mut bcx = bcx;
2093
2094     // Check for overloaded deref.
2095     let method_ty = ccx.tcx().method_map.borrow()
2096                        .get(&method_call).map(|method| method.ty);
2097     let datum = match method_ty {
2098         Some(method_ty) => {
2099             // Overloaded. Evaluate `trans_overloaded_op`, which will
2100             // invoke the user's deref() method, which basically
2101             // converts from the `Smaht<T>` pointer that we have into
2102             // a `&T` pointer.  We can then proceed down the normal
2103             // path (below) to dereference that `&T`.
2104             let datum = match method_call.adjustment {
2105                 // Always perform an AutoPtr when applying an overloaded auto-deref
2106                 ty::AutoDeref(_) => unpack_datum!(bcx, auto_ref(bcx, datum, expr)),
2107                 _ => datum
2108             };
2109
2110             let ref_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty)).unwrap();
2111             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2112
2113             unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2114                                                     datum, Vec::new(), Some(SaveIn(scratch.val))));
2115             scratch.to_expr_datum()
2116         }
2117         None => {
2118             // Not overloaded. We already have a pointer we know how to deref.
2119             datum
2120         }
2121     };
2122
2123     let r = match datum.ty.sty {
2124         ty::ty_uniq(content_ty) => {
2125             if ty::type_is_sized(bcx.tcx(), content_ty) {
2126                 deref_owned_pointer(bcx, expr, datum, content_ty)
2127             } else {
2128                 // A fat pointer and an opened DST value have the same
2129                 // representation just different types. Since there is no
2130                 // temporary for `*e` here (because it is unsized), we cannot
2131                 // emulate the sized object code path for running drop glue and
2132                 // free. Instead, we schedule cleanup for `e`, turning it into
2133                 // an lvalue.
2134                 let datum = unpack_datum!(
2135                     bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2136
2137                 let datum = Datum::new(datum.val, ty::mk_open(bcx.tcx(), content_ty), LvalueExpr);
2138                 DatumBlock::new(bcx, datum)
2139             }
2140         }
2141
2142         ty::ty_ptr(ty::mt { ty: content_ty, .. }) |
2143         ty::ty_rptr(_, ty::mt { ty: content_ty, .. }) => {
2144             if ty::type_is_sized(bcx.tcx(), content_ty) {
2145                 let ptr = datum.to_llscalarish(bcx);
2146
2147                 // Always generate an lvalue datum, even if datum.mode is
2148                 // an rvalue.  This is because datum.mode is only an
2149                 // rvalue for non-owning pointers like &T or *T, in which
2150                 // case cleanup *is* scheduled elsewhere, by the true
2151                 // owner (or, in the case of *T, by the user).
2152                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr))
2153             } else {
2154                 // A fat pointer and an opened DST value have the same representation
2155                 // just different types.
2156                 DatumBlock::new(bcx, Datum::new(datum.val,
2157                                                 ty::mk_open(bcx.tcx(), content_ty),
2158                                                 LvalueExpr))
2159             }
2160         }
2161
2162         _ => {
2163             bcx.tcx().sess.span_bug(
2164                 expr.span,
2165                 format!("deref invoked on expr of illegal type {}",
2166                         datum.ty.repr(bcx.tcx())).as_slice());
2167         }
2168     };
2169
2170     debug!("deref_once(expr={}, method_call={}, result={})",
2171            expr.id, method_call, r.datum.to_string(ccx));
2172
2173     return r;
2174
2175     /// We microoptimize derefs of owned pointers a bit here. Basically, the idea is to make the
2176     /// deref of an rvalue result in an rvalue. This helps to avoid intermediate stack slots in the
2177     /// resulting LLVM. The idea here is that, if the `Box<T>` pointer is an rvalue, then we can
2178     /// schedule a *shallow* free of the `Box<T>` pointer, and then return a ByRef rvalue into the
2179     /// pointer. Because the free is shallow, it is legit to return an rvalue, because we know that
2180     /// the contents are not yet scheduled to be freed. The language rules ensure that the contents
2181     /// will be used (or moved) before the free occurs.
2182     fn deref_owned_pointer<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2183                                        expr: &ast::Expr,
2184                                        datum: Datum<'tcx, Expr>,
2185                                        content_ty: Ty<'tcx>)
2186                                        -> DatumBlock<'blk, 'tcx, Expr> {
2187         match datum.kind {
2188             RvalueExpr(Rvalue { mode: ByRef }) => {
2189                 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2190                 let ptr = Load(bcx, datum.val);
2191                 if !type_is_zero_size(bcx.ccx(), content_ty) {
2192                     bcx.fcx.schedule_free_value(scope, ptr, cleanup::HeapExchange, content_ty);
2193                 }
2194             }
2195             RvalueExpr(Rvalue { mode: ByValue }) => {
2196                 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2197                 if !type_is_zero_size(bcx.ccx(), content_ty) {
2198                     bcx.fcx.schedule_free_value(scope, datum.val, cleanup::HeapExchange,
2199                                                 content_ty);
2200                 }
2201             }
2202             LvalueExpr => { }
2203         }
2204
2205         // If we had an rvalue in, we produce an rvalue out.
2206         let (llptr, kind) = match datum.kind {
2207             LvalueExpr => {
2208                 (Load(bcx, datum.val), LvalueExpr)
2209             }
2210             RvalueExpr(Rvalue { mode: ByRef }) => {
2211                 (Load(bcx, datum.val), RvalueExpr(Rvalue::new(ByRef)))
2212             }
2213             RvalueExpr(Rvalue { mode: ByValue }) => {
2214                 (datum.val, RvalueExpr(Rvalue::new(ByRef)))
2215             }
2216         };
2217
2218         let datum = Datum { ty: content_ty, val: llptr, kind: kind };
2219         DatumBlock { bcx: bcx, datum: datum }
2220     }
2221 }