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