]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/expr.rs
Auto merge of #28136 - huonw:simd, 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     assert!(!lhs_t.is_simd());
1697     let is_float = lhs_t.is_fp();
1698     let is_signed = lhs_t.is_signed();
1699     let info = expr_info(binop_expr);
1700
1701     let binop_debug_loc = binop_expr.debug_loc();
1702
1703     let mut bcx = bcx;
1704     let val = match op.node {
1705       ast::BiAdd => {
1706         if is_float {
1707             FAdd(bcx, lhs, rhs, binop_debug_loc)
1708         } else {
1709             let (newbcx, res) = with_overflow_check(
1710                 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1711             bcx = newbcx;
1712             res
1713         }
1714       }
1715       ast::BiSub => {
1716         if is_float {
1717             FSub(bcx, lhs, rhs, binop_debug_loc)
1718         } else {
1719             let (newbcx, res) = with_overflow_check(
1720                 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1721             bcx = newbcx;
1722             res
1723         }
1724       }
1725       ast::BiMul => {
1726         if is_float {
1727             FMul(bcx, lhs, rhs, binop_debug_loc)
1728         } else {
1729             let (newbcx, res) = with_overflow_check(
1730                 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1731             bcx = newbcx;
1732             res
1733         }
1734       }
1735       ast::BiDiv => {
1736         if is_float {
1737             FDiv(bcx, lhs, rhs, binop_debug_loc)
1738         } else {
1739             // Only zero-check integers; fp /0 is NaN
1740             bcx = base::fail_if_zero_or_overflows(bcx,
1741                                                   expr_info(binop_expr),
1742                                                   op,
1743                                                   lhs,
1744                                                   rhs,
1745                                                   rhs_t);
1746             if is_signed {
1747                 SDiv(bcx, lhs, rhs, binop_debug_loc)
1748             } else {
1749                 UDiv(bcx, lhs, rhs, binop_debug_loc)
1750             }
1751         }
1752       }
1753       ast::BiRem => {
1754         if is_float {
1755             // LLVM currently always lowers the `frem` instructions appropriate
1756             // library calls typically found in libm. Notably f64 gets wired up
1757             // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
1758             // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
1759             // instead just an inline function in a header that goes up to a
1760             // f64, uses `fmod`, and then comes back down to a f32.
1761             //
1762             // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
1763             // still unconditionally lower frem instructions over 32-bit floats
1764             // to a call to `fmodf`. To work around this we special case MSVC
1765             // 32-bit float rem instructions and instead do the call out to
1766             // `fmod` ourselves.
1767             //
1768             // Note that this is currently duplicated with src/libcore/ops.rs
1769             // which does the same thing, and it would be nice to perhaps unify
1770             // these two implementations on day! Also note that we call `fmod`
1771             // for both 32 and 64-bit floats because if we emit any FRem
1772             // instruction at all then LLVM is capable of optimizing it into a
1773             // 32-bit FRem (which we're trying to avoid).
1774             let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
1775                            tcx.sess.target.target.arch == "x86";
1776             if use_fmod {
1777                 let f64t = Type::f64(bcx.ccx());
1778                 let fty = Type::func(&[f64t, f64t], &f64t);
1779                 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty,
1780                                                 tcx.types.f64);
1781                 if lhs_t == tcx.types.f32 {
1782                     let lhs = FPExt(bcx, lhs, f64t);
1783                     let rhs = FPExt(bcx, rhs, f64t);
1784                     let res = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
1785                     FPTrunc(bcx, res, Type::f32(bcx.ccx()))
1786                 } else {
1787                     Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc)
1788                 }
1789             } else {
1790                 FRem(bcx, lhs, rhs, binop_debug_loc)
1791             }
1792         } else {
1793             // Only zero-check integers; fp %0 is NaN
1794             bcx = base::fail_if_zero_or_overflows(bcx,
1795                                                   expr_info(binop_expr),
1796                                                   op, lhs, rhs, rhs_t);
1797             if is_signed {
1798                 SRem(bcx, lhs, rhs, binop_debug_loc)
1799             } else {
1800                 URem(bcx, lhs, rhs, binop_debug_loc)
1801             }
1802         }
1803       }
1804       ast::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1805       ast::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1806       ast::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1807       ast::BiShl => {
1808           let (newbcx, res) = with_overflow_check(
1809               bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1810           bcx = newbcx;
1811           res
1812       }
1813       ast::BiShr => {
1814           let (newbcx, res) = with_overflow_check(
1815               bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1816           bcx = newbcx;
1817           res
1818       }
1819       ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1820           base::compare_scalar_types(bcx, lhs, rhs, lhs_t, op.node, binop_debug_loc)
1821       }
1822       _ => {
1823         bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1824       }
1825     };
1826
1827     immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1828 }
1829
1830 // refinement types would obviate the need for this
1831 enum lazy_binop_ty {
1832     lazy_and,
1833     lazy_or,
1834 }
1835
1836 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1837                                 binop_expr: &ast::Expr,
1838                                 op: lazy_binop_ty,
1839                                 a: &ast::Expr,
1840                                 b: &ast::Expr)
1841                                 -> DatumBlock<'blk, 'tcx, Expr> {
1842     let _icx = push_ctxt("trans_lazy_binop");
1843     let binop_ty = expr_ty(bcx, binop_expr);
1844     let fcx = bcx.fcx;
1845
1846     let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1847     let lhs = lhs.to_llscalarish(past_lhs);
1848
1849     if past_lhs.unreachable.get() {
1850         return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1851     }
1852
1853     let join = fcx.new_id_block("join", binop_expr.id);
1854     let before_rhs = fcx.new_id_block("before_rhs", b.id);
1855
1856     match op {
1857       lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1858       lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1859     }
1860
1861     let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1862     let rhs = rhs.to_llscalarish(past_rhs);
1863
1864     if past_rhs.unreachable.get() {
1865         return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1866     }
1867
1868     Br(past_rhs, join.llbb, DebugLoc::None);
1869     let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1870                   &[past_lhs.llbb, past_rhs.llbb]);
1871
1872     return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1873 }
1874
1875 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1876                             expr: &ast::Expr,
1877                             op: ast::BinOp,
1878                             lhs: &ast::Expr,
1879                             rhs: &ast::Expr)
1880                             -> DatumBlock<'blk, 'tcx, Expr> {
1881     let _icx = push_ctxt("trans_binary");
1882     let ccx = bcx.ccx();
1883
1884     // if overloaded, would be RvalueDpsExpr
1885     assert!(!ccx.tcx().is_method_call(expr.id));
1886
1887     match op.node {
1888         ast::BiAnd => {
1889             trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1890         }
1891         ast::BiOr => {
1892             trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1893         }
1894         _ => {
1895             let mut bcx = bcx;
1896             let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1897             let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1898             let binop_ty = expr_ty(bcx, expr);
1899
1900             debug!("trans_binary (expr {}): lhs_datum={}",
1901                    expr.id,
1902                    lhs_datum.to_string(ccx));
1903             let lhs_ty = lhs_datum.ty;
1904             let lhs = lhs_datum.to_llscalarish(bcx);
1905
1906             debug!("trans_binary (expr {}): rhs_datum={}",
1907                    expr.id,
1908                    rhs_datum.to_string(ccx));
1909             let rhs_ty = rhs_datum.ty;
1910             let rhs = rhs_datum.to_llscalarish(bcx);
1911             trans_eager_binop(bcx, expr, binop_ty, op,
1912                               lhs_ty, lhs, rhs_ty, rhs)
1913         }
1914     }
1915 }
1916
1917 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1918                                    expr: &ast::Expr,
1919                                    method_call: MethodCall,
1920                                    lhs: Datum<'tcx, Expr>,
1921                                    rhs: Option<(Datum<'tcx, Expr>, ast::NodeId)>,
1922                                    dest: Option<Dest>,
1923                                    autoref: bool)
1924                                    -> Result<'blk, 'tcx> {
1925     callee::trans_call_inner(bcx,
1926                              expr.debug_loc(),
1927                              |bcx, arg_cleanup_scope| {
1928                                 meth::trans_method_callee(bcx,
1929                                                           method_call,
1930                                                           None,
1931                                                           arg_cleanup_scope)
1932                              },
1933                              callee::ArgOverloadedOp(lhs, rhs, autoref),
1934                              dest)
1935 }
1936
1937 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1938                                          expr: &ast::Expr,
1939                                          callee: &'a ast::Expr,
1940                                          args: &'a [P<ast::Expr>],
1941                                          dest: Option<Dest>)
1942                                          -> Block<'blk, 'tcx> {
1943     debug!("trans_overloaded_call {}", expr.id);
1944     let method_call = MethodCall::expr(expr.id);
1945     let mut all_args = vec!(callee);
1946     all_args.extend(args.iter().map(|e| &**e));
1947     unpack_result!(bcx,
1948                    callee::trans_call_inner(bcx,
1949                                             expr.debug_loc(),
1950                                             |bcx, arg_cleanup_scope| {
1951                                                 meth::trans_method_callee(
1952                                                     bcx,
1953                                                     method_call,
1954                                                     None,
1955                                                     arg_cleanup_scope)
1956                                             },
1957                                             callee::ArgOverloadedCall(all_args),
1958                                             dest));
1959     bcx
1960 }
1961
1962 pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
1963                           expr: &ast::Expr,
1964                           t_in: Ty<'tcx>,
1965                           t_out: Ty<'tcx>)
1966                           -> bool {
1967     if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
1968         return true;
1969     }
1970
1971     match (t_in.builtin_deref(true), t_out.builtin_deref(true)) {
1972         (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
1973             t_in == t_out
1974         }
1975         _ => {
1976             // This condition isn't redundant with the check for CoercionCast:
1977             // different types can be substituted into the same type, and
1978             // == equality can be overconservative if there are regions.
1979             t_in == t_out
1980         }
1981     }
1982 }
1983
1984 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1985                               expr: &ast::Expr,
1986                               id: ast::NodeId)
1987                               -> DatumBlock<'blk, 'tcx, Expr>
1988 {
1989     use middle::cast::CastTy::*;
1990     use middle::cast::IntTy::*;
1991
1992     fn int_cast(bcx: Block,
1993                 lldsttype: Type,
1994                 llsrctype: Type,
1995                 llsrc: ValueRef,
1996                 signed: bool)
1997                 -> ValueRef
1998     {
1999         let _icx = push_ctxt("int_cast");
2000         let srcsz = llsrctype.int_width();
2001         let dstsz = lldsttype.int_width();
2002         return if dstsz == srcsz {
2003             BitCast(bcx, llsrc, lldsttype)
2004         } else if srcsz > dstsz {
2005             TruncOrBitCast(bcx, llsrc, lldsttype)
2006         } else if signed {
2007             SExtOrBitCast(bcx, llsrc, lldsttype)
2008         } else {
2009             ZExtOrBitCast(bcx, llsrc, lldsttype)
2010         }
2011     }
2012
2013     fn float_cast(bcx: Block,
2014                   lldsttype: Type,
2015                   llsrctype: Type,
2016                   llsrc: ValueRef)
2017                   -> ValueRef
2018     {
2019         let _icx = push_ctxt("float_cast");
2020         let srcsz = llsrctype.float_width();
2021         let dstsz = lldsttype.float_width();
2022         return if dstsz > srcsz {
2023             FPExt(bcx, llsrc, lldsttype)
2024         } else if srcsz > dstsz {
2025             FPTrunc(bcx, llsrc, lldsttype)
2026         } else { llsrc };
2027     }
2028
2029     let _icx = push_ctxt("trans_cast");
2030     let mut bcx = bcx;
2031     let ccx = bcx.ccx();
2032
2033     let t_in = expr_ty_adjusted(bcx, expr);
2034     let t_out = node_id_type(bcx, id);
2035
2036     debug!("trans_cast({:?} as {:?})", t_in, t_out);
2037     let mut ll_t_in = type_of::arg_type_of(ccx, t_in);
2038     let ll_t_out = type_of::arg_type_of(ccx, t_out);
2039     // Convert the value to be cast into a ValueRef, either by-ref or
2040     // by-value as appropriate given its type:
2041     let mut datum = unpack_datum!(bcx, trans(bcx, expr));
2042
2043     let datum_ty = monomorphize_type(bcx, datum.ty);
2044
2045     if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
2046         datum.ty = t_out;
2047         return DatumBlock::new(bcx, datum);
2048     }
2049
2050     if type_is_fat_ptr(bcx.tcx(), t_in) {
2051         assert!(datum.kind.is_by_ref());
2052         if type_is_fat_ptr(bcx.tcx(), t_out) {
2053             return DatumBlock::new(bcx, Datum::new(
2054                 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
2055                 t_out,
2056                 Rvalue::new(ByRef)
2057             )).to_expr_datumblock();
2058         } else {
2059             // Return the address
2060             return immediate_rvalue_bcx(bcx,
2061                                         PointerCast(bcx,
2062                                                     Load(bcx, get_dataptr(bcx, datum.val)),
2063                                                     ll_t_out),
2064                                         t_out).to_expr_datumblock();
2065         }
2066     }
2067
2068     let r_t_in = CastTy::from_ty(t_in).expect("bad input type for cast");
2069     let r_t_out = CastTy::from_ty(t_out).expect("bad output type for cast");
2070
2071     let (llexpr, signed) = if let Int(CEnum) = r_t_in {
2072         let repr = adt::represent_type(ccx, t_in);
2073         let datum = unpack_datum!(
2074             bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2075         let llexpr_ptr = datum.to_llref();
2076         let discr = adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2077         ll_t_in = val_ty(discr);
2078         (discr, adt::is_discr_signed(&*repr))
2079     } else {
2080         (datum.to_llscalarish(bcx), t_in.is_signed())
2081     };
2082
2083     let newval = match (r_t_in, r_t_out) {
2084         (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
2085             PointerCast(bcx, llexpr, ll_t_out)
2086         }
2087         (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
2088         (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
2089
2090         (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
2091         (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
2092         (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
2093         (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
2094         (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
2095         (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
2096
2097         _ => ccx.sess().span_bug(expr.span,
2098                                   &format!("translating unsupported cast: \
2099                                             {:?} -> {:?}",
2100                                            t_in,
2101                                            t_out)
2102                                  )
2103     };
2104     return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2105 }
2106
2107 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2108                                expr: &ast::Expr,
2109                                op: ast::BinOp,
2110                                dst: &ast::Expr,
2111                                src: &ast::Expr)
2112                                -> Block<'blk, 'tcx> {
2113     let _icx = push_ctxt("trans_assign_op");
2114     let mut bcx = bcx;
2115
2116     debug!("trans_assign_op(expr={:?})", expr);
2117
2118     // User-defined operator methods cannot be used with `+=` etc right now
2119     assert!(!bcx.tcx().is_method_call(expr.id));
2120
2121     // Evaluate LHS (destination), which should be an lvalue
2122     let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2123     assert!(!bcx.fcx.type_needs_drop(dst_datum.ty));
2124     let dst_ty = dst_datum.ty;
2125     let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2126
2127     // Evaluate RHS
2128     let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2129     let rhs_ty = rhs_datum.ty;
2130     let rhs = rhs_datum.to_llscalarish(bcx);
2131
2132     // Perform computation and store the result
2133     let result_datum = unpack_datum!(
2134         bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2135                                dst_ty, dst, rhs_ty, rhs));
2136     return result_datum.store_to(bcx, dst_datum.val);
2137 }
2138
2139 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2140                         datum: Datum<'tcx, Expr>,
2141                         expr: &ast::Expr)
2142                         -> DatumBlock<'blk, 'tcx, Expr> {
2143     let mut bcx = bcx;
2144
2145     // Ensure cleanup of `datum` if not already scheduled and obtain
2146     // a "by ref" pointer.
2147     let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2148
2149     // Compute final type. Note that we are loose with the region and
2150     // mutability, since those things don't matter in trans.
2151     let referent_ty = lv_datum.ty;
2152     let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2153
2154     // Get the pointer.
2155     let llref = lv_datum.to_llref();
2156
2157     // Construct the resulting datum, using what was the "by ref"
2158     // ValueRef of type `referent_ty` to be the "by value" ValueRef
2159     // of type `&referent_ty`.
2160     // Pointers to DST types are non-immediate, and therefore still use ByRef.
2161     let kind  = if type_is_sized(bcx.tcx(), referent_ty) { ByValue } else { ByRef };
2162     DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(kind))))
2163 }
2164
2165 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2166                               expr: &ast::Expr,
2167                               datum: Datum<'tcx, Expr>,
2168                               times: usize)
2169                               -> DatumBlock<'blk, 'tcx, Expr> {
2170     let mut bcx = bcx;
2171     let mut datum = datum;
2172     for i in 0..times {
2173         let method_call = MethodCall::autoderef(expr.id, i as u32);
2174         datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2175     }
2176     DatumBlock { bcx: bcx, datum: datum }
2177 }
2178
2179 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2180                           expr: &ast::Expr,
2181                           datum: Datum<'tcx, Expr>,
2182                           method_call: MethodCall)
2183                           -> DatumBlock<'blk, 'tcx, Expr> {
2184     let ccx = bcx.ccx();
2185
2186     debug!("deref_once(expr={:?}, datum={}, method_call={:?})",
2187            expr,
2188            datum.to_string(ccx),
2189            method_call);
2190
2191     let mut bcx = bcx;
2192
2193     // Check for overloaded deref.
2194     let method_ty = ccx.tcx()
2195                        .tables
2196                        .borrow()
2197                        .method_map
2198                        .get(&method_call).map(|method| method.ty);
2199
2200     let datum = match method_ty {
2201         Some(method_ty) => {
2202             let method_ty = monomorphize_type(bcx, method_ty);
2203
2204             // Overloaded. Evaluate `trans_overloaded_op`, which will
2205             // invoke the user's deref() method, which basically
2206             // converts from the `Smaht<T>` pointer that we have into
2207             // a `&T` pointer.  We can then proceed down the normal
2208             // path (below) to dereference that `&T`.
2209             let datum = if method_call.autoderef == 0 {
2210                 datum
2211             } else {
2212                 // Always perform an AutoPtr when applying an overloaded auto-deref
2213                 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2214             };
2215
2216             let ref_ty = // invoked methods have their LB regions instantiated
2217                 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2218             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2219
2220             unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2221                                                     datum, None, Some(SaveIn(scratch.val)),
2222                                                     false));
2223             scratch.to_expr_datum()
2224         }
2225         None => {
2226             // Not overloaded. We already have a pointer we know how to deref.
2227             datum
2228         }
2229     };
2230
2231     let r = match datum.ty.sty {
2232         ty::TyBox(content_ty) => {
2233             // Make sure we have an lvalue datum here to get the
2234             // proper cleanups scheduled
2235             let datum = unpack_datum!(
2236                 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2237
2238             if type_is_sized(bcx.tcx(), content_ty) {
2239                 let ptr = load_ty(bcx, datum.val, datum.ty);
2240                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(datum.kind)))
2241             } else {
2242                 // A fat pointer and a DST lvalue have the same representation
2243                 // just different types. Since there is no temporary for `*e`
2244                 // here (because it is unsized), we cannot emulate the sized
2245                 // object code path for running drop glue and free. Instead,
2246                 // we schedule cleanup for `e`, turning it into an lvalue.
2247
2248                 let lval = Lvalue::new("expr::deref_once ty_uniq");
2249                 let datum = Datum::new(datum.val, content_ty, LvalueExpr(lval));
2250                 DatumBlock::new(bcx, datum)
2251             }
2252         }
2253
2254         ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
2255         ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
2256             let lval = Lvalue::new("expr::deref_once ptr");
2257             if type_is_sized(bcx.tcx(), content_ty) {
2258                 let ptr = datum.to_llscalarish(bcx);
2259
2260                 // Always generate an lvalue datum, even if datum.mode is
2261                 // an rvalue.  This is because datum.mode is only an
2262                 // rvalue for non-owning pointers like &T or *T, in which
2263                 // case cleanup *is* scheduled elsewhere, by the true
2264                 // owner (or, in the case of *T, by the user).
2265                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(lval)))
2266             } else {
2267                 // A fat pointer and a DST lvalue have the same representation
2268                 // just different types.
2269                 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr(lval)))
2270             }
2271         }
2272
2273         _ => {
2274             bcx.tcx().sess.span_bug(
2275                 expr.span,
2276                 &format!("deref invoked on expr of invalid type {:?}",
2277                         datum.ty));
2278         }
2279     };
2280
2281     debug!("deref_once(expr={}, method_call={:?}, result={})",
2282            expr.id, method_call, r.datum.to_string(ccx));
2283
2284     return r;
2285 }
2286
2287 #[derive(Debug)]
2288 enum OverflowOp {
2289     Add,
2290     Sub,
2291     Mul,
2292     Shl,
2293     Shr,
2294 }
2295
2296 impl OverflowOp {
2297     fn codegen_strategy(&self) -> OverflowCodegen {
2298         use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2299         match *self {
2300             OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2301             OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2302             OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2303
2304             OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2305             OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2306         }
2307     }
2308 }
2309
2310 enum OverflowCodegen {
2311     ViaIntrinsic(OverflowOpViaIntrinsic),
2312     ViaInputCheck(OverflowOpViaInputCheck),
2313 }
2314
2315 enum OverflowOpViaInputCheck { Shl, Shr, }
2316
2317 #[derive(Debug)]
2318 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2319
2320 impl OverflowOpViaIntrinsic {
2321     fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2322         let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2323         bcx.ccx().get_intrinsic(&name)
2324     }
2325     fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str {
2326         use syntax::ast::IntTy::*;
2327         use syntax::ast::UintTy::*;
2328         use middle::ty::{TyInt, TyUint};
2329
2330         let new_sty = match ty.sty {
2331             TyInt(TyIs) => match &tcx.sess.target.target.target_pointer_width[..] {
2332                 "32" => TyInt(TyI32),
2333                 "64" => TyInt(TyI64),
2334                 _ => panic!("unsupported target word size")
2335             },
2336             TyUint(TyUs) => match &tcx.sess.target.target.target_pointer_width[..] {
2337                 "32" => TyUint(TyU32),
2338                 "64" => TyUint(TyU64),
2339                 _ => panic!("unsupported target word size")
2340             },
2341             ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2342             _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2343                         *self)
2344         };
2345
2346         match *self {
2347             OverflowOpViaIntrinsic::Add => match new_sty {
2348                 TyInt(TyI8) => "llvm.sadd.with.overflow.i8",
2349                 TyInt(TyI16) => "llvm.sadd.with.overflow.i16",
2350                 TyInt(TyI32) => "llvm.sadd.with.overflow.i32",
2351                 TyInt(TyI64) => "llvm.sadd.with.overflow.i64",
2352
2353                 TyUint(TyU8) => "llvm.uadd.with.overflow.i8",
2354                 TyUint(TyU16) => "llvm.uadd.with.overflow.i16",
2355                 TyUint(TyU32) => "llvm.uadd.with.overflow.i32",
2356                 TyUint(TyU64) => "llvm.uadd.with.overflow.i64",
2357
2358                 _ => unreachable!(),
2359             },
2360             OverflowOpViaIntrinsic::Sub => match new_sty {
2361                 TyInt(TyI8) => "llvm.ssub.with.overflow.i8",
2362                 TyInt(TyI16) => "llvm.ssub.with.overflow.i16",
2363                 TyInt(TyI32) => "llvm.ssub.with.overflow.i32",
2364                 TyInt(TyI64) => "llvm.ssub.with.overflow.i64",
2365
2366                 TyUint(TyU8) => "llvm.usub.with.overflow.i8",
2367                 TyUint(TyU16) => "llvm.usub.with.overflow.i16",
2368                 TyUint(TyU32) => "llvm.usub.with.overflow.i32",
2369                 TyUint(TyU64) => "llvm.usub.with.overflow.i64",
2370
2371                 _ => unreachable!(),
2372             },
2373             OverflowOpViaIntrinsic::Mul => match new_sty {
2374                 TyInt(TyI8) => "llvm.smul.with.overflow.i8",
2375                 TyInt(TyI16) => "llvm.smul.with.overflow.i16",
2376                 TyInt(TyI32) => "llvm.smul.with.overflow.i32",
2377                 TyInt(TyI64) => "llvm.smul.with.overflow.i64",
2378
2379                 TyUint(TyU8) => "llvm.umul.with.overflow.i8",
2380                 TyUint(TyU16) => "llvm.umul.with.overflow.i16",
2381                 TyUint(TyU32) => "llvm.umul.with.overflow.i32",
2382                 TyUint(TyU64) => "llvm.umul.with.overflow.i64",
2383
2384                 _ => unreachable!(),
2385             },
2386         }
2387     }
2388
2389     fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2390                                         info: NodeIdAndSpan,
2391                                         lhs_t: Ty<'tcx>, lhs: ValueRef,
2392                                         rhs: ValueRef,
2393                                         binop_debug_loc: DebugLoc)
2394                                         -> (Block<'blk, 'tcx>, ValueRef) {
2395         let llfn = self.to_intrinsic(bcx, lhs_t);
2396
2397         let val = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
2398         let result = ExtractValue(bcx, val, 0); // iN operation result
2399         let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2400
2401         let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2402                         binop_debug_loc);
2403
2404         let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2405         Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2406              None, binop_debug_loc);
2407
2408         let bcx =
2409             base::with_cond(bcx, cond, |bcx|
2410                 controlflow::trans_fail(bcx, info,
2411                     InternedString::new("arithmetic operation overflowed")));
2412
2413         (bcx, result)
2414     }
2415 }
2416
2417 impl OverflowOpViaInputCheck {
2418     fn build_with_input_check<'blk, 'tcx>(&self,
2419                                           bcx: Block<'blk, 'tcx>,
2420                                           info: NodeIdAndSpan,
2421                                           lhs_t: Ty<'tcx>,
2422                                           lhs: ValueRef,
2423                                           rhs: ValueRef,
2424                                           binop_debug_loc: DebugLoc)
2425                                           -> (Block<'blk, 'tcx>, ValueRef)
2426     {
2427         let lhs_llty = val_ty(lhs);
2428         let rhs_llty = val_ty(rhs);
2429
2430         // Panic if any bits are set outside of bits that we always
2431         // mask in.
2432         //
2433         // Note that the mask's value is derived from the LHS type
2434         // (since that is where the 32/64 distinction is relevant) but
2435         // the mask's type must match the RHS type (since they will
2436         // both be fed into a and-binop)
2437         let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2438
2439         let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2440         let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2441         let result = match *self {
2442             OverflowOpViaInputCheck::Shl =>
2443                 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2444             OverflowOpViaInputCheck::Shr =>
2445                 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2446         };
2447         let bcx =
2448             base::with_cond(bcx, cond, |bcx|
2449                 controlflow::trans_fail(bcx, info,
2450                     InternedString::new("shift operation overflowed")));
2451
2452         (bcx, result)
2453     }
2454 }
2455
2456 fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2457                               llty: Type,
2458                               mask_llty: Type,
2459                               invert: bool) -> ValueRef {
2460     let kind = llty.kind();
2461     match kind {
2462         TypeKind::Integer => {
2463             // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
2464             let val = llty.int_width() - 1;
2465             if invert {
2466                 C_integral(mask_llty, !val, true)
2467             } else {
2468                 C_integral(mask_llty, val, false)
2469             }
2470         },
2471         TypeKind::Vector => {
2472             let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
2473             VectorSplat(bcx, mask_llty.vector_length(), mask)
2474         },
2475         _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
2476     }
2477 }
2478
2479 // Check if an integer or vector contains a nonzero element.
2480 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2481                                    value: ValueRef,
2482                                    binop_debug_loc: DebugLoc) -> ValueRef {
2483     let llty = val_ty(value);
2484     let kind = llty.kind();
2485     match kind {
2486         TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2487         TypeKind::Vector => {
2488             // Check if any elements of the vector are nonzero by treating
2489             // it as a wide integer and checking if the integer is nonzero.
2490             let width = llty.vector_length() as u64 * llty.element_type().int_width();
2491             let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2492             build_nonzero_check(bcx, int_value, binop_debug_loc)
2493         },
2494         _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2495     }
2496 }
2497
2498 // To avoid UB from LLVM, these two functions mask RHS with an
2499 // appropriate mask unconditionally (i.e. the fallback behavior for
2500 // all shifts). For 32- and 64-bit types, this matches the semantics
2501 // of Java. (See related discussion on #1877 and #10183.)
2502
2503 fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2504                                       lhs: ValueRef,
2505                                       rhs: ValueRef,
2506                                       binop_debug_loc: DebugLoc) -> ValueRef {
2507     let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShl, lhs, rhs);
2508     // #1877, #10183: Ensure that input is always valid
2509     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2510     Shl(bcx, lhs, rhs, binop_debug_loc)
2511 }
2512
2513 fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2514                                       lhs_t: Ty<'tcx>,
2515                                       lhs: ValueRef,
2516                                       rhs: ValueRef,
2517                                       binop_debug_loc: DebugLoc) -> ValueRef {
2518     let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShr, lhs, rhs);
2519     // #1877, #10183: Ensure that input is always valid
2520     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2521     let is_signed = lhs_t.is_signed();
2522     if is_signed {
2523         AShr(bcx, lhs, rhs, binop_debug_loc)
2524     } else {
2525         LShr(bcx, lhs, rhs, binop_debug_loc)
2526     }
2527 }
2528
2529 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2530                               rhs: ValueRef,
2531                               debug_loc: DebugLoc) -> ValueRef {
2532     let rhs_llty = val_ty(rhs);
2533     And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
2534 }
2535
2536 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2537                                    lhs_t: Ty<'tcx>, lhs: ValueRef,
2538                                    rhs: ValueRef,
2539                                    binop_debug_loc: DebugLoc)
2540                                    -> (Block<'blk, 'tcx>, ValueRef) {
2541     if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2542     if bcx.ccx().check_overflow() {
2543
2544         match oop.codegen_strategy() {
2545             OverflowCodegen::ViaIntrinsic(oop) =>
2546                 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2547             OverflowCodegen::ViaInputCheck(oop) =>
2548                 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2549         }
2550     } else {
2551         let res = match oop {
2552             OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2553             OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2554             OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2555
2556             OverflowOp::Shl =>
2557                 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2558             OverflowOp::Shr =>
2559                 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2560         };
2561         (bcx, res)
2562     }
2563 }
2564
2565 /// We categorize expressions into three kinds.  The distinction between
2566 /// lvalue/rvalue is fundamental to the language.  The distinction between the
2567 /// two kinds of rvalues is an artifact of trans which reflects how we will
2568 /// generate code for that kind of expression.  See trans/expr.rs for more
2569 /// information.
2570 #[derive(Copy, Clone)]
2571 enum ExprKind {
2572     Lvalue,
2573     RvalueDps,
2574     RvalueDatum,
2575     RvalueStmt
2576 }
2577
2578 fn expr_kind(tcx: &ty::ctxt, expr: &ast::Expr) -> ExprKind {
2579     if tcx.is_method_call(expr.id) {
2580         // Overloaded operations are generally calls, and hence they are
2581         // generated via DPS, but there are a few exceptions:
2582         return match expr.node {
2583             // `a += b` has a unit result.
2584             ast::ExprAssignOp(..) => ExprKind::RvalueStmt,
2585
2586             // the deref method invoked for `*a` always yields an `&T`
2587             ast::ExprUnary(ast::UnDeref, _) => ExprKind::Lvalue,
2588
2589             // the index method invoked for `a[i]` always yields an `&T`
2590             ast::ExprIndex(..) => ExprKind::Lvalue,
2591
2592             // in the general case, result could be any type, use DPS
2593             _ => ExprKind::RvalueDps
2594         };
2595     }
2596
2597     match expr.node {
2598         ast::ExprPath(..) => {
2599             match tcx.resolve_expr(expr) {
2600                 def::DefStruct(_) | def::DefVariant(..) => {
2601                     if let ty::TyBareFn(..) = tcx.node_id_to_type(expr.id).sty {
2602                         // ctor function
2603                         ExprKind::RvalueDatum
2604                     } else {
2605                         ExprKind::RvalueDps
2606                     }
2607                 }
2608
2609                 // Special case: A unit like struct's constructor must be called without () at the
2610                 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
2611                 // of unit structs this is should not be interpreted as function pointer but as
2612                 // call to the constructor.
2613                 def::DefFn(_, true) => ExprKind::RvalueDps,
2614
2615                 // Fn pointers are just scalar values.
2616                 def::DefFn(..) | def::DefMethod(..) => ExprKind::RvalueDatum,
2617
2618                 // Note: there is actually a good case to be made that
2619                 // DefArg's, particularly those of immediate type, ought to
2620                 // considered rvalues.
2621                 def::DefStatic(..) |
2622                 def::DefUpvar(..) |
2623                 def::DefLocal(..) => ExprKind::Lvalue,
2624
2625                 def::DefConst(..) |
2626                 def::DefAssociatedConst(..) => ExprKind::RvalueDatum,
2627
2628                 def => {
2629                     tcx.sess.span_bug(
2630                         expr.span,
2631                         &format!("uncategorized def for expr {}: {:?}",
2632                                 expr.id,
2633                                 def));
2634                 }
2635             }
2636         }
2637
2638         ast::ExprUnary(ast::UnDeref, _) |
2639         ast::ExprField(..) |
2640         ast::ExprTupField(..) |
2641         ast::ExprIndex(..) => {
2642             ExprKind::Lvalue
2643         }
2644
2645         ast::ExprCall(..) |
2646         ast::ExprMethodCall(..) |
2647         ast::ExprStruct(..) |
2648         ast::ExprRange(..) |
2649         ast::ExprTup(..) |
2650         ast::ExprIf(..) |
2651         ast::ExprMatch(..) |
2652         ast::ExprClosure(..) |
2653         ast::ExprBlock(..) |
2654         ast::ExprRepeat(..) |
2655         ast::ExprVec(..) => {
2656             ExprKind::RvalueDps
2657         }
2658
2659         ast::ExprIfLet(..) => {
2660             tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
2661         }
2662         ast::ExprWhileLet(..) => {
2663             tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
2664         }
2665
2666         ast::ExprForLoop(..) => {
2667             tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
2668         }
2669
2670         ast::ExprLit(ref lit) if ast_util::lit_is_str(&**lit) => {
2671             ExprKind::RvalueDps
2672         }
2673
2674         ast::ExprBreak(..) |
2675         ast::ExprAgain(..) |
2676         ast::ExprRet(..) |
2677         ast::ExprWhile(..) |
2678         ast::ExprLoop(..) |
2679         ast::ExprAssign(..) |
2680         ast::ExprInlineAsm(..) |
2681         ast::ExprAssignOp(..) => {
2682             ExprKind::RvalueStmt
2683         }
2684
2685         ast::ExprLit(_) | // Note: LitStr is carved out above
2686         ast::ExprUnary(..) |
2687         ast::ExprBox(None, _) |
2688         ast::ExprAddrOf(..) |
2689         ast::ExprBinary(..) |
2690         ast::ExprCast(..) => {
2691             ExprKind::RvalueDatum
2692         }
2693
2694         ast::ExprBox(Some(ref place), _) => {
2695             // Special case `Box<T>` for now:
2696             let def_id = match tcx.def_map.borrow().get(&place.id) {
2697                 Some(def) => def.def_id(),
2698                 None => panic!("no def for place"),
2699             };
2700             if tcx.lang_items.exchange_heap() == Some(def_id) {
2701                 ExprKind::RvalueDatum
2702             } else {
2703                 ExprKind::RvalueDps
2704             }
2705         }
2706
2707         ast::ExprParen(ref e) => expr_kind(tcx, &**e),
2708
2709         ast::ExprMac(..) => {
2710             tcx.sess.span_bug(
2711                 expr.span,
2712                 "macro expression remains after expansion");
2713         }
2714     }
2715 }