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