]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/expr.rs
Auto merge of #28020 - dotdash:ref_fat_ptr_be_gone, r=eddyb
[rust.git] / src / librustc_trans / trans / expr.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! # Translation of Expressions
12 //!
13 //! The expr module handles translation of expressions. The most general
14 //! translation routine is `trans()`, which will translate an expression
15 //! into a datum. `trans_into()` is also available, which will translate
16 //! an expression and write the result directly into memory, sometimes
17 //! avoiding the need for a temporary stack slot. Finally,
18 //! `trans_to_lvalue()` is available if you'd like to ensure that the
19 //! result has cleanup scheduled.
20 //!
21 //! Internally, each of these functions dispatches to various other
22 //! expression functions depending on the kind of expression. We divide
23 //! up expressions into:
24 //!
25 //! - **Datum expressions:** Those that most naturally yield values.
26 //!   Examples would be `22`, `box x`, or `a + b` (when not overloaded).
27 //! - **DPS expressions:** Those that most naturally write into a location
28 //!   in memory. Examples would be `foo()` or `Point { x: 3, y: 4 }`.
29 //! - **Statement expressions:** That that do not generate a meaningful
30 //!   result. Examples would be `while { ... }` or `return 44`.
31 //!
32 //! Public entry points:
33 //!
34 //! - `trans_into(bcx, expr, dest) -> bcx`: evaluates an expression,
35 //!   storing the result into `dest`. This is the preferred form, if you
36 //!   can manage it.
37 //!
38 //! - `trans(bcx, expr) -> DatumBlock`: evaluates an expression, yielding
39 //!   `Datum` with the result. You can then store the datum, inspect
40 //!   the value, etc. This may introduce temporaries if the datum is a
41 //!   structural type.
42 //!
43 //! - `trans_to_lvalue(bcx, expr, "...") -> DatumBlock`: evaluates an
44 //!   expression and ensures that the result has a cleanup associated with it,
45 //!   creating a temporary stack slot if necessary.
46 //!
47 //! - `trans_local_var -> Datum`: looks up a local variable or upvar.
48
49 #![allow(non_camel_case_types)]
50
51 pub use self::Dest::*;
52 use self::lazy_binop_ty::*;
53
54 use back::abi;
55 use llvm::{self, ValueRef, TypeKind};
56 use middle::check_const;
57 use middle::def;
58 use middle::lang_items::CoerceUnsizedTraitLangItem;
59 use middle::subst::{Substs, VecPerParamSpace};
60 use middle::traits;
61 use trans::{_match, adt, asm, base, callee, closure, consts, controlflow};
62 use trans::base::*;
63 use trans::build::*;
64 use trans::cleanup::{self, CleanupMethods, DropHintMethods};
65 use trans::common::*;
66 use trans::datum::*;
67 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
68 use trans::declare;
69 use trans::glue;
70 use trans::machine;
71 use trans::meth;
72 use trans::tvec;
73 use trans::type_of;
74 use middle::cast::{CastKind, CastTy};
75 use middle::ty::{AdjustDerefRef, AdjustReifyFnPointer, AdjustUnsafeFnPointer};
76 use middle::ty::{self, Ty};
77 use middle::ty::MethodCall;
78 use util::common::indenter;
79 use trans::machine::{llsize_of, llsize_of_alloc};
80 use trans::type_::Type;
81
82 use syntax::{ast, ast_util, codemap};
83 use syntax::parse::token::InternedString;
84 use syntax::ptr::P;
85 use syntax::parse::token;
86 use std::mem;
87
88 // Destinations
89
90 // These are passed around by the code generating functions to track the
91 // destination of a computation's value.
92
93 #[derive(Copy, Clone, PartialEq)]
94 pub enum Dest {
95     SaveIn(ValueRef),
96     Ignore,
97 }
98
99 impl Dest {
100     pub fn to_string(&self, ccx: &CrateContext) -> String {
101         match *self {
102             SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
103             Ignore => "Ignore".to_string()
104         }
105     }
106 }
107
108 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
109 /// better optimized LLVM code.
110 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
111                               expr: &ast::Expr,
112                               dest: Dest)
113                               -> Block<'blk, 'tcx> {
114     let mut bcx = bcx;
115
116     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
117
118     if bcx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
119         // use trans, which may be less efficient but
120         // which will perform the adjustments:
121         let datum = unpack_datum!(bcx, trans(bcx, expr));
122         return datum.store_to_dest(bcx, dest, expr.id);
123     }
124
125     let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
126     if !qualif.intersects(
127         check_const::ConstQualif::NOT_CONST |
128         check_const::ConstQualif::NEEDS_DROP
129     ) {
130         if !qualif.intersects(check_const::ConstQualif::PREFER_IN_PLACE) {
131             if let SaveIn(lldest) = dest {
132                 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
133                                                             bcx.fcx.param_substs);
134                 // Cast pointer to destination, because constants
135                 // have different types.
136                 let lldest = PointerCast(bcx, lldest, val_ty(global));
137                 memcpy_ty(bcx, lldest, global, expr_ty_adjusted(bcx, expr));
138                 return bcx;
139             }
140             // Even if we don't have a value to emit, and the expression
141             // doesn't have any side-effects, we still have to translate the
142             // body of any closures.
143             // FIXME: Find a better way of handling this case.
144         } else {
145             // The only way we're going to see a `const` at this point is if
146             // it prefers in-place instantiation, likely because it contains
147             // `[x; N]` somewhere within.
148             match expr.node {
149                 ast::ExprPath(..) => {
150                     match bcx.def(expr.id) {
151                         def::DefConst(did) => {
152                             let const_expr = consts::get_const_expr(bcx.ccx(), did, expr);
153                             // Temporarily get cleanup scopes out of the way,
154                             // as they require sub-expressions to be contained
155                             // inside the current AST scope.
156                             // These should record no cleanups anyways, `const`
157                             // can't have destructors.
158                             let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
159                                                       vec![]);
160                             // Lock emitted debug locations to the location of
161                             // the constant reference expression.
162                             debuginfo::with_source_location_override(bcx.fcx,
163                                                                      expr.debug_loc(),
164                                                                      || {
165                                 bcx = trans_into(bcx, const_expr, dest)
166                             });
167                             let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
168                                                       scopes);
169                             assert!(scopes.is_empty());
170                             return bcx;
171                         }
172                         _ => {}
173                     }
174                 }
175                 _ => {}
176             }
177         }
178     }
179
180     debug!("trans_into() expr={:?}", expr);
181
182     let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
183                                                                           expr.id,
184                                                                           expr.span,
185                                                                           false);
186     bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
187
188     let kind = expr_kind(bcx.tcx(), expr);
189     bcx = match kind {
190         ExprKind::Lvalue | ExprKind::RvalueDatum => {
191             trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
192         }
193         ExprKind::RvalueDps => {
194             trans_rvalue_dps_unadjusted(bcx, expr, dest)
195         }
196         ExprKind::RvalueStmt => {
197             trans_rvalue_stmt_unadjusted(bcx, expr)
198         }
199     };
200
201     bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
202 }
203
204 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
205 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
206 /// stack.
207 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
208                          expr: &ast::Expr)
209                          -> DatumBlock<'blk, 'tcx, Expr> {
210     debug!("trans(expr={:?})", expr);
211
212     let mut bcx = bcx;
213     let fcx = bcx.fcx;
214     let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
215     let adjusted_global = !qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS);
216     let global = if !qualif.intersects(
217         check_const::ConstQualif::NOT_CONST |
218         check_const::ConstQualif::NEEDS_DROP
219     ) {
220         let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
221                                                       bcx.fcx.param_substs);
222
223         if qualif.intersects(check_const::ConstQualif::HAS_STATIC_BORROWS) {
224             // Is borrowed as 'static, must return lvalue.
225
226             // Cast pointer to global, because constants have different types.
227             let const_ty = expr_ty_adjusted(bcx, expr);
228             let llty = type_of::type_of(bcx.ccx(), const_ty);
229             let global = PointerCast(bcx, global, llty.ptr_to());
230             let datum = Datum::new(global, const_ty, Lvalue::new("expr::trans"));
231             return DatumBlock::new(bcx, datum.to_expr_datum());
232         }
233
234         // Otherwise, keep around and perform adjustments, if needed.
235         let const_ty = if adjusted_global {
236             expr_ty_adjusted(bcx, expr)
237         } else {
238             expr_ty(bcx, expr)
239         };
240
241         // This could use a better heuristic.
242         Some(if type_is_immediate(bcx.ccx(), const_ty) {
243             // Cast pointer to global, because constants have different types.
244             let llty = type_of::type_of(bcx.ccx(), const_ty);
245             let global = PointerCast(bcx, global, llty.ptr_to());
246             // Maybe just get the value directly, instead of loading it?
247             immediate_rvalue(load_ty(bcx, global, const_ty), const_ty)
248         } else {
249             let llty = type_of::type_of(bcx.ccx(), const_ty);
250             // HACK(eddyb) get around issues with lifetime intrinsics.
251             let scratch = alloca_no_lifetime(bcx, llty, "const");
252             let lldest = if !const_ty.is_structural() {
253                 // Cast pointer to slot, because constants have different types.
254                 PointerCast(bcx, scratch, val_ty(global))
255             } else {
256                 // In this case, memcpy_ty calls llvm.memcpy after casting both
257                 // source and destination to i8*, so we don't need any casts.
258                 scratch
259             };
260             memcpy_ty(bcx, lldest, global, const_ty);
261             Datum::new(scratch, const_ty, Rvalue::new(ByRef))
262         })
263     } else {
264         None
265     };
266
267     let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
268                                                                           expr.id,
269                                                                           expr.span,
270                                                                           false);
271     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
272     let datum = match global {
273         Some(rvalue) => rvalue.to_expr_datum(),
274         None => unpack_datum!(bcx, trans_unadjusted(bcx, expr))
275     };
276     let datum = if adjusted_global {
277         datum // trans::consts already performed adjustments.
278     } else {
279         unpack_datum!(bcx, apply_adjustments(bcx, expr, datum))
280     };
281     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
282     return DatumBlock::new(bcx, datum);
283 }
284
285 pub fn get_meta(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
286     StructGEP(bcx, fat_ptr, abi::FAT_PTR_EXTRA)
287 }
288
289 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
290     StructGEP(bcx, fat_ptr, abi::FAT_PTR_ADDR)
291 }
292
293 pub fn copy_fat_ptr(bcx: Block, src_ptr: ValueRef, dst_ptr: ValueRef) {
294     Store(bcx, Load(bcx, get_dataptr(bcx, src_ptr)), get_dataptr(bcx, dst_ptr));
295     Store(bcx, Load(bcx, get_meta(bcx, src_ptr)), get_meta(bcx, dst_ptr));
296 }
297
298 /// Retrieve the information we are losing (making dynamic) in an unsizing
299 /// adjustment.
300 ///
301 /// The `old_info` argument is a bit funny. It is intended for use
302 /// in an upcast, where the new vtable for an object will be drived
303 /// from the old one.
304 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
305                                 source: Ty<'tcx>,
306                                 target: Ty<'tcx>,
307                                 old_info: Option<ValueRef>,
308                                 param_substs: &'tcx Substs<'tcx>)
309                                 -> ValueRef {
310     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
311     match (&source.sty, &target.sty) {
312         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
313         (&ty::TyTrait(_), &ty::TyTrait(_)) => {
314             // For now, upcasts are limited to changes in marker
315             // traits, and hence never actually require an actual
316             // change to the vtable.
317             old_info.expect("unsized_info: missing old info for trait upcast")
318         }
319         (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
320             // Note that we preserve binding levels here:
321             let substs = principal.0.substs.with_self_ty(source).erase_regions();
322             let substs = ccx.tcx().mk_substs(substs);
323             let trait_ref = ty::Binder(ty::TraitRef { def_id: principal.def_id(),
324                                                       substs: substs });
325             consts::ptrcast(meth::get_vtable(ccx, trait_ref, param_substs),
326                             Type::vtable_ptr(ccx))
327         }
328         _ => ccx.sess().bug(&format!("unsized_info: invalid unsizing {:?} -> {:?}",
329                                      source,
330                                      target))
331     }
332 }
333
334 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
335 /// translation of `expr`.
336 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
337                                  expr: &ast::Expr,
338                                  datum: Datum<'tcx, Expr>)
339                                  -> DatumBlock<'blk, 'tcx, Expr>
340 {
341     let mut bcx = bcx;
342     let mut datum = datum;
343     let adjustment = match bcx.tcx().tables.borrow().adjustments.get(&expr.id).cloned() {
344         None => {
345             return DatumBlock::new(bcx, datum);
346         }
347         Some(adj) => { adj }
348     };
349     debug!("unadjusted datum for expr {:?}: {} adjustment={:?}",
350            expr,
351            datum.to_string(bcx.ccx()),
352            adjustment);
353     match adjustment {
354         AdjustReifyFnPointer => {
355             // FIXME(#19925) once fn item types are
356             // zero-sized, we'll need to do something here
357         }
358         AdjustUnsafeFnPointer => {
359             // purely a type-level thing
360         }
361         AdjustDerefRef(ref adj) => {
362             let skip_reborrows = if adj.autoderefs == 1 && adj.autoref.is_some() {
363                 // We are a bit paranoid about adjustments and thus might have a re-
364                 // borrow here which merely derefs and then refs again (it might have
365                 // a different region or mutability, but we don't care here).
366                 match datum.ty.sty {
367                     // Don't skip a conversion from Box<T> to &T, etc.
368                     ty::TyRef(..) => {
369                         if bcx.tcx().is_overloaded_autoderef(expr.id, 0) {
370                             // Don't skip an overloaded deref.
371                             0
372                         } else {
373                             1
374                         }
375                     }
376                     _ => 0
377                 }
378             } else {
379                 0
380             };
381
382             if adj.autoderefs > skip_reborrows {
383                 // Schedule cleanup.
384                 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
385                 datum = unpack_datum!(bcx, deref_multiple(bcx, expr,
386                                                           lval.to_expr_datum(),
387                                                           adj.autoderefs - skip_reborrows));
388             }
389
390             // (You might think there is a more elegant way to do this than a
391             // skip_reborrows bool, but then you remember that the borrow checker exists).
392             if skip_reborrows == 0 && adj.autoref.is_some() {
393                 datum = unpack_datum!(bcx, auto_ref(bcx, datum, expr));
394             }
395
396             if let Some(target) = adj.unsize {
397                 // We do not arrange cleanup ourselves; if we already are an
398                 // L-value, then cleanup will have already been scheduled (and
399                 // the `datum.to_rvalue_datum` call below will emit code to zero
400                 // the drop flag when moving out of the L-value). If we are an
401                 // R-value, then we do not need to schedule cleanup.
402                 let source_datum = unpack_datum!(bcx,
403                     datum.to_rvalue_datum(bcx, "__coerce_source"));
404
405                 let target = bcx.monomorphize(&target);
406                 let llty = type_of::type_of(bcx.ccx(), target);
407
408                 // HACK(eddyb) get around issues with lifetime intrinsics.
409                 let scratch = alloca_no_lifetime(bcx, llty, "__coerce_target");
410                 let target_datum = Datum::new(scratch, target,
411                                               Rvalue::new(ByRef));
412                 bcx = coerce_unsized(bcx, expr.span, source_datum, target_datum);
413                 datum = Datum::new(scratch, target,
414                                    RvalueExpr(Rvalue::new(ByRef)));
415             }
416         }
417     }
418     debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
419     DatumBlock::new(bcx, datum)
420 }
421
422 fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
423                               span: codemap::Span,
424                               source: Datum<'tcx, Rvalue>,
425                               target: Datum<'tcx, Rvalue>)
426                               -> Block<'blk, 'tcx> {
427     let mut bcx = bcx;
428     debug!("coerce_unsized({} -> {})",
429            source.to_string(bcx.ccx()),
430            target.to_string(bcx.ccx()));
431
432     match (&source.ty.sty, &target.ty.sty) {
433         (&ty::TyBox(a), &ty::TyBox(b)) |
434         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
435          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
436         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
437          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
438         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
439          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
440             let (inner_source, inner_target) = (a, b);
441
442             let (base, old_info) = if !type_is_sized(bcx.tcx(), inner_source) {
443                 // Normally, the source is a thin pointer and we are
444                 // adding extra info to make a fat pointer. The exception
445                 // is when we are upcasting an existing object fat pointer
446                 // to use a different vtable. In that case, we want to
447                 // load out the original data pointer so we can repackage
448                 // it.
449                 (Load(bcx, get_dataptr(bcx, source.val)),
450                 Some(Load(bcx, get_meta(bcx, source.val))))
451             } else {
452                 let val = if source.kind.is_by_ref() {
453                     load_ty(bcx, source.val, source.ty)
454                 } else {
455                     source.val
456                 };
457                 (val, None)
458             };
459
460             let info = unsized_info(bcx.ccx(), inner_source, inner_target,
461                                     old_info, bcx.fcx.param_substs);
462
463             // Compute the base pointer. This doesn't change the pointer value,
464             // but merely its type.
465             let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), inner_target).ptr_to();
466             let base = PointerCast(bcx, base, ptr_ty);
467
468             Store(bcx, base, get_dataptr(bcx, target.val));
469             Store(bcx, info, get_meta(bcx, target.val));
470         }
471
472         // This can be extended to enums and tuples in the future.
473         // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
474         (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
475             assert_eq!(def_id_a, def_id_b);
476
477             // The target is already by-ref because it's to be written to.
478             let source = unpack_datum!(bcx, source.to_ref_datum(bcx));
479             assert!(target.kind.is_by_ref());
480
481             let trait_substs = Substs::erased(VecPerParamSpace::new(vec![target.ty],
482                                                                     vec![source.ty],
483                                                                     Vec::new()));
484             let trait_ref = ty::Binder(ty::TraitRef {
485                 def_id: langcall(bcx, Some(span), "coercion",
486                                  CoerceUnsizedTraitLangItem),
487                 substs: bcx.tcx().mk_substs(trait_substs)
488             });
489
490             let kind = match fulfill_obligation(bcx.ccx(), span, trait_ref) {
491                 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
492                     bcx.tcx().custom_coerce_unsized_kind(impl_def_id)
493                 }
494                 vtable => {
495                     bcx.sess().span_bug(span, &format!("invalid CoerceUnsized vtable: {:?}",
496                                                        vtable));
497                 }
498             };
499
500             let repr_source = adt::represent_type(bcx.ccx(), source.ty);
501             let src_fields = match &*repr_source {
502                 &adt::Repr::Univariant(ref s, _) => &s.fields,
503                 _ => bcx.sess().span_bug(span,
504                                          &format!("Non univariant struct? (repr_source: {:?})",
505                                                   repr_source)),
506             };
507             let repr_target = adt::represent_type(bcx.ccx(), target.ty);
508             let target_fields = match &*repr_target {
509                 &adt::Repr::Univariant(ref s, _) => &s.fields,
510                 _ => bcx.sess().span_bug(span,
511                                          &format!("Non univariant struct? (repr_target: {:?})",
512                                                   repr_target)),
513             };
514
515             let coerce_index = match kind {
516                 ty::CustomCoerceUnsized::Struct(i) => i
517             };
518             assert!(coerce_index < src_fields.len() && src_fields.len() == target_fields.len());
519
520             let iter = src_fields.iter().zip(target_fields).enumerate();
521             for (i, (src_ty, target_ty)) in iter {
522                 let ll_source = adt::trans_field_ptr(bcx, &repr_source, source.val, 0, i);
523                 let ll_target = adt::trans_field_ptr(bcx, &repr_target, target.val, 0, i);
524
525                 // If this is the field we need to coerce, recurse on it.
526                 if i == coerce_index {
527                     coerce_unsized(bcx, span,
528                                    Datum::new(ll_source, src_ty,
529                                               Rvalue::new(ByRef)),
530                                    Datum::new(ll_target, target_ty,
531                                               Rvalue::new(ByRef)));
532                 } else {
533                     // Otherwise, simply copy the data from the source.
534                     assert_eq!(src_ty, target_ty);
535                     memcpy_ty(bcx, ll_target, ll_source, src_ty);
536                 }
537             }
538         }
539         _ => bcx.sess().bug(&format!("coerce_unsized: invalid coercion {:?} -> {:?}",
540                                      source.ty,
541                                      target.ty))
542     }
543     bcx
544 }
545
546 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
547 /// that the expr represents.
548 ///
549 /// If this expression is an rvalue, this implies introducing a temporary.  In other words,
550 /// something like `x().f` is translated into roughly the equivalent of
551 ///
552 ///   { tmp = x(); tmp.f }
553 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
554                                    expr: &ast::Expr,
555                                    name: &str)
556                                    -> DatumBlock<'blk, 'tcx, Lvalue> {
557     let mut bcx = bcx;
558     let datum = unpack_datum!(bcx, trans(bcx, expr));
559     return datum.to_lvalue_datum(bcx, name, expr.id);
560 }
561
562 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
563 /// directly.
564 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
565                                 expr: &ast::Expr)
566                                 -> DatumBlock<'blk, 'tcx, Expr> {
567     let mut bcx = bcx;
568
569     debug!("trans_unadjusted(expr={:?})", expr);
570     let _indenter = indenter();
571
572     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
573
574     return match expr_kind(bcx.tcx(), expr) {
575         ExprKind::Lvalue | ExprKind::RvalueDatum => {
576             let datum = unpack_datum!(bcx, {
577                 trans_datum_unadjusted(bcx, expr)
578             });
579
580             DatumBlock {bcx: bcx, datum: datum}
581         }
582
583         ExprKind::RvalueStmt => {
584             bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
585             nil(bcx, expr_ty(bcx, expr))
586         }
587
588         ExprKind::RvalueDps => {
589             let ty = expr_ty(bcx, expr);
590             if type_is_zero_size(bcx.ccx(), ty) {
591                 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
592                 nil(bcx, ty)
593             } else {
594                 let scratch = rvalue_scratch_datum(bcx, ty, "");
595                 bcx = trans_rvalue_dps_unadjusted(
596                     bcx, expr, SaveIn(scratch.val));
597
598                 // Note: this is not obviously a good idea.  It causes
599                 // immediate values to be loaded immediately after a
600                 // return from a call or other similar expression,
601                 // which in turn leads to alloca's having shorter
602                 // lifetimes and hence larger stack frames.  However,
603                 // in turn it can lead to more register pressure.
604                 // Still, in practice it seems to increase
605                 // performance, since we have fewer problems with
606                 // morestack churn.
607                 let scratch = unpack_datum!(
608                     bcx, scratch.to_appropriate_datum(bcx));
609
610                 DatumBlock::new(bcx, scratch.to_expr_datum())
611             }
612         }
613     };
614
615     fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
616                        -> DatumBlock<'blk, 'tcx, Expr> {
617         let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
618         let datum = immediate_rvalue(llval, ty);
619         DatumBlock::new(bcx, datum.to_expr_datum())
620     }
621 }
622
623 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
624                                       expr: &ast::Expr)
625                                       -> DatumBlock<'blk, 'tcx, Expr> {
626     let mut bcx = bcx;
627     let fcx = bcx.fcx;
628     let _icx = push_ctxt("trans_datum_unadjusted");
629
630     match expr.node {
631         ast::ExprParen(ref e) => {
632             trans(bcx, &**e)
633         }
634         ast::ExprPath(..) => {
635             trans_def(bcx, expr, bcx.def(expr.id))
636         }
637         ast::ExprField(ref base, ident) => {
638             trans_rec_field(bcx, &**base, ident.node.name)
639         }
640         ast::ExprTupField(ref base, idx) => {
641             trans_rec_tup_field(bcx, &**base, idx.node)
642         }
643         ast::ExprIndex(ref base, ref idx) => {
644             trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
645         }
646         ast::ExprBox(_, ref contents) => {
647             // Special case for `Box<T>`
648             let box_ty = expr_ty(bcx, expr);
649             let contents_ty = expr_ty(bcx, &**contents);
650             match box_ty.sty {
651                 ty::TyBox(..) => {
652                     trans_uniq_expr(bcx, expr, box_ty, &**contents, contents_ty)
653                 }
654                 _ => bcx.sess().span_bug(expr.span,
655                                          "expected unique box")
656             }
657
658         }
659         ast::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
660         ast::ExprBinary(op, ref lhs, ref rhs) => {
661             trans_binary(bcx, expr, op, &**lhs, &**rhs)
662         }
663         ast::ExprUnary(op, ref x) => {
664             trans_unary(bcx, expr, op, &**x)
665         }
666         ast::ExprAddrOf(_, ref x) => {
667             match x.node {
668                 ast::ExprRepeat(..) | ast::ExprVec(..) => {
669                     // Special case for slices.
670                     let cleanup_debug_loc =
671                         debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
672                                                                       x.id,
673                                                                       x.span,
674                                                                       false);
675                     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
676                     let datum = unpack_datum!(
677                         bcx, tvec::trans_slice_vec(bcx, expr, &**x));
678                     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
679                     DatumBlock::new(bcx, datum)
680                 }
681                 _ => {
682                     trans_addr_of(bcx, expr, &**x)
683                 }
684             }
685         }
686         ast::ExprCast(ref val, _) => {
687             // Datum output mode means this is a scalar cast:
688             trans_imm_cast(bcx, &**val, expr.id)
689         }
690         _ => {
691             bcx.tcx().sess.span_bug(
692                 expr.span,
693                 &format!("trans_rvalue_datum_unadjusted reached \
694                          fall-through case: {:?}",
695                         expr.node));
696         }
697     }
698 }
699
700 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
701                               base: &ast::Expr,
702                               get_idx: F)
703                               -> DatumBlock<'blk, 'tcx, Expr> where
704     F: FnOnce(&'blk ty::ctxt<'tcx>, &VariantInfo<'tcx>) -> usize,
705 {
706     let mut bcx = bcx;
707     let _icx = push_ctxt("trans_rec_field");
708
709     let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
710     let bare_ty = base_datum.ty;
711     let repr = adt::represent_type(bcx.ccx(), bare_ty);
712     let vinfo = VariantInfo::from_ty(bcx.tcx(), bare_ty, None);
713
714     let ix = get_idx(bcx.tcx(), &vinfo);
715     let d = base_datum.get_element(
716         bcx,
717         vinfo.fields[ix].1,
718         |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, vinfo.discr, ix));
719
720     if type_is_sized(bcx.tcx(), d.ty) {
721         DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
722     } else {
723         let scratch = rvalue_scratch_datum(bcx, d.ty, "");
724         Store(bcx, d.val, get_dataptr(bcx, scratch.val));
725         let info = Load(bcx, get_meta(bcx, base_datum.val));
726         Store(bcx, info, get_meta(bcx, scratch.val));
727
728         // Always generate an lvalue datum, because this pointer doesn't own
729         // the data and cleanup is scheduled elsewhere.
730         DatumBlock::new(bcx, Datum::new(scratch.val, scratch.ty, LvalueExpr(d.kind)))
731     }
732 }
733
734 /// Translates `base.field`.
735 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
736                                base: &ast::Expr,
737                                field: ast::Name)
738                                -> DatumBlock<'blk, 'tcx, Expr> {
739     trans_field(bcx, base, |_, vinfo| vinfo.field_index(field))
740 }
741
742 /// Translates `base.<idx>`.
743 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
744                                    base: &ast::Expr,
745                                    idx: usize)
746                                    -> DatumBlock<'blk, 'tcx, Expr> {
747     trans_field(bcx, base, |_, _| idx)
748 }
749
750 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
751                            index_expr: &ast::Expr,
752                            base: &ast::Expr,
753                            idx: &ast::Expr,
754                            method_call: MethodCall)
755                            -> DatumBlock<'blk, 'tcx, Expr> {
756     //! Translates `base[idx]`.
757
758     let _icx = push_ctxt("trans_index");
759     let ccx = bcx.ccx();
760     let mut bcx = bcx;
761
762     let index_expr_debug_loc = index_expr.debug_loc();
763
764     // Check for overloaded index.
765     let method_ty = ccx.tcx()
766                        .tables
767                        .borrow()
768                        .method_map
769                        .get(&method_call)
770                        .map(|method| method.ty);
771     let elt_datum = match method_ty {
772         Some(method_ty) => {
773             let method_ty = monomorphize_type(bcx, method_ty);
774
775             let base_datum = unpack_datum!(bcx, trans(bcx, base));
776
777             // Translate index expression.
778             let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
779
780             let ref_ty = // invoked methods have LB regions instantiated:
781                 bcx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
782             let elt_ty = match ref_ty.builtin_deref(true) {
783                 None => {
784                     bcx.tcx().sess.span_bug(index_expr.span,
785                                             "index method didn't return a \
786                                              dereferenceable type?!")
787                 }
788                 Some(elt_tm) => elt_tm.ty,
789             };
790
791             // Overloaded. Evaluate `trans_overloaded_op`, which will
792             // invoke the user's index() method, which basically yields
793             // a `&T` pointer.  We can then proceed down the normal
794             // path (below) to dereference that `&T`.
795             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
796             unpack_result!(bcx,
797                            trans_overloaded_op(bcx,
798                                                index_expr,
799                                                method_call,
800                                                base_datum,
801                                                Some((ix_datum, idx.id)),
802                                                Some(SaveIn(scratch.val)),
803                                                false));
804             let datum = scratch.to_expr_datum();
805             let lval = Lvalue::new("expr::trans_index overload");
806             if type_is_sized(bcx.tcx(), elt_ty) {
807                 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr(lval))
808             } else {
809                 Datum::new(datum.val, elt_ty, LvalueExpr(lval))
810             }
811         }
812         None => {
813             let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
814                                                                 base,
815                                                                 "index"));
816
817             // Translate index expression and cast to a suitable LLVM integer.
818             // Rust is less strict than LLVM in this regard.
819             let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
820             let ix_val = ix_datum.to_llscalarish(bcx);
821             let ix_size = machine::llbitsize_of_real(bcx.ccx(),
822                                                      val_ty(ix_val));
823             let int_size = machine::llbitsize_of_real(bcx.ccx(),
824                                                       ccx.int_type());
825             let ix_val = {
826                 if ix_size < int_size {
827                     if expr_ty(bcx, idx).is_signed() {
828                         SExt(bcx, ix_val, ccx.int_type())
829                     } else { ZExt(bcx, ix_val, ccx.int_type()) }
830                 } else if ix_size > int_size {
831                     Trunc(bcx, ix_val, ccx.int_type())
832                 } else {
833                     ix_val
834                 }
835             };
836
837             let unit_ty = base_datum.ty.sequence_element_type(bcx.tcx());
838
839             let (base, len) = base_datum.get_vec_base_and_len(bcx);
840
841             debug!("trans_index: base {}", bcx.val_to_string(base));
842             debug!("trans_index: len {}", bcx.val_to_string(len));
843
844             let bounds_check = ICmp(bcx,
845                                     llvm::IntUGE,
846                                     ix_val,
847                                     len,
848                                     index_expr_debug_loc);
849             let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
850             let expected = Call(bcx,
851                                 expect,
852                                 &[bounds_check, C_bool(ccx, false)],
853                                 None,
854                                 index_expr_debug_loc);
855             bcx = with_cond(bcx, expected, |bcx| {
856                 controlflow::trans_fail_bounds_check(bcx,
857                                                      expr_info(index_expr),
858                                                      ix_val,
859                                                      len)
860             });
861             let elt = InBoundsGEP(bcx, base, &[ix_val]);
862             let elt = PointerCast(bcx, elt, type_of::type_of(ccx, unit_ty).ptr_to());
863             let lval = Lvalue::new("expr::trans_index fallback");
864             Datum::new(elt, unit_ty, LvalueExpr(lval))
865         }
866     };
867
868     DatumBlock::new(bcx, elt_datum)
869 }
870
871 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
872                          ref_expr: &ast::Expr,
873                          def: def::Def)
874                          -> DatumBlock<'blk, 'tcx, Expr> {
875     //! Translates a reference to a path.
876
877     let _icx = push_ctxt("trans_def_lvalue");
878     match def {
879         def::DefFn(..) | def::DefMethod(..) |
880         def::DefStruct(_) | def::DefVariant(..) => {
881             let datum = trans_def_fn_unadjusted(bcx.ccx(), ref_expr, def,
882                                                 bcx.fcx.param_substs);
883             DatumBlock::new(bcx, datum.to_expr_datum())
884         }
885         def::DefStatic(did, _) => {
886             // There are two things that may happen here:
887             //  1) If the static item is defined in this crate, it will be
888             //     translated using `get_item_val`, and we return a pointer to
889             //     the result.
890             //  2) If the static item is defined in another crate then we add
891             //     (or reuse) a declaration of an external global, and return a
892             //     pointer to that.
893             let const_ty = expr_ty(bcx, ref_expr);
894
895             // For external constants, we don't inline.
896             let val = if did.is_local() {
897                 // Case 1.
898
899                 // The LLVM global has the type of its initializer,
900                 // which may not be equal to the enum's type for
901                 // non-C-like enums.
902                 let val = base::get_item_val(bcx.ccx(), did.node);
903                 let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
904                 PointerCast(bcx, val, pty)
905             } else {
906                 // Case 2.
907                 base::get_extern_const(bcx.ccx(), did, const_ty)
908             };
909             let lval = Lvalue::new("expr::trans_def");
910             DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr(lval)))
911         }
912         def::DefConst(_) => {
913             bcx.sess().span_bug(ref_expr.span,
914                 "constant expression should not reach expr::trans_def")
915         }
916         _ => {
917             DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
918         }
919     }
920 }
921
922 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
923                                             expr: &ast::Expr)
924                                             -> Block<'blk, 'tcx> {
925     let mut bcx = bcx;
926     let _icx = push_ctxt("trans_rvalue_stmt");
927
928     if bcx.unreachable.get() {
929         return bcx;
930     }
931
932     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
933
934     match expr.node {
935         ast::ExprParen(ref e) => {
936             trans_into(bcx, &**e, Ignore)
937         }
938         ast::ExprBreak(label_opt) => {
939             controlflow::trans_break(bcx, expr, label_opt)
940         }
941         ast::ExprAgain(label_opt) => {
942             controlflow::trans_cont(bcx, expr, label_opt)
943         }
944         ast::ExprRet(ref ex) => {
945             // Check to see if the return expression itself is reachable.
946             // This can occur when the inner expression contains a return
947             let reachable = if let Some(ref cfg) = bcx.fcx.cfg {
948                 cfg.node_is_reachable(expr.id)
949             } else {
950                 true
951             };
952
953             if reachable {
954                 controlflow::trans_ret(bcx, expr, ex.as_ref().map(|e| &**e))
955             } else {
956                 // If it's not reachable, just translate the inner expression
957                 // directly. This avoids having to manage a return slot when
958                 // it won't actually be used anyway.
959                 if let &Some(ref x) = ex {
960                     bcx = trans_into(bcx, &**x, Ignore);
961                 }
962                 // Mark the end of the block as unreachable. Once we get to
963                 // a return expression, there's no more we should be doing
964                 // after this.
965                 Unreachable(bcx);
966                 bcx
967             }
968         }
969         ast::ExprWhile(ref cond, ref body, _) => {
970             controlflow::trans_while(bcx, expr, &**cond, &**body)
971         }
972         ast::ExprLoop(ref body, _) => {
973             controlflow::trans_loop(bcx, expr, &**body)
974         }
975         ast::ExprAssign(ref dst, ref src) => {
976             let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
977             let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
978
979             if bcx.fcx.type_needs_drop(dst_datum.ty) {
980                 // If there are destructors involved, make sure we
981                 // are copying from an rvalue, since that cannot possible
982                 // alias an lvalue. We are concerned about code like:
983                 //
984                 //   a = a
985                 //
986                 // but also
987                 //
988                 //   a = a.b
989                 //
990                 // where e.g. a : Option<Foo> and a.b :
991                 // Option<Foo>. In that case, freeing `a` before the
992                 // assignment may also free `a.b`!
993                 //
994                 // We could avoid this intermediary with some analysis
995                 // to determine whether `dst` may possibly own `src`.
996                 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
997                 let src_datum = unpack_datum!(
998                     bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
999                 let opt_hint_datum = dst_datum.kind.drop_flag_info.hint_datum(bcx);
1000                 let opt_hint_val = opt_hint_datum.map(|d|d.to_value());
1001
1002                 // 1. Drop the data at the destination, passing the
1003                 //    drop-hint in case the lvalue has already been
1004                 //    dropped or moved.
1005                 bcx = glue::drop_ty_core(bcx,
1006                                          dst_datum.val,
1007                                          dst_datum.ty,
1008                                          expr.debug_loc(),
1009                                          false,
1010                                          opt_hint_val);
1011
1012                 // 2. We are overwriting the destination; ensure that
1013                 //    its drop-hint (if any) says "initialized."
1014                 if let Some(hint_val) = opt_hint_val {
1015                     let hint_llval = hint_val.value();
1016                     let drop_needed = C_u8(bcx.fcx.ccx, adt::DTOR_NEEDED_HINT);
1017                     Store(bcx, drop_needed, hint_llval);
1018                 }
1019                 src_datum.store_to(bcx, dst_datum.val)
1020             } else {
1021                 src_datum.store_to(bcx, dst_datum.val)
1022             }
1023         }
1024         ast::ExprAssignOp(op, ref dst, ref src) => {
1025             trans_assign_op(bcx, expr, op, &**dst, &**src)
1026         }
1027         ast::ExprInlineAsm(ref a) => {
1028             asm::trans_inline_asm(bcx, a)
1029         }
1030         _ => {
1031             bcx.tcx().sess.span_bug(
1032                 expr.span,
1033                 &format!("trans_rvalue_stmt_unadjusted reached \
1034                          fall-through case: {:?}",
1035                         expr.node));
1036         }
1037     }
1038 }
1039
1040 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1041                                            expr: &ast::Expr,
1042                                            dest: Dest)
1043                                            -> Block<'blk, 'tcx> {
1044     let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
1045     let mut bcx = bcx;
1046     let tcx = bcx.tcx();
1047
1048     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1049
1050     match expr.node {
1051         ast::ExprParen(ref e) => {
1052             trans_into(bcx, &**e, dest)
1053         }
1054         ast::ExprPath(..) => {
1055             trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1056         }
1057         ast::ExprIf(ref cond, ref thn, ref els) => {
1058             controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1059         }
1060         ast::ExprMatch(ref discr, ref arms, _) => {
1061             _match::trans_match(bcx, expr, &**discr, &arms[..], dest)
1062         }
1063         ast::ExprBlock(ref blk) => {
1064             controlflow::trans_block(bcx, &**blk, dest)
1065         }
1066         ast::ExprStruct(_, ref fields, ref base) => {
1067             trans_struct(bcx,
1068                          &fields[..],
1069                          base.as_ref().map(|e| &**e),
1070                          expr.span,
1071                          expr.id,
1072                          node_id_type(bcx, expr.id),
1073                          dest)
1074         }
1075         ast::ExprRange(ref start, ref end) => {
1076             // FIXME it is just not right that we are synthesising ast nodes in
1077             // trans. Shudder.
1078             fn make_field(field_name: &str, expr: P<ast::Expr>) -> ast::Field {
1079                 ast::Field {
1080                     ident: codemap::dummy_spanned(token::str_to_ident(field_name)),
1081                     expr: expr,
1082                     span: codemap::DUMMY_SP,
1083                 }
1084             }
1085
1086             // A range just desugars into a struct.
1087             // Note that the type of the start and end may not be the same, but
1088             // they should only differ in their lifetime, which should not matter
1089             // in trans.
1090             let (did, fields, ty_params) = match (start, end) {
1091                 (&Some(ref start), &Some(ref end)) => {
1092                     // Desugar to Range
1093                     let fields = vec![make_field("start", start.clone()),
1094                                       make_field("end", end.clone())];
1095                     (tcx.lang_items.range_struct(), fields, vec![node_id_type(bcx, start.id)])
1096                 }
1097                 (&Some(ref start), &None) => {
1098                     // Desugar to RangeFrom
1099                     let fields = vec![make_field("start", start.clone())];
1100                     (tcx.lang_items.range_from_struct(), fields, vec![node_id_type(bcx, start.id)])
1101                 }
1102                 (&None, &Some(ref end)) => {
1103                     // Desugar to RangeTo
1104                     let fields = vec![make_field("end", end.clone())];
1105                     (tcx.lang_items.range_to_struct(), fields, vec![node_id_type(bcx, end.id)])
1106                 }
1107                 _ => {
1108                     // Desugar to RangeFull
1109                     (tcx.lang_items.range_full_struct(), vec![], vec![])
1110                 }
1111             };
1112
1113             if let Some(did) = did {
1114                 let substs = Substs::new_type(ty_params, vec![]);
1115                 trans_struct(bcx,
1116                              &fields,
1117                              None,
1118                              expr.span,
1119                              expr.id,
1120                              tcx.mk_struct(tcx.lookup_adt_def(did),
1121                                            tcx.mk_substs(substs)),
1122                              dest)
1123             } else {
1124                 tcx.sess.span_bug(expr.span,
1125                                   "No lang item for ranges (how did we get this far?)")
1126             }
1127         }
1128         ast::ExprTup(ref args) => {
1129             let numbered_fields: Vec<(usize, &ast::Expr)> =
1130                 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1131             trans_adt(bcx,
1132                       expr_ty(bcx, expr),
1133                       0,
1134                       &numbered_fields[..],
1135                       None,
1136                       dest,
1137                       expr.debug_loc())
1138         }
1139         ast::ExprLit(ref lit) => {
1140             match lit.node {
1141                 ast::LitStr(ref s, _) => {
1142                     tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1143                 }
1144                 _ => {
1145                     bcx.tcx()
1146                        .sess
1147                        .span_bug(expr.span,
1148                                  "trans_rvalue_dps_unadjusted shouldn't be \
1149                                   translating this type of literal")
1150                 }
1151             }
1152         }
1153         ast::ExprVec(..) | ast::ExprRepeat(..) => {
1154             tvec::trans_fixed_vstore(bcx, expr, dest)
1155         }
1156         ast::ExprClosure(_, ref decl, ref body) => {
1157             let dest = match dest {
1158                 SaveIn(lldest) => closure::Dest::SaveIn(bcx, lldest),
1159                 Ignore => closure::Dest::Ignore(bcx.ccx())
1160             };
1161             let substs = match expr_ty(bcx, expr).sty {
1162                 ty::TyClosure(_, ref substs) => substs,
1163                 ref t =>
1164                     bcx.tcx().sess.span_bug(
1165                         expr.span,
1166                         &format!("closure expr without closure type: {:?}", t)),
1167             };
1168             closure::trans_closure_expr(dest, decl, body, expr.id, substs).unwrap_or(bcx)
1169         }
1170         ast::ExprCall(ref f, ref args) => {
1171             if bcx.tcx().is_method_call(expr.id) {
1172                 trans_overloaded_call(bcx,
1173                                       expr,
1174                                       &**f,
1175                                       &args[..],
1176                                       Some(dest))
1177             } else {
1178                 callee::trans_call(bcx,
1179                                    expr,
1180                                    &**f,
1181                                    callee::ArgExprs(&args[..]),
1182                                    dest)
1183             }
1184         }
1185         ast::ExprMethodCall(_, _, ref args) => {
1186             callee::trans_method_call(bcx,
1187                                       expr,
1188                                       &*args[0],
1189                                       callee::ArgExprs(&args[..]),
1190                                       dest)
1191         }
1192         ast::ExprBinary(op, ref lhs, ref rhs) => {
1193             // if not overloaded, would be RvalueDatumExpr
1194             let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1195             let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1196             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1197                                 Some((rhs_datum, rhs.id)), Some(dest),
1198                                 !ast_util::is_by_value_binop(op.node)).bcx
1199         }
1200         ast::ExprUnary(op, ref subexpr) => {
1201             // if not overloaded, would be RvalueDatumExpr
1202             let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1203             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1204                                 arg, None, Some(dest), !ast_util::is_by_value_unop(op)).bcx
1205         }
1206         ast::ExprIndex(ref base, ref idx) => {
1207             // if not overloaded, would be RvalueDatumExpr
1208             let base = unpack_datum!(bcx, trans(bcx, &**base));
1209             let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1210             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1211                                 Some((idx_datum, idx.id)), Some(dest), true).bcx
1212         }
1213         ast::ExprCast(..) => {
1214             // Trait casts used to come this way, now they should be coercions.
1215             bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
1216         }
1217         ast::ExprAssignOp(op, ref dst, ref src) => {
1218             trans_assign_op(bcx, expr, op, &**dst, &**src)
1219         }
1220         _ => {
1221             bcx.tcx().sess.span_bug(
1222                 expr.span,
1223                 &format!("trans_rvalue_dps_unadjusted reached fall-through \
1224                          case: {:?}",
1225                         expr.node));
1226         }
1227     }
1228 }
1229
1230 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1231                                         ref_expr: &ast::Expr,
1232                                         def: def::Def,
1233                                         dest: Dest)
1234                                         -> Block<'blk, 'tcx> {
1235     let _icx = push_ctxt("trans_def_dps_unadjusted");
1236
1237     let lldest = match dest {
1238         SaveIn(lldest) => lldest,
1239         Ignore => { return bcx; }
1240     };
1241
1242     match def {
1243         def::DefVariant(tid, vid, _) => {
1244             let variant = bcx.tcx().lookup_adt_def(tid).variant_with_id(vid);
1245             if let ty::VariantKind::Tuple = variant.kind() {
1246                 // N-ary variant.
1247                 let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
1248                                                 ExprId(ref_expr.id),
1249                                                 bcx.fcx.param_substs).val;
1250                 Store(bcx, llfn, lldest);
1251                 return bcx;
1252             } else {
1253                 // Nullary variant.
1254                 let ty = expr_ty(bcx, ref_expr);
1255                 let repr = adt::represent_type(bcx.ccx(), ty);
1256                 adt::trans_set_discr(bcx, &*repr, lldest, variant.disr_val);
1257                 return bcx;
1258             }
1259         }
1260         def::DefStruct(_) => {
1261             let ty = expr_ty(bcx, ref_expr);
1262             match ty.sty {
1263                 ty::TyStruct(def, _) if def.has_dtor() => {
1264                     let repr = adt::represent_type(bcx.ccx(), ty);
1265                     adt::trans_set_discr(bcx, &*repr, lldest, 0);
1266                 }
1267                 _ => {}
1268             }
1269             bcx
1270         }
1271         _ => {
1272             bcx.tcx().sess.span_bug(ref_expr.span, &format!(
1273                 "Non-DPS def {:?} referened by {}",
1274                 def, bcx.node_id_to_string(ref_expr.id)));
1275         }
1276     }
1277 }
1278
1279 pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1280                                          ref_expr: &ast::Expr,
1281                                          def: def::Def,
1282                                          param_substs: &'tcx Substs<'tcx>)
1283                                          -> Datum<'tcx, Rvalue> {
1284     let _icx = push_ctxt("trans_def_datum_unadjusted");
1285
1286     match def {
1287         def::DefFn(did, _) |
1288         def::DefStruct(did) | def::DefVariant(_, did, _) => {
1289             callee::trans_fn_ref(ccx, did, ExprId(ref_expr.id), param_substs)
1290         }
1291         def::DefMethod(method_did) => {
1292             match ccx.tcx().impl_or_trait_item(method_did).container() {
1293                 ty::ImplContainer(_) => {
1294                     callee::trans_fn_ref(ccx, method_did,
1295                                          ExprId(ref_expr.id),
1296                                          param_substs)
1297                 }
1298                 ty::TraitContainer(trait_did) => {
1299                     meth::trans_static_method_callee(ccx, method_did,
1300                                                      trait_did, ref_expr.id,
1301                                                      param_substs)
1302                 }
1303             }
1304         }
1305         _ => {
1306             ccx.tcx().sess.span_bug(ref_expr.span, &format!(
1307                     "trans_def_fn_unadjusted invoked on: {:?} for {:?}",
1308                     def,
1309                     ref_expr));
1310         }
1311     }
1312 }
1313
1314 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1315 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1316                                    def: def::Def)
1317                                    -> Datum<'tcx, Lvalue> {
1318     let _icx = push_ctxt("trans_local_var");
1319
1320     match def {
1321         def::DefUpvar(nid, _) => {
1322             // Can't move upvars, so this is never a ZeroMemLastUse.
1323             let local_ty = node_id_type(bcx, nid);
1324             let lval = Lvalue::new_with_hint("expr::trans_local_var (upvar)",
1325                                              bcx, nid, HintKind::ZeroAndMaintain);
1326             match bcx.fcx.llupvars.borrow().get(&nid) {
1327                 Some(&val) => Datum::new(val, local_ty, lval),
1328                 None => {
1329                     bcx.sess().bug(&format!(
1330                         "trans_local_var: no llval for upvar {} found",
1331                         nid));
1332                 }
1333             }
1334         }
1335         def::DefLocal(nid) => {
1336             let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1337                 Some(&v) => v,
1338                 None => {
1339                     bcx.sess().bug(&format!(
1340                         "trans_local_var: no datum for local/arg {} found",
1341                         nid));
1342                 }
1343             };
1344             debug!("take_local(nid={}, v={}, ty={})",
1345                    nid, bcx.val_to_string(datum.val), datum.ty);
1346             datum
1347         }
1348         _ => {
1349             bcx.sess().unimpl(&format!(
1350                 "unsupported def type in trans_local_var: {:?}",
1351                 def));
1352         }
1353     }
1354 }
1355
1356 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1357                             fields: &[ast::Field],
1358                             base: Option<&ast::Expr>,
1359                             expr_span: codemap::Span,
1360                             expr_id: ast::NodeId,
1361                             ty: Ty<'tcx>,
1362                             dest: Dest) -> Block<'blk, 'tcx> {
1363     let _icx = push_ctxt("trans_rec");
1364
1365     let tcx = bcx.tcx();
1366     let vinfo = VariantInfo::of_node(tcx, ty, expr_id);
1367
1368     let mut need_base = vec![true; vinfo.fields.len()];
1369
1370     let numbered_fields = fields.iter().map(|field| {
1371         let pos = vinfo.field_index(field.ident.node.name);
1372         need_base[pos] = false;
1373         (pos, &*field.expr)
1374     }).collect::<Vec<_>>();
1375
1376     let optbase = match base {
1377         Some(base_expr) => {
1378             let mut leftovers = Vec::new();
1379             for (i, b) in need_base.iter().enumerate() {
1380                 if *b {
1381                     leftovers.push((i, vinfo.fields[i].1));
1382                 }
1383             }
1384             Some(StructBaseInfo {expr: base_expr,
1385                                  fields: leftovers })
1386         }
1387         None => {
1388             if need_base.iter().any(|b| *b) {
1389                 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1390             }
1391             None
1392         }
1393     };
1394
1395     trans_adt(bcx,
1396               ty,
1397               vinfo.discr,
1398               &numbered_fields,
1399               optbase,
1400               dest,
1401               DebugLoc::At(expr_id, expr_span))
1402 }
1403
1404 /// Information that `trans_adt` needs in order to fill in the fields
1405 /// of a struct copied from a base struct (e.g., from an expression
1406 /// like `Foo { a: b, ..base }`.
1407 ///
1408 /// Note that `fields` may be empty; the base expression must always be
1409 /// evaluated for side-effects.
1410 pub struct StructBaseInfo<'a, 'tcx> {
1411     /// The base expression; will be evaluated after all explicit fields.
1412     expr: &'a ast::Expr,
1413     /// The indices of fields to copy paired with their types.
1414     fields: Vec<(usize, Ty<'tcx>)>
1415 }
1416
1417 /// Constructs an ADT instance:
1418 ///
1419 /// - `fields` should be a list of field indices paired with the
1420 /// expression to store into that field.  The initializers will be
1421 /// evaluated in the order specified by `fields`.
1422 ///
1423 /// - `optbase` contains information on the base struct (if any) from
1424 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1425 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1426                                  ty: Ty<'tcx>,
1427                                  discr: ty::Disr,
1428                                  fields: &[(usize, &ast::Expr)],
1429                                  optbase: Option<StructBaseInfo<'a, 'tcx>>,
1430                                  dest: Dest,
1431                                  debug_location: DebugLoc)
1432                                  -> Block<'blk, 'tcx> {
1433     let _icx = push_ctxt("trans_adt");
1434     let fcx = bcx.fcx;
1435     let repr = adt::represent_type(bcx.ccx(), ty);
1436
1437     debug_location.apply(bcx.fcx);
1438
1439     // If we don't care about the result, just make a
1440     // temporary stack slot
1441     let addr = match dest {
1442         SaveIn(pos) => pos,
1443         Ignore => alloc_ty(bcx, ty, "temp"),
1444     };
1445
1446     // This scope holds intermediates that must be cleaned should
1447     // panic occur before the ADT as a whole is ready.
1448     let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1449
1450     if ty.is_simd() {
1451         // Issue 23112: The original logic appeared vulnerable to same
1452         // order-of-eval bug. But, SIMD values are tuple-structs;
1453         // i.e. functional record update (FRU) syntax is unavailable.
1454         //
1455         // To be safe, double-check that we did not get here via FRU.
1456         assert!(optbase.is_none());
1457
1458         // This is the constructor of a SIMD type, such types are
1459         // always primitive machine types and so do not have a
1460         // destructor or require any clean-up.
1461         let llty = type_of::type_of(bcx.ccx(), ty);
1462
1463         // keep a vector as a register, and running through the field
1464         // `insertelement`ing them directly into that register
1465         // (i.e. avoid GEPi and `store`s to an alloca) .
1466         let mut vec_val = C_undef(llty);
1467
1468         for &(i, ref e) in fields {
1469             let block_datum = trans(bcx, &**e);
1470             bcx = block_datum.bcx;
1471             let position = C_uint(bcx.ccx(), i);
1472             let value = block_datum.datum.to_llscalarish(bcx);
1473             vec_val = InsertElement(bcx, vec_val, value, position);
1474         }
1475         Store(bcx, vec_val, addr);
1476     } else if let Some(base) = optbase {
1477         // Issue 23112: If there is a base, then order-of-eval
1478         // requires field expressions eval'ed before base expression.
1479
1480         // First, trans field expressions to temporary scratch values.
1481         let scratch_vals: Vec<_> = fields.iter().map(|&(i, ref e)| {
1482             let datum = unpack_datum!(bcx, trans(bcx, &**e));
1483             (i, datum)
1484         }).collect();
1485
1486         debug_location.apply(bcx.fcx);
1487
1488         // Second, trans the base to the dest.
1489         assert_eq!(discr, 0);
1490
1491         match expr_kind(bcx.tcx(), &*base.expr) {
1492             ExprKind::RvalueDps | ExprKind::RvalueDatum if !bcx.fcx.type_needs_drop(ty) => {
1493                 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1494             },
1495             ExprKind::RvalueStmt => {
1496                 bcx.tcx().sess.bug("unexpected expr kind for struct base expr")
1497             }
1498             _ => {
1499                 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1500                 for &(i, t) in &base.fields {
1501                     let datum = base_datum.get_element(
1502                             bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1503                     assert!(type_is_sized(bcx.tcx(), datum.ty));
1504                     let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1505                     bcx = datum.store_to(bcx, dest);
1506                 }
1507             }
1508         }
1509
1510         // Finally, move scratch field values into actual field locations
1511         for (i, datum) in scratch_vals {
1512             let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1513             bcx = datum.store_to(bcx, dest);
1514         }
1515     } else {
1516         // No base means we can write all fields directly in place.
1517         for &(i, ref e) in fields {
1518             let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1519             let e_ty = expr_ty_adjusted(bcx, &**e);
1520             bcx = trans_into(bcx, &**e, SaveIn(dest));
1521             let scope = cleanup::CustomScope(custom_cleanup_scope);
1522             fcx.schedule_lifetime_end(scope, dest);
1523             // FIXME: nonzeroing move should generalize to fields
1524             fcx.schedule_drop_mem(scope, dest, e_ty, None);
1525         }
1526     }
1527
1528     adt::trans_set_discr(bcx, &*repr, addr, discr);
1529
1530     fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1531
1532     // If we don't care about the result drop the temporary we made
1533     match dest {
1534         SaveIn(_) => bcx,
1535         Ignore => {
1536             bcx = glue::drop_ty(bcx, addr, ty, debug_location);
1537             base::call_lifetime_end(bcx, addr);
1538             bcx
1539         }
1540     }
1541 }
1542
1543
1544 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1545                                    expr: &ast::Expr,
1546                                    lit: &ast::Lit)
1547                                    -> DatumBlock<'blk, 'tcx, Expr> {
1548     // must not be a string constant, that is a RvalueDpsExpr
1549     let _icx = push_ctxt("trans_immediate_lit");
1550     let ty = expr_ty(bcx, expr);
1551     let v = consts::const_lit(bcx.ccx(), expr, lit);
1552     immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1553 }
1554
1555 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1556                            expr: &ast::Expr,
1557                            op: ast::UnOp,
1558                            sub_expr: &ast::Expr)
1559                            -> DatumBlock<'blk, 'tcx, Expr> {
1560     let ccx = bcx.ccx();
1561     let mut bcx = bcx;
1562     let _icx = push_ctxt("trans_unary_datum");
1563
1564     let method_call = MethodCall::expr(expr.id);
1565
1566     // The only overloaded operator that is translated to a datum
1567     // is an overloaded deref, since it is always yields a `&T`.
1568     // Otherwise, we should be in the RvalueDpsExpr path.
1569     assert!(op == ast::UnDeref || !ccx.tcx().is_method_call(expr.id));
1570
1571     let un_ty = expr_ty(bcx, expr);
1572
1573     let debug_loc = expr.debug_loc();
1574
1575     match op {
1576         ast::UnNot => {
1577             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1578             let llresult = Not(bcx, datum.to_llscalarish(bcx), debug_loc);
1579             immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1580         }
1581         ast::UnNeg => {
1582             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1583             let val = datum.to_llscalarish(bcx);
1584             let (bcx, llneg) = {
1585                 if un_ty.is_fp() {
1586                     let result = FNeg(bcx, val, debug_loc);
1587                     (bcx, result)
1588                 } else {
1589                     let is_signed = un_ty.is_signed();
1590                     let result = Neg(bcx, val, debug_loc);
1591                     let bcx = if bcx.ccx().check_overflow() && is_signed {
1592                         let (llty, min) = base::llty_and_min_for_signed_ty(bcx, un_ty);
1593                         let is_min = ICmp(bcx, llvm::IntEQ, val,
1594                                           C_integral(llty, min, true), debug_loc);
1595                         with_cond(bcx, is_min, |bcx| {
1596                             let msg = InternedString::new(
1597                                 "attempted to negate with overflow");
1598                             controlflow::trans_fail(bcx, expr_info(expr), msg)
1599                         })
1600                     } else {
1601                         bcx
1602                     };
1603                     (bcx, result)
1604                 }
1605             };
1606             immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1607         }
1608         ast::UnUniq => {
1609             trans_uniq_expr(bcx, expr, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1610         }
1611         ast::UnDeref => {
1612             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1613             deref_once(bcx, expr, datum, method_call)
1614         }
1615     }
1616 }
1617
1618 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1619                                box_expr: &ast::Expr,
1620                                box_ty: Ty<'tcx>,
1621                                contents: &ast::Expr,
1622                                contents_ty: Ty<'tcx>)
1623                                -> DatumBlock<'blk, 'tcx, Expr> {
1624     let _icx = push_ctxt("trans_uniq_expr");
1625     let fcx = bcx.fcx;
1626     assert!(type_is_sized(bcx.tcx(), contents_ty));
1627     let llty = type_of::type_of(bcx.ccx(), contents_ty);
1628     let size = llsize_of(bcx.ccx(), llty);
1629     let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1630     let llty_ptr = llty.ptr_to();
1631     let Result { bcx, val } = malloc_raw_dyn(bcx,
1632                                              llty_ptr,
1633                                              box_ty,
1634                                              size,
1635                                              align,
1636                                              box_expr.debug_loc());
1637     // Unique boxes do not allocate for zero-size types. The standard library
1638     // may assume that `free` is never called on the pointer returned for
1639     // `Box<ZeroSizeType>`.
1640     let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1641         trans_into(bcx, contents, SaveIn(val))
1642     } else {
1643         let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1644         fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1645                                 val, cleanup::HeapExchange, contents_ty);
1646         let bcx = trans_into(bcx, contents, SaveIn(val));
1647         fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1648         bcx
1649     };
1650     immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1651 }
1652
1653 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1654                            lval: Datum<'tcx, Lvalue>)
1655                            -> DatumBlock<'blk, 'tcx, Expr> {
1656     let dest_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), lval.ty);
1657     let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
1658     memcpy_ty(bcx, scratch.val, lval.val, scratch.ty);
1659
1660     DatumBlock::new(bcx, scratch.to_expr_datum())
1661 }
1662
1663 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1664                              expr: &ast::Expr,
1665                              subexpr: &ast::Expr)
1666                              -> DatumBlock<'blk, 'tcx, Expr> {
1667     let _icx = push_ctxt("trans_addr_of");
1668     let mut bcx = bcx;
1669     let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1670     if !type_is_sized(bcx.tcx(), sub_datum.ty) {
1671         // DST lvalue, close to a fat pointer
1672         ref_fat_ptr(bcx, sub_datum)
1673     } else {
1674         // Sized value, ref to a thin pointer
1675         let ty = expr_ty(bcx, expr);
1676         immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1677     }
1678 }
1679
1680 // Important to get types for both lhs and rhs, because one might be _|_
1681 // and the other not.
1682 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1683                                  binop_expr: &ast::Expr,
1684                                  binop_ty: Ty<'tcx>,
1685                                  op: ast::BinOp,
1686                                  lhs_t: Ty<'tcx>,
1687                                  lhs: ValueRef,
1688                                  rhs_t: Ty<'tcx>,
1689                                  rhs: ValueRef)
1690                                  -> DatumBlock<'blk, 'tcx, Expr> {
1691     let _icx = push_ctxt("trans_eager_binop");
1692
1693     let tcx = bcx.tcx();
1694     let is_simd = lhs_t.is_simd();
1695     let intype = if is_simd {
1696         lhs_t.simd_type(tcx)
1697     } else {
1698         lhs_t
1699     };
1700     let is_float = intype.is_fp();
1701     let is_signed = intype.is_signed();
1702     let info = expr_info(binop_expr);
1703
1704     let binop_debug_loc = binop_expr.debug_loc();
1705
1706     let mut bcx = bcx;
1707     let val = match op.node {
1708       ast::BiAdd => {
1709         if is_float {
1710             FAdd(bcx, lhs, rhs, binop_debug_loc)
1711         } else if is_simd {
1712             Add(bcx, lhs, rhs, binop_debug_loc)
1713         } else {
1714             let (newbcx, res) = with_overflow_check(
1715                 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1716             bcx = newbcx;
1717             res
1718         }
1719       }
1720       ast::BiSub => {
1721         if is_float {
1722             FSub(bcx, lhs, rhs, binop_debug_loc)
1723         } else if is_simd {
1724             Sub(bcx, lhs, rhs, binop_debug_loc)
1725         } else {
1726             let (newbcx, res) = with_overflow_check(
1727                 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1728             bcx = newbcx;
1729             res
1730         }
1731       }
1732       ast::BiMul => {
1733         if is_float {
1734             FMul(bcx, lhs, rhs, binop_debug_loc)
1735         } else if is_simd {
1736             Mul(bcx, lhs, rhs, binop_debug_loc)
1737         } else {
1738             let (newbcx, res) = with_overflow_check(
1739                 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1740             bcx = newbcx;
1741             res
1742         }
1743       }
1744       ast::BiDiv => {
1745         if is_float {
1746             FDiv(bcx, lhs, rhs, binop_debug_loc)
1747         } else {
1748             // Only zero-check integers; fp /0 is NaN
1749             bcx = base::fail_if_zero_or_overflows(bcx,
1750                                                   expr_info(binop_expr),
1751                                                   op,
1752                                                   lhs,
1753                                                   rhs,
1754                                                   rhs_t);
1755             if is_signed {
1756                 SDiv(bcx, lhs, rhs, binop_debug_loc)
1757             } else {
1758                 UDiv(bcx, lhs, rhs, binop_debug_loc)
1759             }
1760         }
1761       }
1762       ast::BiRem => {
1763         if is_float {
1764             // LLVM currently always lowers the `frem` instructions appropriate
1765             // library calls typically found in libm. Notably f64 gets wired up
1766             // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
1767             // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
1768             // instead just an inline function in a header that goes up to a
1769             // f64, uses `fmod`, and then comes back down to a f32.
1770             //
1771             // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
1772             // still unconditionally lower frem instructions over 32-bit floats
1773             // to a call to `fmodf`. To work around this we special case MSVC
1774             // 32-bit float rem instructions and instead do the call out to
1775             // `fmod` ourselves.
1776             //
1777             // Note that this is currently duplicated with src/libcore/ops.rs
1778             // which does the same thing, and it would be nice to perhaps unify
1779             // these two implementations on day! Also note that we call `fmod`
1780             // for both 32 and 64-bit floats because if we emit any FRem
1781             // instruction at all then LLVM is capable of optimizing it into a
1782             // 32-bit FRem (which we're trying to avoid).
1783             let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
1784                            tcx.sess.target.target.arch == "x86";
1785             if use_fmod {
1786                 let f64t = Type::f64(bcx.ccx());
1787                 let fty = Type::func(&[f64t, f64t], &f64t);
1788                 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty,
1789                                                 tcx.types.f64);
1790                 if lhs_t == tcx.types.f32 {
1791                     let lhs = FPExt(bcx, lhs, f64t);
1792                     let rhs = FPExt(bcx, rhs, f64t);
1793                     let res = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
1794                     FPTrunc(bcx, res, Type::f32(bcx.ccx()))
1795                 } else {
1796                     Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc)
1797                 }
1798             } else {
1799                 FRem(bcx, lhs, rhs, binop_debug_loc)
1800             }
1801         } else {
1802             // Only zero-check integers; fp %0 is NaN
1803             bcx = base::fail_if_zero_or_overflows(bcx,
1804                                                   expr_info(binop_expr),
1805                                                   op, lhs, rhs, rhs_t);
1806             if is_signed {
1807                 SRem(bcx, lhs, rhs, binop_debug_loc)
1808             } else {
1809                 URem(bcx, lhs, rhs, binop_debug_loc)
1810             }
1811         }
1812       }
1813       ast::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1814       ast::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1815       ast::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1816       ast::BiShl => {
1817           let (newbcx, res) = with_overflow_check(
1818               bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1819           bcx = newbcx;
1820           res
1821       }
1822       ast::BiShr => {
1823           let (newbcx, res) = with_overflow_check(
1824               bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1825           bcx = newbcx;
1826           res
1827       }
1828       ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1829         if is_simd {
1830             base::compare_simd_types(bcx, lhs, rhs, intype, val_ty(lhs), op.node, binop_debug_loc)
1831         } else {
1832             base::compare_scalar_types(bcx, lhs, rhs, intype, op.node, binop_debug_loc)
1833         }
1834       }
1835       _ => {
1836         bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1837       }
1838     };
1839
1840     immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1841 }
1842
1843 // refinement types would obviate the need for this
1844 enum lazy_binop_ty {
1845     lazy_and,
1846     lazy_or,
1847 }
1848
1849 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1850                                 binop_expr: &ast::Expr,
1851                                 op: lazy_binop_ty,
1852                                 a: &ast::Expr,
1853                                 b: &ast::Expr)
1854                                 -> DatumBlock<'blk, 'tcx, Expr> {
1855     let _icx = push_ctxt("trans_lazy_binop");
1856     let binop_ty = expr_ty(bcx, binop_expr);
1857     let fcx = bcx.fcx;
1858
1859     let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1860     let lhs = lhs.to_llscalarish(past_lhs);
1861
1862     if past_lhs.unreachable.get() {
1863         return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1864     }
1865
1866     let join = fcx.new_id_block("join", binop_expr.id);
1867     let before_rhs = fcx.new_id_block("before_rhs", b.id);
1868
1869     match op {
1870       lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1871       lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1872     }
1873
1874     let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1875     let rhs = rhs.to_llscalarish(past_rhs);
1876
1877     if past_rhs.unreachable.get() {
1878         return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1879     }
1880
1881     Br(past_rhs, join.llbb, DebugLoc::None);
1882     let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1883                   &[past_lhs.llbb, past_rhs.llbb]);
1884
1885     return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1886 }
1887
1888 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1889                             expr: &ast::Expr,
1890                             op: ast::BinOp,
1891                             lhs: &ast::Expr,
1892                             rhs: &ast::Expr)
1893                             -> DatumBlock<'blk, 'tcx, Expr> {
1894     let _icx = push_ctxt("trans_binary");
1895     let ccx = bcx.ccx();
1896
1897     // if overloaded, would be RvalueDpsExpr
1898     assert!(!ccx.tcx().is_method_call(expr.id));
1899
1900     match op.node {
1901         ast::BiAnd => {
1902             trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1903         }
1904         ast::BiOr => {
1905             trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1906         }
1907         _ => {
1908             let mut bcx = bcx;
1909             let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1910             let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1911             let binop_ty = expr_ty(bcx, expr);
1912
1913             debug!("trans_binary (expr {}): lhs_datum={}",
1914                    expr.id,
1915                    lhs_datum.to_string(ccx));
1916             let lhs_ty = lhs_datum.ty;
1917             let lhs = lhs_datum.to_llscalarish(bcx);
1918
1919             debug!("trans_binary (expr {}): rhs_datum={}",
1920                    expr.id,
1921                    rhs_datum.to_string(ccx));
1922             let rhs_ty = rhs_datum.ty;
1923             let rhs = rhs_datum.to_llscalarish(bcx);
1924             trans_eager_binop(bcx, expr, binop_ty, op,
1925                               lhs_ty, lhs, rhs_ty, rhs)
1926         }
1927     }
1928 }
1929
1930 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1931                                    expr: &ast::Expr,
1932                                    method_call: MethodCall,
1933                                    lhs: Datum<'tcx, Expr>,
1934                                    rhs: Option<(Datum<'tcx, Expr>, ast::NodeId)>,
1935                                    dest: Option<Dest>,
1936                                    autoref: bool)
1937                                    -> Result<'blk, 'tcx> {
1938     callee::trans_call_inner(bcx,
1939                              expr.debug_loc(),
1940                              |bcx, arg_cleanup_scope| {
1941                                 meth::trans_method_callee(bcx,
1942                                                           method_call,
1943                                                           None,
1944                                                           arg_cleanup_scope)
1945                              },
1946                              callee::ArgOverloadedOp(lhs, rhs, autoref),
1947                              dest)
1948 }
1949
1950 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1951                                          expr: &ast::Expr,
1952                                          callee: &'a ast::Expr,
1953                                          args: &'a [P<ast::Expr>],
1954                                          dest: Option<Dest>)
1955                                          -> Block<'blk, 'tcx> {
1956     debug!("trans_overloaded_call {}", expr.id);
1957     let method_call = MethodCall::expr(expr.id);
1958     let mut all_args = vec!(callee);
1959     all_args.extend(args.iter().map(|e| &**e));
1960     unpack_result!(bcx,
1961                    callee::trans_call_inner(bcx,
1962                                             expr.debug_loc(),
1963                                             |bcx, arg_cleanup_scope| {
1964                                                 meth::trans_method_callee(
1965                                                     bcx,
1966                                                     method_call,
1967                                                     None,
1968                                                     arg_cleanup_scope)
1969                                             },
1970                                             callee::ArgOverloadedCall(all_args),
1971                                             dest));
1972     bcx
1973 }
1974
1975 pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
1976                           expr: &ast::Expr,
1977                           t_in: Ty<'tcx>,
1978                           t_out: Ty<'tcx>)
1979                           -> bool {
1980     if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
1981         return true;
1982     }
1983
1984     match (t_in.builtin_deref(true), t_out.builtin_deref(true)) {
1985         (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
1986             t_in == t_out
1987         }
1988         _ => {
1989             // This condition isn't redundant with the check for CoercionCast:
1990             // different types can be substituted into the same type, and
1991             // == equality can be overconservative if there are regions.
1992             t_in == t_out
1993         }
1994     }
1995 }
1996
1997 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1998                               expr: &ast::Expr,
1999                               id: ast::NodeId)
2000                               -> DatumBlock<'blk, 'tcx, Expr>
2001 {
2002     use middle::cast::CastTy::*;
2003     use middle::cast::IntTy::*;
2004
2005     fn int_cast(bcx: Block,
2006                 lldsttype: Type,
2007                 llsrctype: Type,
2008                 llsrc: ValueRef,
2009                 signed: bool)
2010                 -> ValueRef
2011     {
2012         let _icx = push_ctxt("int_cast");
2013         let srcsz = llsrctype.int_width();
2014         let dstsz = lldsttype.int_width();
2015         return if dstsz == srcsz {
2016             BitCast(bcx, llsrc, lldsttype)
2017         } else if srcsz > dstsz {
2018             TruncOrBitCast(bcx, llsrc, lldsttype)
2019         } else if signed {
2020             SExtOrBitCast(bcx, llsrc, lldsttype)
2021         } else {
2022             ZExtOrBitCast(bcx, llsrc, lldsttype)
2023         }
2024     }
2025
2026     fn float_cast(bcx: Block,
2027                   lldsttype: Type,
2028                   llsrctype: Type,
2029                   llsrc: ValueRef)
2030                   -> ValueRef
2031     {
2032         let _icx = push_ctxt("float_cast");
2033         let srcsz = llsrctype.float_width();
2034         let dstsz = lldsttype.float_width();
2035         return if dstsz > srcsz {
2036             FPExt(bcx, llsrc, lldsttype)
2037         } else if srcsz > dstsz {
2038             FPTrunc(bcx, llsrc, lldsttype)
2039         } else { llsrc };
2040     }
2041
2042     let _icx = push_ctxt("trans_cast");
2043     let mut bcx = bcx;
2044     let ccx = bcx.ccx();
2045
2046     let t_in = expr_ty_adjusted(bcx, expr);
2047     let t_out = node_id_type(bcx, id);
2048
2049     debug!("trans_cast({:?} as {:?})", t_in, t_out);
2050     let mut ll_t_in = type_of::arg_type_of(ccx, t_in);
2051     let ll_t_out = type_of::arg_type_of(ccx, t_out);
2052     // Convert the value to be cast into a ValueRef, either by-ref or
2053     // by-value as appropriate given its type:
2054     let mut datum = unpack_datum!(bcx, trans(bcx, expr));
2055
2056     let datum_ty = monomorphize_type(bcx, datum.ty);
2057
2058     if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
2059         datum.ty = t_out;
2060         return DatumBlock::new(bcx, datum);
2061     }
2062
2063     if type_is_fat_ptr(bcx.tcx(), t_in) {
2064         assert!(datum.kind.is_by_ref());
2065         if type_is_fat_ptr(bcx.tcx(), t_out) {
2066             return DatumBlock::new(bcx, Datum::new(
2067                 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
2068                 t_out,
2069                 Rvalue::new(ByRef)
2070             )).to_expr_datumblock();
2071         } else {
2072             // Return the address
2073             return immediate_rvalue_bcx(bcx,
2074                                         PointerCast(bcx,
2075                                                     Load(bcx, get_dataptr(bcx, datum.val)),
2076                                                     ll_t_out),
2077                                         t_out).to_expr_datumblock();
2078         }
2079     }
2080
2081     let r_t_in = CastTy::from_ty(t_in).expect("bad input type for cast");
2082     let r_t_out = CastTy::from_ty(t_out).expect("bad output type for cast");
2083
2084     let (llexpr, signed) = if let Int(CEnum) = r_t_in {
2085         let repr = adt::represent_type(ccx, t_in);
2086         let datum = unpack_datum!(
2087             bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2088         let llexpr_ptr = datum.to_llref();
2089         let discr = adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2090         ll_t_in = val_ty(discr);
2091         (discr, adt::is_discr_signed(&*repr))
2092     } else {
2093         (datum.to_llscalarish(bcx), t_in.is_signed())
2094     };
2095
2096     let newval = match (r_t_in, r_t_out) {
2097         (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
2098             PointerCast(bcx, llexpr, ll_t_out)
2099         }
2100         (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
2101         (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
2102
2103         (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
2104         (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
2105         (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
2106         (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
2107         (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
2108         (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
2109
2110         _ => ccx.sess().span_bug(expr.span,
2111                                   &format!("translating unsupported cast: \
2112                                             {:?} -> {:?}",
2113                                            t_in,
2114                                            t_out)
2115                                  )
2116     };
2117     return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2118 }
2119
2120 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2121                                expr: &ast::Expr,
2122                                op: ast::BinOp,
2123                                dst: &ast::Expr,
2124                                src: &ast::Expr)
2125                                -> Block<'blk, 'tcx> {
2126     let _icx = push_ctxt("trans_assign_op");
2127     let mut bcx = bcx;
2128
2129     debug!("trans_assign_op(expr={:?})", expr);
2130
2131     // User-defined operator methods cannot be used with `+=` etc right now
2132     assert!(!bcx.tcx().is_method_call(expr.id));
2133
2134     // Evaluate LHS (destination), which should be an lvalue
2135     let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2136     assert!(!bcx.fcx.type_needs_drop(dst_datum.ty));
2137     let dst_ty = dst_datum.ty;
2138     let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2139
2140     // Evaluate RHS
2141     let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2142     let rhs_ty = rhs_datum.ty;
2143     let rhs = rhs_datum.to_llscalarish(bcx);
2144
2145     // Perform computation and store the result
2146     let result_datum = unpack_datum!(
2147         bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2148                                dst_ty, dst, rhs_ty, rhs));
2149     return result_datum.store_to(bcx, dst_datum.val);
2150 }
2151
2152 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2153                         datum: Datum<'tcx, Expr>,
2154                         expr: &ast::Expr)
2155                         -> DatumBlock<'blk, 'tcx, Expr> {
2156     let mut bcx = bcx;
2157
2158     // Ensure cleanup of `datum` if not already scheduled and obtain
2159     // a "by ref" pointer.
2160     let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2161
2162     // Compute final type. Note that we are loose with the region and
2163     // mutability, since those things don't matter in trans.
2164     let referent_ty = lv_datum.ty;
2165     let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2166
2167     // Get the pointer.
2168     let llref = lv_datum.to_llref();
2169
2170     // Construct the resulting datum, using what was the "by ref"
2171     // ValueRef of type `referent_ty` to be the "by value" ValueRef
2172     // of type `&referent_ty`.
2173     // Pointers to DST types are non-immediate, and therefore still use ByRef.
2174     let kind  = if type_is_sized(bcx.tcx(), referent_ty) { ByValue } else { ByRef };
2175     DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(kind))))
2176 }
2177
2178 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2179                               expr: &ast::Expr,
2180                               datum: Datum<'tcx, Expr>,
2181                               times: usize)
2182                               -> DatumBlock<'blk, 'tcx, Expr> {
2183     let mut bcx = bcx;
2184     let mut datum = datum;
2185     for i in 0..times {
2186         let method_call = MethodCall::autoderef(expr.id, i as u32);
2187         datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2188     }
2189     DatumBlock { bcx: bcx, datum: datum }
2190 }
2191
2192 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2193                           expr: &ast::Expr,
2194                           datum: Datum<'tcx, Expr>,
2195                           method_call: MethodCall)
2196                           -> DatumBlock<'blk, 'tcx, Expr> {
2197     let ccx = bcx.ccx();
2198
2199     debug!("deref_once(expr={:?}, datum={}, method_call={:?})",
2200            expr,
2201            datum.to_string(ccx),
2202            method_call);
2203
2204     let mut bcx = bcx;
2205
2206     // Check for overloaded deref.
2207     let method_ty = ccx.tcx()
2208                        .tables
2209                        .borrow()
2210                        .method_map
2211                        .get(&method_call).map(|method| method.ty);
2212
2213     let datum = match method_ty {
2214         Some(method_ty) => {
2215             let method_ty = monomorphize_type(bcx, method_ty);
2216
2217             // Overloaded. Evaluate `trans_overloaded_op`, which will
2218             // invoke the user's deref() method, which basically
2219             // converts from the `Smaht<T>` pointer that we have into
2220             // a `&T` pointer.  We can then proceed down the normal
2221             // path (below) to dereference that `&T`.
2222             let datum = if method_call.autoderef == 0 {
2223                 datum
2224             } else {
2225                 // Always perform an AutoPtr when applying an overloaded auto-deref
2226                 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2227             };
2228
2229             let ref_ty = // invoked methods have their LB regions instantiated
2230                 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2231             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2232
2233             unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2234                                                     datum, None, Some(SaveIn(scratch.val)),
2235                                                     false));
2236             scratch.to_expr_datum()
2237         }
2238         None => {
2239             // Not overloaded. We already have a pointer we know how to deref.
2240             datum
2241         }
2242     };
2243
2244     let r = match datum.ty.sty {
2245         ty::TyBox(content_ty) => {
2246             // Make sure we have an lvalue datum here to get the
2247             // proper cleanups scheduled
2248             let datum = unpack_datum!(
2249                 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2250
2251             if type_is_sized(bcx.tcx(), content_ty) {
2252                 let ptr = load_ty(bcx, datum.val, datum.ty);
2253                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(datum.kind)))
2254             } else {
2255                 // A fat pointer and a DST lvalue have the same representation
2256                 // just different types. Since there is no temporary for `*e`
2257                 // here (because it is unsized), we cannot emulate the sized
2258                 // object code path for running drop glue and free. Instead,
2259                 // we schedule cleanup for `e`, turning it into an lvalue.
2260
2261                 let lval = Lvalue::new("expr::deref_once ty_uniq");
2262                 let datum = Datum::new(datum.val, content_ty, LvalueExpr(lval));
2263                 DatumBlock::new(bcx, datum)
2264             }
2265         }
2266
2267         ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
2268         ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
2269             let lval = Lvalue::new("expr::deref_once ptr");
2270             if type_is_sized(bcx.tcx(), content_ty) {
2271                 let ptr = datum.to_llscalarish(bcx);
2272
2273                 // Always generate an lvalue datum, even if datum.mode is
2274                 // an rvalue.  This is because datum.mode is only an
2275                 // rvalue for non-owning pointers like &T or *T, in which
2276                 // case cleanup *is* scheduled elsewhere, by the true
2277                 // owner (or, in the case of *T, by the user).
2278                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(lval)))
2279             } else {
2280                 // A fat pointer and a DST lvalue have the same representation
2281                 // just different types.
2282                 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr(lval)))
2283             }
2284         }
2285
2286         _ => {
2287             bcx.tcx().sess.span_bug(
2288                 expr.span,
2289                 &format!("deref invoked on expr of invalid type {:?}",
2290                         datum.ty));
2291         }
2292     };
2293
2294     debug!("deref_once(expr={}, method_call={:?}, result={})",
2295            expr.id, method_call, r.datum.to_string(ccx));
2296
2297     return r;
2298 }
2299
2300 #[derive(Debug)]
2301 enum OverflowOp {
2302     Add,
2303     Sub,
2304     Mul,
2305     Shl,
2306     Shr,
2307 }
2308
2309 impl OverflowOp {
2310     fn codegen_strategy(&self) -> OverflowCodegen {
2311         use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2312         match *self {
2313             OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2314             OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2315             OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2316
2317             OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2318             OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2319         }
2320     }
2321 }
2322
2323 enum OverflowCodegen {
2324     ViaIntrinsic(OverflowOpViaIntrinsic),
2325     ViaInputCheck(OverflowOpViaInputCheck),
2326 }
2327
2328 enum OverflowOpViaInputCheck { Shl, Shr, }
2329
2330 #[derive(Debug)]
2331 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2332
2333 impl OverflowOpViaIntrinsic {
2334     fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2335         let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2336         bcx.ccx().get_intrinsic(&name)
2337     }
2338     fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str {
2339         use syntax::ast::IntTy::*;
2340         use syntax::ast::UintTy::*;
2341         use middle::ty::{TyInt, TyUint};
2342
2343         let new_sty = match ty.sty {
2344             TyInt(TyIs) => match &tcx.sess.target.target.target_pointer_width[..] {
2345                 "32" => TyInt(TyI32),
2346                 "64" => TyInt(TyI64),
2347                 _ => panic!("unsupported target word size")
2348             },
2349             TyUint(TyUs) => match &tcx.sess.target.target.target_pointer_width[..] {
2350                 "32" => TyUint(TyU32),
2351                 "64" => TyUint(TyU64),
2352                 _ => panic!("unsupported target word size")
2353             },
2354             ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2355             _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2356                         *self)
2357         };
2358
2359         match *self {
2360             OverflowOpViaIntrinsic::Add => match new_sty {
2361                 TyInt(TyI8) => "llvm.sadd.with.overflow.i8",
2362                 TyInt(TyI16) => "llvm.sadd.with.overflow.i16",
2363                 TyInt(TyI32) => "llvm.sadd.with.overflow.i32",
2364                 TyInt(TyI64) => "llvm.sadd.with.overflow.i64",
2365
2366                 TyUint(TyU8) => "llvm.uadd.with.overflow.i8",
2367                 TyUint(TyU16) => "llvm.uadd.with.overflow.i16",
2368                 TyUint(TyU32) => "llvm.uadd.with.overflow.i32",
2369                 TyUint(TyU64) => "llvm.uadd.with.overflow.i64",
2370
2371                 _ => unreachable!(),
2372             },
2373             OverflowOpViaIntrinsic::Sub => match new_sty {
2374                 TyInt(TyI8) => "llvm.ssub.with.overflow.i8",
2375                 TyInt(TyI16) => "llvm.ssub.with.overflow.i16",
2376                 TyInt(TyI32) => "llvm.ssub.with.overflow.i32",
2377                 TyInt(TyI64) => "llvm.ssub.with.overflow.i64",
2378
2379                 TyUint(TyU8) => "llvm.usub.with.overflow.i8",
2380                 TyUint(TyU16) => "llvm.usub.with.overflow.i16",
2381                 TyUint(TyU32) => "llvm.usub.with.overflow.i32",
2382                 TyUint(TyU64) => "llvm.usub.with.overflow.i64",
2383
2384                 _ => unreachable!(),
2385             },
2386             OverflowOpViaIntrinsic::Mul => match new_sty {
2387                 TyInt(TyI8) => "llvm.smul.with.overflow.i8",
2388                 TyInt(TyI16) => "llvm.smul.with.overflow.i16",
2389                 TyInt(TyI32) => "llvm.smul.with.overflow.i32",
2390                 TyInt(TyI64) => "llvm.smul.with.overflow.i64",
2391
2392                 TyUint(TyU8) => "llvm.umul.with.overflow.i8",
2393                 TyUint(TyU16) => "llvm.umul.with.overflow.i16",
2394                 TyUint(TyU32) => "llvm.umul.with.overflow.i32",
2395                 TyUint(TyU64) => "llvm.umul.with.overflow.i64",
2396
2397                 _ => unreachable!(),
2398             },
2399         }
2400     }
2401
2402     fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2403                                         info: NodeIdAndSpan,
2404                                         lhs_t: Ty<'tcx>, lhs: ValueRef,
2405                                         rhs: ValueRef,
2406                                         binop_debug_loc: DebugLoc)
2407                                         -> (Block<'blk, 'tcx>, ValueRef) {
2408         let llfn = self.to_intrinsic(bcx, lhs_t);
2409
2410         let val = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
2411         let result = ExtractValue(bcx, val, 0); // iN operation result
2412         let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2413
2414         let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2415                         binop_debug_loc);
2416
2417         let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2418         Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2419              None, binop_debug_loc);
2420
2421         let bcx =
2422             base::with_cond(bcx, cond, |bcx|
2423                 controlflow::trans_fail(bcx, info,
2424                     InternedString::new("arithmetic operation overflowed")));
2425
2426         (bcx, result)
2427     }
2428 }
2429
2430 impl OverflowOpViaInputCheck {
2431     fn build_with_input_check<'blk, 'tcx>(&self,
2432                                           bcx: Block<'blk, 'tcx>,
2433                                           info: NodeIdAndSpan,
2434                                           lhs_t: Ty<'tcx>,
2435                                           lhs: ValueRef,
2436                                           rhs: ValueRef,
2437                                           binop_debug_loc: DebugLoc)
2438                                           -> (Block<'blk, 'tcx>, ValueRef)
2439     {
2440         let lhs_llty = val_ty(lhs);
2441         let rhs_llty = val_ty(rhs);
2442
2443         // Panic if any bits are set outside of bits that we always
2444         // mask in.
2445         //
2446         // Note that the mask's value is derived from the LHS type
2447         // (since that is where the 32/64 distinction is relevant) but
2448         // the mask's type must match the RHS type (since they will
2449         // both be fed into a and-binop)
2450         let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2451
2452         let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2453         let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2454         let result = match *self {
2455             OverflowOpViaInputCheck::Shl =>
2456                 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2457             OverflowOpViaInputCheck::Shr =>
2458                 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2459         };
2460         let bcx =
2461             base::with_cond(bcx, cond, |bcx|
2462                 controlflow::trans_fail(bcx, info,
2463                     InternedString::new("shift operation overflowed")));
2464
2465         (bcx, result)
2466     }
2467 }
2468
2469 fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2470                               llty: Type,
2471                               mask_llty: Type,
2472                               invert: bool) -> ValueRef {
2473     let kind = llty.kind();
2474     match kind {
2475         TypeKind::Integer => {
2476             // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
2477             let val = llty.int_width() - 1;
2478             if invert {
2479                 C_integral(mask_llty, !val, true)
2480             } else {
2481                 C_integral(mask_llty, val, false)
2482             }
2483         },
2484         TypeKind::Vector => {
2485             let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
2486             VectorSplat(bcx, mask_llty.vector_length(), mask)
2487         },
2488         _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
2489     }
2490 }
2491
2492 // Check if an integer or vector contains a nonzero element.
2493 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2494                                    value: ValueRef,
2495                                    binop_debug_loc: DebugLoc) -> ValueRef {
2496     let llty = val_ty(value);
2497     let kind = llty.kind();
2498     match kind {
2499         TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2500         TypeKind::Vector => {
2501             // Check if any elements of the vector are nonzero by treating
2502             // it as a wide integer and checking if the integer is nonzero.
2503             let width = llty.vector_length() as u64 * llty.element_type().int_width();
2504             let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2505             build_nonzero_check(bcx, int_value, binop_debug_loc)
2506         },
2507         _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2508     }
2509 }
2510
2511 // To avoid UB from LLVM, these two functions mask RHS with an
2512 // appropriate mask unconditionally (i.e. the fallback behavior for
2513 // all shifts). For 32- and 64-bit types, this matches the semantics
2514 // of Java. (See related discussion on #1877 and #10183.)
2515
2516 fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2517                                       lhs: ValueRef,
2518                                       rhs: ValueRef,
2519                                       binop_debug_loc: DebugLoc) -> ValueRef {
2520     let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShl, lhs, rhs);
2521     // #1877, #10183: Ensure that input is always valid
2522     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2523     Shl(bcx, lhs, rhs, binop_debug_loc)
2524 }
2525
2526 fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2527                                       lhs_t: Ty<'tcx>,
2528                                       lhs: ValueRef,
2529                                       rhs: ValueRef,
2530                                       binop_debug_loc: DebugLoc) -> ValueRef {
2531     let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShr, lhs, rhs);
2532     // #1877, #10183: Ensure that input is always valid
2533     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2534     let tcx = bcx.tcx();
2535     let is_simd = lhs_t.is_simd();
2536     let intype = if is_simd {
2537         lhs_t.simd_type(tcx)
2538     } else {
2539         lhs_t
2540     };
2541     let is_signed = intype.is_signed();
2542     if is_signed {
2543         AShr(bcx, lhs, rhs, binop_debug_loc)
2544     } else {
2545         LShr(bcx, lhs, rhs, binop_debug_loc)
2546     }
2547 }
2548
2549 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2550                               rhs: ValueRef,
2551                               debug_loc: DebugLoc) -> ValueRef {
2552     let rhs_llty = val_ty(rhs);
2553     And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
2554 }
2555
2556 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2557                                    lhs_t: Ty<'tcx>, lhs: ValueRef,
2558                                    rhs: ValueRef,
2559                                    binop_debug_loc: DebugLoc)
2560                                    -> (Block<'blk, 'tcx>, ValueRef) {
2561     if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2562     if bcx.ccx().check_overflow() {
2563
2564         match oop.codegen_strategy() {
2565             OverflowCodegen::ViaIntrinsic(oop) =>
2566                 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2567             OverflowCodegen::ViaInputCheck(oop) =>
2568                 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2569         }
2570     } else {
2571         let res = match oop {
2572             OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2573             OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2574             OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2575
2576             OverflowOp::Shl =>
2577                 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2578             OverflowOp::Shr =>
2579                 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2580         };
2581         (bcx, res)
2582     }
2583 }
2584
2585 /// We categorize expressions into three kinds.  The distinction between
2586 /// lvalue/rvalue is fundamental to the language.  The distinction between the
2587 /// two kinds of rvalues is an artifact of trans which reflects how we will
2588 /// generate code for that kind of expression.  See trans/expr.rs for more
2589 /// information.
2590 #[derive(Copy, Clone)]
2591 enum ExprKind {
2592     Lvalue,
2593     RvalueDps,
2594     RvalueDatum,
2595     RvalueStmt
2596 }
2597
2598 fn expr_kind(tcx: &ty::ctxt, expr: &ast::Expr) -> ExprKind {
2599     if tcx.is_method_call(expr.id) {
2600         // Overloaded operations are generally calls, and hence they are
2601         // generated via DPS, but there are a few exceptions:
2602         return match expr.node {
2603             // `a += b` has a unit result.
2604             ast::ExprAssignOp(..) => ExprKind::RvalueStmt,
2605
2606             // the deref method invoked for `*a` always yields an `&T`
2607             ast::ExprUnary(ast::UnDeref, _) => ExprKind::Lvalue,
2608
2609             // the index method invoked for `a[i]` always yields an `&T`
2610             ast::ExprIndex(..) => ExprKind::Lvalue,
2611
2612             // in the general case, result could be any type, use DPS
2613             _ => ExprKind::RvalueDps
2614         };
2615     }
2616
2617     match expr.node {
2618         ast::ExprPath(..) => {
2619             match tcx.resolve_expr(expr) {
2620                 def::DefStruct(_) | def::DefVariant(..) => {
2621                     if let ty::TyBareFn(..) = tcx.node_id_to_type(expr.id).sty {
2622                         // ctor function
2623                         ExprKind::RvalueDatum
2624                     } else {
2625                         ExprKind::RvalueDps
2626                     }
2627                 }
2628
2629                 // Special case: A unit like struct's constructor must be called without () at the
2630                 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
2631                 // of unit structs this is should not be interpreted as function pointer but as
2632                 // call to the constructor.
2633                 def::DefFn(_, true) => ExprKind::RvalueDps,
2634
2635                 // Fn pointers are just scalar values.
2636                 def::DefFn(..) | def::DefMethod(..) => ExprKind::RvalueDatum,
2637
2638                 // Note: there is actually a good case to be made that
2639                 // DefArg's, particularly those of immediate type, ought to
2640                 // considered rvalues.
2641                 def::DefStatic(..) |
2642                 def::DefUpvar(..) |
2643                 def::DefLocal(..) => ExprKind::Lvalue,
2644
2645                 def::DefConst(..) |
2646                 def::DefAssociatedConst(..) => ExprKind::RvalueDatum,
2647
2648                 def => {
2649                     tcx.sess.span_bug(
2650                         expr.span,
2651                         &format!("uncategorized def for expr {}: {:?}",
2652                                 expr.id,
2653                                 def));
2654                 }
2655             }
2656         }
2657
2658         ast::ExprUnary(ast::UnDeref, _) |
2659         ast::ExprField(..) |
2660         ast::ExprTupField(..) |
2661         ast::ExprIndex(..) => {
2662             ExprKind::Lvalue
2663         }
2664
2665         ast::ExprCall(..) |
2666         ast::ExprMethodCall(..) |
2667         ast::ExprStruct(..) |
2668         ast::ExprRange(..) |
2669         ast::ExprTup(..) |
2670         ast::ExprIf(..) |
2671         ast::ExprMatch(..) |
2672         ast::ExprClosure(..) |
2673         ast::ExprBlock(..) |
2674         ast::ExprRepeat(..) |
2675         ast::ExprVec(..) => {
2676             ExprKind::RvalueDps
2677         }
2678
2679         ast::ExprIfLet(..) => {
2680             tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
2681         }
2682         ast::ExprWhileLet(..) => {
2683             tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
2684         }
2685
2686         ast::ExprForLoop(..) => {
2687             tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
2688         }
2689
2690         ast::ExprLit(ref lit) if ast_util::lit_is_str(&**lit) => {
2691             ExprKind::RvalueDps
2692         }
2693
2694         ast::ExprBreak(..) |
2695         ast::ExprAgain(..) |
2696         ast::ExprRet(..) |
2697         ast::ExprWhile(..) |
2698         ast::ExprLoop(..) |
2699         ast::ExprAssign(..) |
2700         ast::ExprInlineAsm(..) |
2701         ast::ExprAssignOp(..) => {
2702             ExprKind::RvalueStmt
2703         }
2704
2705         ast::ExprLit(_) | // Note: LitStr is carved out above
2706         ast::ExprUnary(..) |
2707         ast::ExprBox(None, _) |
2708         ast::ExprAddrOf(..) |
2709         ast::ExprBinary(..) |
2710         ast::ExprCast(..) => {
2711             ExprKind::RvalueDatum
2712         }
2713
2714         ast::ExprBox(Some(ref place), _) => {
2715             // Special case `Box<T>` for now:
2716             let def_id = match tcx.def_map.borrow().get(&place.id) {
2717                 Some(def) => def.def_id(),
2718                 None => panic!("no def for place"),
2719             };
2720             if tcx.lang_items.exchange_heap() == Some(def_id) {
2721                 ExprKind::RvalueDatum
2722             } else {
2723                 ExprKind::RvalueDps
2724             }
2725         }
2726
2727         ast::ExprParen(ref e) => expr_kind(tcx, &**e),
2728
2729         ast::ExprMac(..) => {
2730             tcx.sess.span_bug(
2731                 expr.span,
2732                 "macro expression remains after expansion");
2733         }
2734     }
2735 }