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