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