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