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