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