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