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.
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.
11 //! # Translation of Expressions
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.
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:
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`.
32 //! Public entry points:
34 //! - `trans_into(bcx, expr, dest) -> bcx`: evaluates an expression,
35 //! storing the result into `dest`. This is the preferred form, if you
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
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.
47 //! - `trans_local_var -> Datum`: looks up a local variable or upvar.
49 #![allow(non_camel_case_types)]
51 pub use self::Dest::*;
52 use self::lazy_binop_ty::*;
55 use llvm::{self, ValueRef, TypeKind};
56 use middle::check_const;
58 use middle::lang_items::CoerceUnsizedTraitLangItem;
59 use middle::subst::{Substs, VecPerParamSpace};
61 use trans::{_match, adt, asm, base, callee, closure, consts, controlflow};
64 use trans::cleanup::{self, CleanupMethods, DropHintMethods};
67 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
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;
82 use syntax::{ast, ast_util, codemap};
83 use syntax::parse::token::InternedString;
85 use syntax::parse::token;
90 // These are passed around by the code generating functions to track the
91 // destination of a computation's value.
93 #[derive(Copy, Clone, PartialEq)]
100 pub fn to_string(&self, ccx: &CrateContext) -> String {
102 SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
103 Ignore => "Ignore".to_string()
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>,
113 -> Block<'blk, 'tcx> {
116 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
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);
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
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));
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.
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.
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(),
160 // Lock emitted debug locations to the location of
161 // the constant reference expression.
162 debuginfo::with_source_location_override(bcx.fcx,
165 bcx = trans_into(bcx, const_expr, dest)
167 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
169 assert!(scopes.is_empty());
180 debug!("trans_into() expr={:?}", expr);
182 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
186 bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
188 let kind = expr_kind(bcx.tcx(), expr);
190 ExprKind::Lvalue | ExprKind::RvalueDatum => {
191 trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
193 ExprKind::RvalueDps => {
194 trans_rvalue_dps_unadjusted(bcx, expr, dest)
196 ExprKind::RvalueStmt => {
197 trans_rvalue_stmt_unadjusted(bcx, expr)
201 bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
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
207 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
209 -> DatumBlock<'blk, 'tcx, Expr> {
210 debug!("trans(expr={:?})", expr);
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
220 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
221 bcx.fcx.param_substs);
223 if qualif.intersects(check_const::ConstQualif::HAS_STATIC_BORROWS) {
224 // Is borrowed as 'static, must return lvalue.
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());
234 // Otherwise, keep around and perform adjustments, if needed.
235 let const_ty = if adjusted_global {
236 expr_ty_adjusted(bcx, expr)
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)
249 let llty = type_of::type_of(bcx.ccx(), const_ty);
250 // HACK(eddyb) get around issues with lifetime intrinsics.
251 let scratch = alloca_no_lifetime(bcx, llty, "const");
252 let lldest = if !const_ty.is_structural() {
253 // Cast pointer to slot, because constants have different types.
254 PointerCast(bcx, scratch, val_ty(global))
256 // In this case, memcpy_ty calls llvm.memcpy after casting both
257 // source and destination to i8*, so we don't need any casts.
260 memcpy_ty(bcx, lldest, global, const_ty);
261 Datum::new(scratch, const_ty, Rvalue::new(ByRef))
267 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
271 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
272 let datum = match global {
273 Some(rvalue) => rvalue.to_expr_datum(),
274 None => unpack_datum!(bcx, trans_unadjusted(bcx, expr))
276 let datum = if adjusted_global {
277 datum // trans::consts already performed adjustments.
279 unpack_datum!(bcx, apply_adjustments(bcx, expr, datum))
281 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
282 return DatumBlock::new(bcx, datum);
285 pub fn get_meta(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
286 StructGEP(bcx, fat_ptr, abi::FAT_PTR_EXTRA)
289 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
290 StructGEP(bcx, fat_ptr, abi::FAT_PTR_ADDR)
293 pub fn copy_fat_ptr(bcx: Block, src_ptr: ValueRef, dst_ptr: ValueRef) {
294 Store(bcx, Load(bcx, get_dataptr(bcx, src_ptr)), get_dataptr(bcx, dst_ptr));
295 Store(bcx, Load(bcx, get_meta(bcx, src_ptr)), get_meta(bcx, dst_ptr));
298 /// Retrieve the information we are losing (making dynamic) in an unsizing
301 /// The `old_info` argument is a bit funny. It is intended for use
302 /// in an upcast, where the new vtable for an object will be drived
303 /// from the old one.
304 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
307 old_info: Option<ValueRef>,
308 param_substs: &'tcx Substs<'tcx>)
310 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
311 match (&source.sty, &target.sty) {
312 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
313 (&ty::TyTrait(_), &ty::TyTrait(_)) => {
314 // For now, upcasts are limited to changes in marker
315 // traits, and hence never actually require an actual
316 // change to the vtable.
317 old_info.expect("unsized_info: missing old info for trait upcast")
319 (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
320 // Note that we preserve binding levels here:
321 let substs = principal.0.substs.with_self_ty(source).erase_regions();
322 let substs = ccx.tcx().mk_substs(substs);
323 let trait_ref = ty::Binder(ty::TraitRef { def_id: principal.def_id(),
325 consts::ptrcast(meth::get_vtable(ccx, trait_ref, param_substs),
326 Type::vtable_ptr(ccx))
328 _ => ccx.sess().bug(&format!("unsized_info: invalid unsizing {:?} -> {:?}",
334 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
335 /// translation of `expr`.
336 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
338 datum: Datum<'tcx, Expr>)
339 -> DatumBlock<'blk, 'tcx, Expr>
342 let mut datum = datum;
343 let adjustment = match bcx.tcx().tables.borrow().adjustments.get(&expr.id).cloned() {
345 return DatumBlock::new(bcx, datum);
349 debug!("unadjusted datum for expr {:?}: {} adjustment={:?}",
351 datum.to_string(bcx.ccx()),
354 AdjustReifyFnPointer => {
355 // FIXME(#19925) once fn item types are
356 // zero-sized, we'll need to do something here
358 AdjustUnsafeFnPointer => {
359 // purely a type-level thing
361 AdjustDerefRef(ref adj) => {
362 let skip_reborrows = if adj.autoderefs == 1 && adj.autoref.is_some() {
363 // We are a bit paranoid about adjustments and thus might have a re-
364 // borrow here which merely derefs and then refs again (it might have
365 // a different region or mutability, but we don't care here).
367 // Don't skip a conversion from Box<T> to &T, etc.
369 if bcx.tcx().is_overloaded_autoderef(expr.id, 0) {
370 // Don't skip an overloaded deref.
382 if adj.autoderefs > skip_reborrows {
384 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
385 datum = unpack_datum!(bcx, deref_multiple(bcx, expr,
386 lval.to_expr_datum(),
387 adj.autoderefs - skip_reborrows));
390 // (You might think there is a more elegant way to do this than a
391 // skip_reborrows bool, but then you remember that the borrow checker exists).
392 if skip_reborrows == 0 && adj.autoref.is_some() {
393 datum = unpack_datum!(bcx, auto_ref(bcx, datum, expr));
396 if let Some(target) = adj.unsize {
397 // We do not arrange cleanup ourselves; if we already are an
398 // L-value, then cleanup will have already been scheduled (and
399 // the `datum.to_rvalue_datum` call below will emit code to zero
400 // the drop flag when moving out of the L-value). If we are an
401 // R-value, then we do not need to schedule cleanup.
402 let source_datum = unpack_datum!(bcx,
403 datum.to_rvalue_datum(bcx, "__coerce_source"));
405 let target = bcx.monomorphize(&target);
406 let llty = type_of::type_of(bcx.ccx(), target);
408 // HACK(eddyb) get around issues with lifetime intrinsics.
409 let scratch = alloca_no_lifetime(bcx, llty, "__coerce_target");
410 let target_datum = Datum::new(scratch, target,
412 bcx = coerce_unsized(bcx, expr.span, source_datum, target_datum);
413 datum = Datum::new(scratch, target,
414 RvalueExpr(Rvalue::new(ByRef)));
418 debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
419 DatumBlock::new(bcx, datum)
422 fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
424 source: Datum<'tcx, Rvalue>,
425 target: Datum<'tcx, Rvalue>)
426 -> Block<'blk, 'tcx> {
428 debug!("coerce_unsized({} -> {})",
429 source.to_string(bcx.ccx()),
430 target.to_string(bcx.ccx()));
432 match (&source.ty.sty, &target.ty.sty) {
433 (&ty::TyBox(a), &ty::TyBox(b)) |
434 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
435 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
436 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
437 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
438 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
439 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
440 let (inner_source, inner_target) = (a, b);
442 let (base, old_info) = if !type_is_sized(bcx.tcx(), inner_source) {
443 // Normally, the source is a thin pointer and we are
444 // adding extra info to make a fat pointer. The exception
445 // is when we are upcasting an existing object fat pointer
446 // to use a different vtable. In that case, we want to
447 // load out the original data pointer so we can repackage
449 (Load(bcx, get_dataptr(bcx, source.val)),
450 Some(Load(bcx, get_meta(bcx, source.val))))
452 let val = if source.kind.is_by_ref() {
453 load_ty(bcx, source.val, source.ty)
460 let info = unsized_info(bcx.ccx(), inner_source, inner_target,
461 old_info, bcx.fcx.param_substs);
463 // Compute the base pointer. This doesn't change the pointer value,
464 // but merely its type.
465 let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), inner_target).ptr_to();
466 let base = PointerCast(bcx, base, ptr_ty);
468 Store(bcx, base, get_dataptr(bcx, target.val));
469 Store(bcx, info, get_meta(bcx, target.val));
472 // This can be extended to enums and tuples in the future.
473 // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
474 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
475 assert_eq!(def_id_a, def_id_b);
477 // The target is already by-ref because it's to be written to.
478 let source = unpack_datum!(bcx, source.to_ref_datum(bcx));
479 assert!(target.kind.is_by_ref());
481 let trait_substs = Substs::erased(VecPerParamSpace::new(vec![target.ty],
484 let trait_ref = ty::Binder(ty::TraitRef {
485 def_id: langcall(bcx, Some(span), "coercion",
486 CoerceUnsizedTraitLangItem),
487 substs: bcx.tcx().mk_substs(trait_substs)
490 let kind = match fulfill_obligation(bcx.ccx(), span, trait_ref) {
491 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
492 bcx.tcx().custom_coerce_unsized_kind(impl_def_id)
495 bcx.sess().span_bug(span, &format!("invalid CoerceUnsized vtable: {:?}",
500 let repr_source = adt::represent_type(bcx.ccx(), source.ty);
501 let src_fields = match &*repr_source {
502 &adt::Repr::Univariant(ref s, _) => &s.fields,
503 _ => bcx.sess().span_bug(span,
504 &format!("Non univariant struct? (repr_source: {:?})",
507 let repr_target = adt::represent_type(bcx.ccx(), target.ty);
508 let target_fields = match &*repr_target {
509 &adt::Repr::Univariant(ref s, _) => &s.fields,
510 _ => bcx.sess().span_bug(span,
511 &format!("Non univariant struct? (repr_target: {:?})",
515 let coerce_index = match kind {
516 ty::CustomCoerceUnsized::Struct(i) => i
518 assert!(coerce_index < src_fields.len() && src_fields.len() == target_fields.len());
520 let iter = src_fields.iter().zip(target_fields).enumerate();
521 for (i, (src_ty, target_ty)) in iter {
522 let ll_source = adt::trans_field_ptr(bcx, &repr_source, source.val, 0, i);
523 let ll_target = adt::trans_field_ptr(bcx, &repr_target, target.val, 0, i);
525 // If this is the field we need to coerce, recurse on it.
526 if i == coerce_index {
527 coerce_unsized(bcx, span,
528 Datum::new(ll_source, src_ty,
530 Datum::new(ll_target, target_ty,
531 Rvalue::new(ByRef)));
533 // Otherwise, simply copy the data from the source.
534 assert_eq!(src_ty, target_ty);
535 memcpy_ty(bcx, ll_target, ll_source, src_ty);
539 _ => bcx.sess().bug(&format!("coerce_unsized: invalid coercion {:?} -> {:?}",
546 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
547 /// that the expr represents.
549 /// If this expression is an rvalue, this implies introducing a temporary. In other words,
550 /// something like `x().f` is translated into roughly the equivalent of
552 /// { tmp = x(); tmp.f }
553 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
556 -> DatumBlock<'blk, 'tcx, Lvalue> {
558 let datum = unpack_datum!(bcx, trans(bcx, expr));
559 return datum.to_lvalue_datum(bcx, name, expr.id);
562 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
564 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
566 -> DatumBlock<'blk, 'tcx, Expr> {
569 debug!("trans_unadjusted(expr={:?})", expr);
570 let _indenter = indenter();
572 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
574 return match expr_kind(bcx.tcx(), expr) {
575 ExprKind::Lvalue | ExprKind::RvalueDatum => {
576 let datum = unpack_datum!(bcx, {
577 trans_datum_unadjusted(bcx, expr)
580 DatumBlock {bcx: bcx, datum: datum}
583 ExprKind::RvalueStmt => {
584 bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
585 nil(bcx, expr_ty(bcx, expr))
588 ExprKind::RvalueDps => {
589 let ty = expr_ty(bcx, expr);
590 if type_is_zero_size(bcx.ccx(), ty) {
591 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
594 let scratch = rvalue_scratch_datum(bcx, ty, "");
595 bcx = trans_rvalue_dps_unadjusted(
596 bcx, expr, SaveIn(scratch.val));
598 // Note: this is not obviously a good idea. It causes
599 // immediate values to be loaded immediately after a
600 // return from a call or other similar expression,
601 // which in turn leads to alloca's having shorter
602 // lifetimes and hence larger stack frames. However,
603 // in turn it can lead to more register pressure.
604 // Still, in practice it seems to increase
605 // performance, since we have fewer problems with
607 let scratch = unpack_datum!(
608 bcx, scratch.to_appropriate_datum(bcx));
610 DatumBlock::new(bcx, scratch.to_expr_datum())
615 fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
616 -> DatumBlock<'blk, 'tcx, Expr> {
617 let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
618 let datum = immediate_rvalue(llval, ty);
619 DatumBlock::new(bcx, datum.to_expr_datum())
623 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
625 -> DatumBlock<'blk, 'tcx, Expr> {
628 let _icx = push_ctxt("trans_datum_unadjusted");
631 ast::ExprParen(ref e) => {
634 ast::ExprPath(..) => {
635 trans_def(bcx, expr, bcx.def(expr.id))
637 ast::ExprField(ref base, ident) => {
638 trans_rec_field(bcx, &**base, ident.node.name)
640 ast::ExprTupField(ref base, idx) => {
641 trans_rec_tup_field(bcx, &**base, idx.node)
643 ast::ExprIndex(ref base, ref idx) => {
644 trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
646 ast::ExprBox(_, ref contents) => {
647 // Special case for `Box<T>`
648 let box_ty = expr_ty(bcx, expr);
649 let contents_ty = expr_ty(bcx, &**contents);
652 trans_uniq_expr(bcx, expr, box_ty, &**contents, contents_ty)
654 _ => bcx.sess().span_bug(expr.span,
655 "expected unique box")
659 ast::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
660 ast::ExprBinary(op, ref lhs, ref rhs) => {
661 trans_binary(bcx, expr, op, &**lhs, &**rhs)
663 ast::ExprUnary(op, ref x) => {
664 trans_unary(bcx, expr, op, &**x)
666 ast::ExprAddrOf(_, ref x) => {
668 ast::ExprRepeat(..) | ast::ExprVec(..) => {
669 // Special case for slices.
670 let cleanup_debug_loc =
671 debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
675 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
676 let datum = unpack_datum!(
677 bcx, tvec::trans_slice_vec(bcx, expr, &**x));
678 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
679 DatumBlock::new(bcx, datum)
682 trans_addr_of(bcx, expr, &**x)
686 ast::ExprCast(ref val, _) => {
687 // Datum output mode means this is a scalar cast:
688 trans_imm_cast(bcx, &**val, expr.id)
691 bcx.tcx().sess.span_bug(
693 &format!("trans_rvalue_datum_unadjusted reached \
694 fall-through case: {:?}",
700 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
703 -> DatumBlock<'blk, 'tcx, Expr> where
704 F: FnOnce(&'blk ty::ctxt<'tcx>, &VariantInfo<'tcx>) -> usize,
707 let _icx = push_ctxt("trans_rec_field");
709 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
710 let bare_ty = base_datum.ty;
711 let repr = adt::represent_type(bcx.ccx(), bare_ty);
712 let vinfo = VariantInfo::from_ty(bcx.tcx(), bare_ty, None);
714 let ix = get_idx(bcx.tcx(), &vinfo);
715 let d = base_datum.get_element(
718 |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, vinfo.discr, ix));
720 if type_is_sized(bcx.tcx(), d.ty) {
721 DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
723 let scratch = rvalue_scratch_datum(bcx, d.ty, "");
724 Store(bcx, d.val, get_dataptr(bcx, scratch.val));
725 let info = Load(bcx, get_meta(bcx, base_datum.val));
726 Store(bcx, info, get_meta(bcx, scratch.val));
728 // Always generate an lvalue datum, because this pointer doesn't own
729 // the data and cleanup is scheduled elsewhere.
730 DatumBlock::new(bcx, Datum::new(scratch.val, scratch.ty, LvalueExpr(d.kind)))
734 /// Translates `base.field`.
735 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
738 -> DatumBlock<'blk, 'tcx, Expr> {
739 trans_field(bcx, base, |_, vinfo| vinfo.field_index(field))
742 /// Translates `base.<idx>`.
743 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
746 -> DatumBlock<'blk, 'tcx, Expr> {
747 trans_field(bcx, base, |_, _| idx)
750 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
751 index_expr: &ast::Expr,
754 method_call: MethodCall)
755 -> DatumBlock<'blk, 'tcx, Expr> {
756 //! Translates `base[idx]`.
758 let _icx = push_ctxt("trans_index");
762 let index_expr_debug_loc = index_expr.debug_loc();
764 // Check for overloaded index.
765 let method_ty = ccx.tcx()
770 .map(|method| method.ty);
771 let elt_datum = match method_ty {
773 let method_ty = monomorphize_type(bcx, method_ty);
775 let base_datum = unpack_datum!(bcx, trans(bcx, base));
777 // Translate index expression.
778 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
780 let ref_ty = // invoked methods have LB regions instantiated:
781 bcx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
782 let elt_ty = match ref_ty.builtin_deref(true) {
784 bcx.tcx().sess.span_bug(index_expr.span,
785 "index method didn't return a \
786 dereferenceable type?!")
788 Some(elt_tm) => elt_tm.ty,
791 // Overloaded. Evaluate `trans_overloaded_op`, which will
792 // invoke the user's index() method, which basically yields
793 // a `&T` pointer. We can then proceed down the normal
794 // path (below) to dereference that `&T`.
795 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
797 trans_overloaded_op(bcx,
801 Some((ix_datum, idx.id)),
802 Some(SaveIn(scratch.val)),
804 let datum = scratch.to_expr_datum();
805 let lval = Lvalue::new("expr::trans_index overload");
806 if type_is_sized(bcx.tcx(), elt_ty) {
807 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr(lval))
809 Datum::new(datum.val, elt_ty, LvalueExpr(lval))
813 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
817 // Translate index expression and cast to a suitable LLVM integer.
818 // Rust is less strict than LLVM in this regard.
819 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
820 let ix_val = ix_datum.to_llscalarish(bcx);
821 let ix_size = machine::llbitsize_of_real(bcx.ccx(),
823 let int_size = machine::llbitsize_of_real(bcx.ccx(),
826 if ix_size < int_size {
827 if expr_ty(bcx, idx).is_signed() {
828 SExt(bcx, ix_val, ccx.int_type())
829 } else { ZExt(bcx, ix_val, ccx.int_type()) }
830 } else if ix_size > int_size {
831 Trunc(bcx, ix_val, ccx.int_type())
837 let unit_ty = base_datum.ty.sequence_element_type(bcx.tcx());
839 let (base, len) = base_datum.get_vec_base_and_len(bcx);
841 debug!("trans_index: base {}", bcx.val_to_string(base));
842 debug!("trans_index: len {}", bcx.val_to_string(len));
844 let bounds_check = ICmp(bcx,
848 index_expr_debug_loc);
849 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
850 let expected = Call(bcx,
852 &[bounds_check, C_bool(ccx, false)],
854 index_expr_debug_loc);
855 bcx = with_cond(bcx, expected, |bcx| {
856 controlflow::trans_fail_bounds_check(bcx,
857 expr_info(index_expr),
861 let elt = InBoundsGEP(bcx, base, &[ix_val]);
862 let elt = PointerCast(bcx, elt, type_of::type_of(ccx, unit_ty).ptr_to());
863 let lval = Lvalue::new("expr::trans_index fallback");
864 Datum::new(elt, unit_ty, LvalueExpr(lval))
868 DatumBlock::new(bcx, elt_datum)
871 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
872 ref_expr: &ast::Expr,
874 -> DatumBlock<'blk, 'tcx, Expr> {
875 //! Translates a reference to a path.
877 let _icx = push_ctxt("trans_def_lvalue");
879 def::DefFn(..) | def::DefMethod(..) |
880 def::DefStruct(_) | def::DefVariant(..) => {
881 let datum = trans_def_fn_unadjusted(bcx.ccx(), ref_expr, def,
882 bcx.fcx.param_substs);
883 DatumBlock::new(bcx, datum.to_expr_datum())
885 def::DefStatic(did, _) => {
886 // There are two things that may happen here:
887 // 1) If the static item is defined in this crate, it will be
888 // translated using `get_item_val`, and we return a pointer to
890 // 2) If the static item is defined in another crate then we add
891 // (or reuse) a declaration of an external global, and return a
893 let const_ty = expr_ty(bcx, ref_expr);
895 // For external constants, we don't inline.
896 let val = if did.is_local() {
899 // The LLVM global has the type of its initializer,
900 // which may not be equal to the enum's type for
902 let val = base::get_item_val(bcx.ccx(), did.node);
903 let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
904 PointerCast(bcx, val, pty)
907 base::get_extern_const(bcx.ccx(), did, const_ty)
909 let lval = Lvalue::new("expr::trans_def");
910 DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr(lval)))
912 def::DefConst(_) => {
913 bcx.sess().span_bug(ref_expr.span,
914 "constant expression should not reach expr::trans_def")
917 DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
922 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
924 -> Block<'blk, 'tcx> {
926 let _icx = push_ctxt("trans_rvalue_stmt");
928 if bcx.unreachable.get() {
932 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
935 ast::ExprParen(ref e) => {
936 trans_into(bcx, &**e, Ignore)
938 ast::ExprBreak(label_opt) => {
939 controlflow::trans_break(bcx, expr, label_opt)
941 ast::ExprAgain(label_opt) => {
942 controlflow::trans_cont(bcx, expr, label_opt)
944 ast::ExprRet(ref ex) => {
945 // Check to see if the return expression itself is reachable.
946 // This can occur when the inner expression contains a return
947 let reachable = if let Some(ref cfg) = bcx.fcx.cfg {
948 cfg.node_is_reachable(expr.id)
954 controlflow::trans_ret(bcx, expr, ex.as_ref().map(|e| &**e))
956 // If it's not reachable, just translate the inner expression
957 // directly. This avoids having to manage a return slot when
958 // it won't actually be used anyway.
959 if let &Some(ref x) = ex {
960 bcx = trans_into(bcx, &**x, Ignore);
962 // Mark the end of the block as unreachable. Once we get to
963 // a return expression, there's no more we should be doing
969 ast::ExprWhile(ref cond, ref body, _) => {
970 controlflow::trans_while(bcx, expr, &**cond, &**body)
972 ast::ExprLoop(ref body, _) => {
973 controlflow::trans_loop(bcx, expr, &**body)
975 ast::ExprAssign(ref dst, ref src) => {
976 let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
977 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
979 if bcx.fcx.type_needs_drop(dst_datum.ty) {
980 // If there are destructors involved, make sure we
981 // are copying from an rvalue, since that cannot possible
982 // alias an lvalue. We are concerned about code like:
990 // where e.g. a : Option<Foo> and a.b :
991 // Option<Foo>. In that case, freeing `a` before the
992 // assignment may also free `a.b`!
994 // We could avoid this intermediary with some analysis
995 // to determine whether `dst` may possibly own `src`.
996 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
997 let src_datum = unpack_datum!(
998 bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
999 let opt_hint_datum = dst_datum.kind.drop_flag_info.hint_datum(bcx);
1000 let opt_hint_val = opt_hint_datum.map(|d|d.to_value());
1002 // 1. Drop the data at the destination, passing the
1003 // drop-hint in case the lvalue has already been
1004 // dropped or moved.
1005 bcx = glue::drop_ty_core(bcx,
1012 // 2. We are overwriting the destination; ensure that
1013 // its drop-hint (if any) says "initialized."
1014 if let Some(hint_val) = opt_hint_val {
1015 let hint_llval = hint_val.value();
1016 let drop_needed = C_u8(bcx.fcx.ccx, adt::DTOR_NEEDED_HINT);
1017 Store(bcx, drop_needed, hint_llval);
1019 src_datum.store_to(bcx, dst_datum.val)
1021 src_datum.store_to(bcx, dst_datum.val)
1024 ast::ExprAssignOp(op, ref dst, ref src) => {
1025 trans_assign_op(bcx, expr, op, &**dst, &**src)
1027 ast::ExprInlineAsm(ref a) => {
1028 asm::trans_inline_asm(bcx, a)
1031 bcx.tcx().sess.span_bug(
1033 &format!("trans_rvalue_stmt_unadjusted reached \
1034 fall-through case: {:?}",
1040 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1043 -> Block<'blk, 'tcx> {
1044 let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
1046 let tcx = bcx.tcx();
1048 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1051 ast::ExprParen(ref e) => {
1052 trans_into(bcx, &**e, dest)
1054 ast::ExprPath(..) => {
1055 trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1057 ast::ExprIf(ref cond, ref thn, ref els) => {
1058 controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1060 ast::ExprMatch(ref discr, ref arms, _) => {
1061 _match::trans_match(bcx, expr, &**discr, &arms[..], dest)
1063 ast::ExprBlock(ref blk) => {
1064 controlflow::trans_block(bcx, &**blk, dest)
1066 ast::ExprStruct(_, ref fields, ref base) => {
1069 base.as_ref().map(|e| &**e),
1072 node_id_type(bcx, expr.id),
1075 ast::ExprRange(ref start, ref end) => {
1076 // FIXME it is just not right that we are synthesising ast nodes in
1078 fn make_field(field_name: &str, expr: P<ast::Expr>) -> ast::Field {
1080 ident: codemap::dummy_spanned(token::str_to_ident(field_name)),
1082 span: codemap::DUMMY_SP,
1086 // A range just desugars into a struct.
1087 // Note that the type of the start and end may not be the same, but
1088 // they should only differ in their lifetime, which should not matter
1090 let (did, fields, ty_params) = match (start, end) {
1091 (&Some(ref start), &Some(ref end)) => {
1093 let fields = vec![make_field("start", start.clone()),
1094 make_field("end", end.clone())];
1095 (tcx.lang_items.range_struct(), fields, vec![node_id_type(bcx, start.id)])
1097 (&Some(ref start), &None) => {
1098 // Desugar to RangeFrom
1099 let fields = vec![make_field("start", start.clone())];
1100 (tcx.lang_items.range_from_struct(), fields, vec![node_id_type(bcx, start.id)])
1102 (&None, &Some(ref end)) => {
1103 // Desugar to RangeTo
1104 let fields = vec![make_field("end", end.clone())];
1105 (tcx.lang_items.range_to_struct(), fields, vec![node_id_type(bcx, end.id)])
1108 // Desugar to RangeFull
1109 (tcx.lang_items.range_full_struct(), vec![], vec![])
1113 if let Some(did) = did {
1114 let substs = Substs::new_type(ty_params, vec![]);
1120 tcx.mk_struct(tcx.lookup_adt_def(did),
1121 tcx.mk_substs(substs)),
1124 tcx.sess.span_bug(expr.span,
1125 "No lang item for ranges (how did we get this far?)")
1128 ast::ExprTup(ref args) => {
1129 let numbered_fields: Vec<(usize, &ast::Expr)> =
1130 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1134 &numbered_fields[..],
1139 ast::ExprLit(ref lit) => {
1141 ast::LitStr(ref s, _) => {
1142 tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1147 .span_bug(expr.span,
1148 "trans_rvalue_dps_unadjusted shouldn't be \
1149 translating this type of literal")
1153 ast::ExprVec(..) | ast::ExprRepeat(..) => {
1154 tvec::trans_fixed_vstore(bcx, expr, dest)
1156 ast::ExprClosure(_, ref decl, ref body) => {
1157 let dest = match dest {
1158 SaveIn(lldest) => closure::Dest::SaveIn(bcx, lldest),
1159 Ignore => closure::Dest::Ignore(bcx.ccx())
1161 let substs = match expr_ty(bcx, expr).sty {
1162 ty::TyClosure(_, ref substs) => substs,
1164 bcx.tcx().sess.span_bug(
1166 &format!("closure expr without closure type: {:?}", t)),
1168 closure::trans_closure_expr(dest, decl, body, expr.id, substs).unwrap_or(bcx)
1170 ast::ExprCall(ref f, ref args) => {
1171 if bcx.tcx().is_method_call(expr.id) {
1172 trans_overloaded_call(bcx,
1178 callee::trans_call(bcx,
1181 callee::ArgExprs(&args[..]),
1185 ast::ExprMethodCall(_, _, ref args) => {
1186 callee::trans_method_call(bcx,
1189 callee::ArgExprs(&args[..]),
1192 ast::ExprBinary(op, ref lhs, ref rhs) => {
1193 // if not overloaded, would be RvalueDatumExpr
1194 let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1195 let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1196 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1197 Some((rhs_datum, rhs.id)), Some(dest),
1198 !ast_util::is_by_value_binop(op.node)).bcx
1200 ast::ExprUnary(op, ref subexpr) => {
1201 // if not overloaded, would be RvalueDatumExpr
1202 let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1203 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1204 arg, None, Some(dest), !ast_util::is_by_value_unop(op)).bcx
1206 ast::ExprIndex(ref base, ref idx) => {
1207 // if not overloaded, would be RvalueDatumExpr
1208 let base = unpack_datum!(bcx, trans(bcx, &**base));
1209 let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1210 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1211 Some((idx_datum, idx.id)), Some(dest), true).bcx
1213 ast::ExprCast(..) => {
1214 // Trait casts used to come this way, now they should be coercions.
1215 bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
1217 ast::ExprAssignOp(op, ref dst, ref src) => {
1218 trans_assign_op(bcx, expr, op, &**dst, &**src)
1221 bcx.tcx().sess.span_bug(
1223 &format!("trans_rvalue_dps_unadjusted reached fall-through \
1230 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1231 ref_expr: &ast::Expr,
1234 -> Block<'blk, 'tcx> {
1235 let _icx = push_ctxt("trans_def_dps_unadjusted");
1237 let lldest = match dest {
1238 SaveIn(lldest) => lldest,
1239 Ignore => { return bcx; }
1243 def::DefVariant(tid, vid, _) => {
1244 let variant = bcx.tcx().lookup_adt_def(tid).variant_with_id(vid);
1245 if let ty::VariantKind::Tuple = variant.kind() {
1247 let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
1248 ExprId(ref_expr.id),
1249 bcx.fcx.param_substs).val;
1250 Store(bcx, llfn, lldest);
1254 let ty = expr_ty(bcx, ref_expr);
1255 let repr = adt::represent_type(bcx.ccx(), ty);
1256 adt::trans_set_discr(bcx, &*repr, lldest, variant.disr_val);
1260 def::DefStruct(_) => {
1261 let ty = expr_ty(bcx, ref_expr);
1263 ty::TyStruct(def, _) if def.has_dtor() => {
1264 let repr = adt::represent_type(bcx.ccx(), ty);
1265 adt::trans_set_discr(bcx, &*repr, lldest, 0);
1272 bcx.tcx().sess.span_bug(ref_expr.span, &format!(
1273 "Non-DPS def {:?} referened by {}",
1274 def, bcx.node_id_to_string(ref_expr.id)));
1279 pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1280 ref_expr: &ast::Expr,
1282 param_substs: &'tcx Substs<'tcx>)
1283 -> Datum<'tcx, Rvalue> {
1284 let _icx = push_ctxt("trans_def_datum_unadjusted");
1287 def::DefFn(did, _) |
1288 def::DefStruct(did) | def::DefVariant(_, did, _) => {
1289 callee::trans_fn_ref(ccx, did, ExprId(ref_expr.id), param_substs)
1291 def::DefMethod(method_did) => {
1292 match ccx.tcx().impl_or_trait_item(method_did).container() {
1293 ty::ImplContainer(_) => {
1294 callee::trans_fn_ref(ccx, method_did,
1295 ExprId(ref_expr.id),
1298 ty::TraitContainer(trait_did) => {
1299 meth::trans_static_method_callee(ccx, method_did,
1300 trait_did, ref_expr.id,
1306 ccx.tcx().sess.span_bug(ref_expr.span, &format!(
1307 "trans_def_fn_unadjusted invoked on: {:?} for {:?}",
1314 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1315 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1317 -> Datum<'tcx, Lvalue> {
1318 let _icx = push_ctxt("trans_local_var");
1321 def::DefUpvar(nid, _) => {
1322 // Can't move upvars, so this is never a ZeroMemLastUse.
1323 let local_ty = node_id_type(bcx, nid);
1324 let lval = Lvalue::new_with_hint("expr::trans_local_var (upvar)",
1325 bcx, nid, HintKind::ZeroAndMaintain);
1326 match bcx.fcx.llupvars.borrow().get(&nid) {
1327 Some(&val) => Datum::new(val, local_ty, lval),
1329 bcx.sess().bug(&format!(
1330 "trans_local_var: no llval for upvar {} found",
1335 def::DefLocal(nid) => {
1336 let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1339 bcx.sess().bug(&format!(
1340 "trans_local_var: no datum for local/arg {} found",
1344 debug!("take_local(nid={}, v={}, ty={})",
1345 nid, bcx.val_to_string(datum.val), datum.ty);
1349 bcx.sess().unimpl(&format!(
1350 "unsupported def type in trans_local_var: {:?}",
1356 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1357 fields: &[ast::Field],
1358 base: Option<&ast::Expr>,
1359 expr_span: codemap::Span,
1360 expr_id: ast::NodeId,
1362 dest: Dest) -> Block<'blk, 'tcx> {
1363 let _icx = push_ctxt("trans_rec");
1365 let tcx = bcx.tcx();
1366 let vinfo = VariantInfo::of_node(tcx, ty, expr_id);
1368 let mut need_base = vec![true; vinfo.fields.len()];
1370 let numbered_fields = fields.iter().map(|field| {
1371 let pos = vinfo.field_index(field.ident.node.name);
1372 need_base[pos] = false;
1374 }).collect::<Vec<_>>();
1376 let optbase = match base {
1377 Some(base_expr) => {
1378 let mut leftovers = Vec::new();
1379 for (i, b) in need_base.iter().enumerate() {
1381 leftovers.push((i, vinfo.fields[i].1));
1384 Some(StructBaseInfo {expr: base_expr,
1385 fields: leftovers })
1388 if need_base.iter().any(|b| *b) {
1389 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1401 DebugLoc::At(expr_id, expr_span))
1404 /// Information that `trans_adt` needs in order to fill in the fields
1405 /// of a struct copied from a base struct (e.g., from an expression
1406 /// like `Foo { a: b, ..base }`.
1408 /// Note that `fields` may be empty; the base expression must always be
1409 /// evaluated for side-effects.
1410 pub struct StructBaseInfo<'a, 'tcx> {
1411 /// The base expression; will be evaluated after all explicit fields.
1412 expr: &'a ast::Expr,
1413 /// The indices of fields to copy paired with their types.
1414 fields: Vec<(usize, Ty<'tcx>)>
1417 /// Constructs an ADT instance:
1419 /// - `fields` should be a list of field indices paired with the
1420 /// expression to store into that field. The initializers will be
1421 /// evaluated in the order specified by `fields`.
1423 /// - `optbase` contains information on the base struct (if any) from
1424 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1425 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1428 fields: &[(usize, &ast::Expr)],
1429 optbase: Option<StructBaseInfo<'a, 'tcx>>,
1431 debug_location: DebugLoc)
1432 -> Block<'blk, 'tcx> {
1433 let _icx = push_ctxt("trans_adt");
1435 let repr = adt::represent_type(bcx.ccx(), ty);
1437 debug_location.apply(bcx.fcx);
1439 // If we don't care about the result, just make a
1440 // temporary stack slot
1441 let addr = match dest {
1443 Ignore => alloc_ty(bcx, ty, "temp"),
1446 // This scope holds intermediates that must be cleaned should
1447 // panic occur before the ADT as a whole is ready.
1448 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1451 // Issue 23112: The original logic appeared vulnerable to same
1452 // order-of-eval bug. But, SIMD values are tuple-structs;
1453 // i.e. functional record update (FRU) syntax is unavailable.
1455 // To be safe, double-check that we did not get here via FRU.
1456 assert!(optbase.is_none());
1458 // This is the constructor of a SIMD type, such types are
1459 // always primitive machine types and so do not have a
1460 // destructor or require any clean-up.
1461 let llty = type_of::type_of(bcx.ccx(), ty);
1463 // keep a vector as a register, and running through the field
1464 // `insertelement`ing them directly into that register
1465 // (i.e. avoid GEPi and `store`s to an alloca) .
1466 let mut vec_val = C_undef(llty);
1468 for &(i, ref e) in fields {
1469 let block_datum = trans(bcx, &**e);
1470 bcx = block_datum.bcx;
1471 let position = C_uint(bcx.ccx(), i);
1472 let value = block_datum.datum.to_llscalarish(bcx);
1473 vec_val = InsertElement(bcx, vec_val, value, position);
1475 Store(bcx, vec_val, addr);
1476 } else if let Some(base) = optbase {
1477 // Issue 23112: If there is a base, then order-of-eval
1478 // requires field expressions eval'ed before base expression.
1480 // First, trans field expressions to temporary scratch values.
1481 let scratch_vals: Vec<_> = fields.iter().map(|&(i, ref e)| {
1482 let datum = unpack_datum!(bcx, trans(bcx, &**e));
1486 debug_location.apply(bcx.fcx);
1488 // Second, trans the base to the dest.
1489 assert_eq!(discr, 0);
1491 match expr_kind(bcx.tcx(), &*base.expr) {
1492 ExprKind::RvalueDps | ExprKind::RvalueDatum if !bcx.fcx.type_needs_drop(ty) => {
1493 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1495 ExprKind::RvalueStmt => {
1496 bcx.tcx().sess.bug("unexpected expr kind for struct base expr")
1499 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1500 for &(i, t) in &base.fields {
1501 let datum = base_datum.get_element(
1502 bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1503 assert!(type_is_sized(bcx.tcx(), datum.ty));
1504 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1505 bcx = datum.store_to(bcx, dest);
1510 // Finally, move scratch field values into actual field locations
1511 for (i, datum) in scratch_vals {
1512 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1513 bcx = datum.store_to(bcx, dest);
1516 // No base means we can write all fields directly in place.
1517 for &(i, ref e) in fields {
1518 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1519 let e_ty = expr_ty_adjusted(bcx, &**e);
1520 bcx = trans_into(bcx, &**e, SaveIn(dest));
1521 let scope = cleanup::CustomScope(custom_cleanup_scope);
1522 fcx.schedule_lifetime_end(scope, dest);
1523 // FIXME: nonzeroing move should generalize to fields
1524 fcx.schedule_drop_mem(scope, dest, e_ty, None);
1528 adt::trans_set_discr(bcx, &*repr, addr, discr);
1530 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1532 // If we don't care about the result drop the temporary we made
1536 bcx = glue::drop_ty(bcx, addr, ty, debug_location);
1537 base::call_lifetime_end(bcx, addr);
1544 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1547 -> DatumBlock<'blk, 'tcx, Expr> {
1548 // must not be a string constant, that is a RvalueDpsExpr
1549 let _icx = push_ctxt("trans_immediate_lit");
1550 let ty = expr_ty(bcx, expr);
1551 let v = consts::const_lit(bcx.ccx(), expr, lit);
1552 immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1555 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1558 sub_expr: &ast::Expr)
1559 -> DatumBlock<'blk, 'tcx, Expr> {
1560 let ccx = bcx.ccx();
1562 let _icx = push_ctxt("trans_unary_datum");
1564 let method_call = MethodCall::expr(expr.id);
1566 // The only overloaded operator that is translated to a datum
1567 // is an overloaded deref, since it is always yields a `&T`.
1568 // Otherwise, we should be in the RvalueDpsExpr path.
1569 assert!(op == ast::UnDeref || !ccx.tcx().is_method_call(expr.id));
1571 let un_ty = expr_ty(bcx, expr);
1573 let debug_loc = expr.debug_loc();
1577 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1578 let llresult = Not(bcx, datum.to_llscalarish(bcx), debug_loc);
1579 immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1582 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1583 let val = datum.to_llscalarish(bcx);
1584 let (bcx, llneg) = {
1586 let result = FNeg(bcx, val, debug_loc);
1589 let is_signed = un_ty.is_signed();
1590 let result = Neg(bcx, val, debug_loc);
1591 let bcx = if bcx.ccx().check_overflow() && is_signed {
1592 let (llty, min) = base::llty_and_min_for_signed_ty(bcx, un_ty);
1593 let is_min = ICmp(bcx, llvm::IntEQ, val,
1594 C_integral(llty, min, true), debug_loc);
1595 with_cond(bcx, is_min, |bcx| {
1596 let msg = InternedString::new(
1597 "attempted to negate with overflow");
1598 controlflow::trans_fail(bcx, expr_info(expr), msg)
1606 immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1609 trans_uniq_expr(bcx, expr, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1612 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1613 deref_once(bcx, expr, datum, method_call)
1618 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1619 box_expr: &ast::Expr,
1621 contents: &ast::Expr,
1622 contents_ty: Ty<'tcx>)
1623 -> DatumBlock<'blk, 'tcx, Expr> {
1624 let _icx = push_ctxt("trans_uniq_expr");
1626 assert!(type_is_sized(bcx.tcx(), contents_ty));
1627 let llty = type_of::type_of(bcx.ccx(), contents_ty);
1628 let size = llsize_of(bcx.ccx(), llty);
1629 let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1630 let llty_ptr = llty.ptr_to();
1631 let Result { bcx, val } = malloc_raw_dyn(bcx,
1636 box_expr.debug_loc());
1637 // Unique boxes do not allocate for zero-size types. The standard library
1638 // may assume that `free` is never called on the pointer returned for
1639 // `Box<ZeroSizeType>`.
1640 let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1641 trans_into(bcx, contents, SaveIn(val))
1643 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1644 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1645 val, cleanup::HeapExchange, contents_ty);
1646 let bcx = trans_into(bcx, contents, SaveIn(val));
1647 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1650 immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1653 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1654 lval: Datum<'tcx, Lvalue>)
1655 -> DatumBlock<'blk, 'tcx, Expr> {
1656 let dest_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), lval.ty);
1657 let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
1658 memcpy_ty(bcx, scratch.val, lval.val, scratch.ty);
1660 DatumBlock::new(bcx, scratch.to_expr_datum())
1663 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1665 subexpr: &ast::Expr)
1666 -> DatumBlock<'blk, 'tcx, Expr> {
1667 let _icx = push_ctxt("trans_addr_of");
1669 let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1670 if !type_is_sized(bcx.tcx(), sub_datum.ty) {
1671 // DST lvalue, close to a fat pointer
1672 ref_fat_ptr(bcx, sub_datum)
1674 // Sized value, ref to a thin pointer
1675 let ty = expr_ty(bcx, expr);
1676 immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1680 // Important to get types for both lhs and rhs, because one might be _|_
1681 // and the other not.
1682 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1683 binop_expr: &ast::Expr,
1690 -> DatumBlock<'blk, 'tcx, Expr> {
1691 let _icx = push_ctxt("trans_eager_binop");
1693 let tcx = bcx.tcx();
1694 let is_simd = lhs_t.is_simd();
1695 let intype = if is_simd {
1696 lhs_t.simd_type(tcx)
1700 let is_float = intype.is_fp();
1701 let is_signed = intype.is_signed();
1702 let info = expr_info(binop_expr);
1704 let binop_debug_loc = binop_expr.debug_loc();
1707 let val = match op.node {
1710 FAdd(bcx, lhs, rhs, binop_debug_loc)
1712 Add(bcx, lhs, rhs, binop_debug_loc)
1714 let (newbcx, res) = with_overflow_check(
1715 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1722 FSub(bcx, lhs, rhs, binop_debug_loc)
1724 Sub(bcx, lhs, rhs, binop_debug_loc)
1726 let (newbcx, res) = with_overflow_check(
1727 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1734 FMul(bcx, lhs, rhs, binop_debug_loc)
1736 Mul(bcx, lhs, rhs, binop_debug_loc)
1738 let (newbcx, res) = with_overflow_check(
1739 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1746 FDiv(bcx, lhs, rhs, binop_debug_loc)
1748 // Only zero-check integers; fp /0 is NaN
1749 bcx = base::fail_if_zero_or_overflows(bcx,
1750 expr_info(binop_expr),
1756 SDiv(bcx, lhs, rhs, binop_debug_loc)
1758 UDiv(bcx, lhs, rhs, binop_debug_loc)
1764 // LLVM currently always lowers the `frem` instructions appropriate
1765 // library calls typically found in libm. Notably f64 gets wired up
1766 // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
1767 // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
1768 // instead just an inline function in a header that goes up to a
1769 // f64, uses `fmod`, and then comes back down to a f32.
1771 // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
1772 // still unconditionally lower frem instructions over 32-bit floats
1773 // to a call to `fmodf`. To work around this we special case MSVC
1774 // 32-bit float rem instructions and instead do the call out to
1775 // `fmod` ourselves.
1777 // Note that this is currently duplicated with src/libcore/ops.rs
1778 // which does the same thing, and it would be nice to perhaps unify
1779 // these two implementations on day! Also note that we call `fmod`
1780 // for both 32 and 64-bit floats because if we emit any FRem
1781 // instruction at all then LLVM is capable of optimizing it into a
1782 // 32-bit FRem (which we're trying to avoid).
1783 let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
1784 tcx.sess.target.target.arch == "x86";
1786 let f64t = Type::f64(bcx.ccx());
1787 let fty = Type::func(&[f64t, f64t], &f64t);
1788 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty,
1790 if lhs_t == tcx.types.f32 {
1791 let lhs = FPExt(bcx, lhs, f64t);
1792 let rhs = FPExt(bcx, rhs, f64t);
1793 let res = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
1794 FPTrunc(bcx, res, Type::f32(bcx.ccx()))
1796 Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc)
1799 FRem(bcx, lhs, rhs, binop_debug_loc)
1802 // Only zero-check integers; fp %0 is NaN
1803 bcx = base::fail_if_zero_or_overflows(bcx,
1804 expr_info(binop_expr),
1805 op, lhs, rhs, rhs_t);
1807 SRem(bcx, lhs, rhs, binop_debug_loc)
1809 URem(bcx, lhs, rhs, binop_debug_loc)
1813 ast::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1814 ast::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1815 ast::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1817 let (newbcx, res) = with_overflow_check(
1818 bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1823 let (newbcx, res) = with_overflow_check(
1824 bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1828 ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1830 base::compare_simd_types(bcx, lhs, rhs, intype, val_ty(lhs), op.node, binop_debug_loc)
1832 base::compare_scalar_types(bcx, lhs, rhs, intype, op.node, binop_debug_loc)
1836 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1840 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1843 // refinement types would obviate the need for this
1844 enum lazy_binop_ty {
1849 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1850 binop_expr: &ast::Expr,
1854 -> DatumBlock<'blk, 'tcx, Expr> {
1855 let _icx = push_ctxt("trans_lazy_binop");
1856 let binop_ty = expr_ty(bcx, binop_expr);
1859 let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1860 let lhs = lhs.to_llscalarish(past_lhs);
1862 if past_lhs.unreachable.get() {
1863 return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1866 let join = fcx.new_id_block("join", binop_expr.id);
1867 let before_rhs = fcx.new_id_block("before_rhs", b.id);
1870 lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1871 lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1874 let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1875 let rhs = rhs.to_llscalarish(past_rhs);
1877 if past_rhs.unreachable.get() {
1878 return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1881 Br(past_rhs, join.llbb, DebugLoc::None);
1882 let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1883 &[past_lhs.llbb, past_rhs.llbb]);
1885 return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1888 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1893 -> DatumBlock<'blk, 'tcx, Expr> {
1894 let _icx = push_ctxt("trans_binary");
1895 let ccx = bcx.ccx();
1897 // if overloaded, would be RvalueDpsExpr
1898 assert!(!ccx.tcx().is_method_call(expr.id));
1902 trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1905 trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1909 let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1910 let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1911 let binop_ty = expr_ty(bcx, expr);
1913 debug!("trans_binary (expr {}): lhs_datum={}",
1915 lhs_datum.to_string(ccx));
1916 let lhs_ty = lhs_datum.ty;
1917 let lhs = lhs_datum.to_llscalarish(bcx);
1919 debug!("trans_binary (expr {}): rhs_datum={}",
1921 rhs_datum.to_string(ccx));
1922 let rhs_ty = rhs_datum.ty;
1923 let rhs = rhs_datum.to_llscalarish(bcx);
1924 trans_eager_binop(bcx, expr, binop_ty, op,
1925 lhs_ty, lhs, rhs_ty, rhs)
1930 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1932 method_call: MethodCall,
1933 lhs: Datum<'tcx, Expr>,
1934 rhs: Option<(Datum<'tcx, Expr>, ast::NodeId)>,
1937 -> Result<'blk, 'tcx> {
1938 callee::trans_call_inner(bcx,
1940 |bcx, arg_cleanup_scope| {
1941 meth::trans_method_callee(bcx,
1946 callee::ArgOverloadedOp(lhs, rhs, autoref),
1950 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1952 callee: &'a ast::Expr,
1953 args: &'a [P<ast::Expr>],
1955 -> Block<'blk, 'tcx> {
1956 debug!("trans_overloaded_call {}", expr.id);
1957 let method_call = MethodCall::expr(expr.id);
1958 let mut all_args = vec!(callee);
1959 all_args.extend(args.iter().map(|e| &**e));
1961 callee::trans_call_inner(bcx,
1963 |bcx, arg_cleanup_scope| {
1964 meth::trans_method_callee(
1970 callee::ArgOverloadedCall(all_args),
1975 pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
1980 if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
1984 match (t_in.builtin_deref(true), t_out.builtin_deref(true)) {
1985 (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
1989 // This condition isn't redundant with the check for CoercionCast:
1990 // different types can be substituted into the same type, and
1991 // == equality can be overconservative if there are regions.
1997 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2000 -> DatumBlock<'blk, 'tcx, Expr>
2002 use middle::cast::CastTy::*;
2003 use middle::cast::IntTy::*;
2005 fn int_cast(bcx: Block,
2012 let _icx = push_ctxt("int_cast");
2013 let srcsz = llsrctype.int_width();
2014 let dstsz = lldsttype.int_width();
2015 return if dstsz == srcsz {
2016 BitCast(bcx, llsrc, lldsttype)
2017 } else if srcsz > dstsz {
2018 TruncOrBitCast(bcx, llsrc, lldsttype)
2020 SExtOrBitCast(bcx, llsrc, lldsttype)
2022 ZExtOrBitCast(bcx, llsrc, lldsttype)
2026 fn float_cast(bcx: Block,
2032 let _icx = push_ctxt("float_cast");
2033 let srcsz = llsrctype.float_width();
2034 let dstsz = lldsttype.float_width();
2035 return if dstsz > srcsz {
2036 FPExt(bcx, llsrc, lldsttype)
2037 } else if srcsz > dstsz {
2038 FPTrunc(bcx, llsrc, lldsttype)
2042 let _icx = push_ctxt("trans_cast");
2044 let ccx = bcx.ccx();
2046 let t_in = expr_ty_adjusted(bcx, expr);
2047 let t_out = node_id_type(bcx, id);
2049 debug!("trans_cast({:?} as {:?})", t_in, t_out);
2050 let mut ll_t_in = type_of::arg_type_of(ccx, t_in);
2051 let ll_t_out = type_of::arg_type_of(ccx, t_out);
2052 // Convert the value to be cast into a ValueRef, either by-ref or
2053 // by-value as appropriate given its type:
2054 let mut datum = unpack_datum!(bcx, trans(bcx, expr));
2056 let datum_ty = monomorphize_type(bcx, datum.ty);
2058 if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
2060 return DatumBlock::new(bcx, datum);
2063 if type_is_fat_ptr(bcx.tcx(), t_in) {
2064 assert!(datum.kind.is_by_ref());
2065 if type_is_fat_ptr(bcx.tcx(), t_out) {
2066 return DatumBlock::new(bcx, Datum::new(
2067 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
2070 )).to_expr_datumblock();
2072 // Return the address
2073 return immediate_rvalue_bcx(bcx,
2075 Load(bcx, get_dataptr(bcx, datum.val)),
2077 t_out).to_expr_datumblock();
2081 let r_t_in = CastTy::from_ty(t_in).expect("bad input type for cast");
2082 let r_t_out = CastTy::from_ty(t_out).expect("bad output type for cast");
2084 let (llexpr, signed) = if let Int(CEnum) = r_t_in {
2085 let repr = adt::represent_type(ccx, t_in);
2086 let datum = unpack_datum!(
2087 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2088 let llexpr_ptr = datum.to_llref();
2089 let discr = adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2090 ll_t_in = val_ty(discr);
2091 (discr, adt::is_discr_signed(&*repr))
2093 (datum.to_llscalarish(bcx), t_in.is_signed())
2096 let newval = match (r_t_in, r_t_out) {
2097 (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
2098 PointerCast(bcx, llexpr, ll_t_out)
2100 (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
2101 (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
2103 (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
2104 (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
2105 (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
2106 (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
2107 (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
2108 (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
2110 _ => ccx.sess().span_bug(expr.span,
2111 &format!("translating unsupported cast: \
2117 return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2120 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2125 -> Block<'blk, 'tcx> {
2126 let _icx = push_ctxt("trans_assign_op");
2129 debug!("trans_assign_op(expr={:?})", expr);
2131 // User-defined operator methods cannot be used with `+=` etc right now
2132 assert!(!bcx.tcx().is_method_call(expr.id));
2134 // Evaluate LHS (destination), which should be an lvalue
2135 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2136 assert!(!bcx.fcx.type_needs_drop(dst_datum.ty));
2137 let dst_ty = dst_datum.ty;
2138 let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2141 let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2142 let rhs_ty = rhs_datum.ty;
2143 let rhs = rhs_datum.to_llscalarish(bcx);
2145 // Perform computation and store the result
2146 let result_datum = unpack_datum!(
2147 bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2148 dst_ty, dst, rhs_ty, rhs));
2149 return result_datum.store_to(bcx, dst_datum.val);
2152 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2153 datum: Datum<'tcx, Expr>,
2155 -> DatumBlock<'blk, 'tcx, Expr> {
2158 // Ensure cleanup of `datum` if not already scheduled and obtain
2159 // a "by ref" pointer.
2160 let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2162 // Compute final type. Note that we are loose with the region and
2163 // mutability, since those things don't matter in trans.
2164 let referent_ty = lv_datum.ty;
2165 let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2168 let llref = lv_datum.to_llref();
2170 // Construct the resulting datum, using what was the "by ref"
2171 // ValueRef of type `referent_ty` to be the "by value" ValueRef
2172 // of type `&referent_ty`.
2173 // Pointers to DST types are non-immediate, and therefore still use ByRef.
2174 let kind = if type_is_sized(bcx.tcx(), referent_ty) { ByValue } else { ByRef };
2175 DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(kind))))
2178 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2180 datum: Datum<'tcx, Expr>,
2182 -> DatumBlock<'blk, 'tcx, Expr> {
2184 let mut datum = datum;
2186 let method_call = MethodCall::autoderef(expr.id, i as u32);
2187 datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2189 DatumBlock { bcx: bcx, datum: datum }
2192 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2194 datum: Datum<'tcx, Expr>,
2195 method_call: MethodCall)
2196 -> DatumBlock<'blk, 'tcx, Expr> {
2197 let ccx = bcx.ccx();
2199 debug!("deref_once(expr={:?}, datum={}, method_call={:?})",
2201 datum.to_string(ccx),
2206 // Check for overloaded deref.
2207 let method_ty = ccx.tcx()
2211 .get(&method_call).map(|method| method.ty);
2213 let datum = match method_ty {
2214 Some(method_ty) => {
2215 let method_ty = monomorphize_type(bcx, method_ty);
2217 // Overloaded. Evaluate `trans_overloaded_op`, which will
2218 // invoke the user's deref() method, which basically
2219 // converts from the `Smaht<T>` pointer that we have into
2220 // a `&T` pointer. We can then proceed down the normal
2221 // path (below) to dereference that `&T`.
2222 let datum = if method_call.autoderef == 0 {
2225 // Always perform an AutoPtr when applying an overloaded auto-deref
2226 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2229 let ref_ty = // invoked methods have their LB regions instantiated
2230 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2231 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2233 unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2234 datum, None, Some(SaveIn(scratch.val)),
2236 scratch.to_expr_datum()
2239 // Not overloaded. We already have a pointer we know how to deref.
2244 let r = match datum.ty.sty {
2245 ty::TyBox(content_ty) => {
2246 // Make sure we have an lvalue datum here to get the
2247 // proper cleanups scheduled
2248 let datum = unpack_datum!(
2249 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2251 if type_is_sized(bcx.tcx(), content_ty) {
2252 let ptr = load_ty(bcx, datum.val, datum.ty);
2253 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(datum.kind)))
2255 // A fat pointer and a DST lvalue have the same representation
2256 // just different types. Since there is no temporary for `*e`
2257 // here (because it is unsized), we cannot emulate the sized
2258 // object code path for running drop glue and free. Instead,
2259 // we schedule cleanup for `e`, turning it into an lvalue.
2261 let lval = Lvalue::new("expr::deref_once ty_uniq");
2262 let datum = Datum::new(datum.val, content_ty, LvalueExpr(lval));
2263 DatumBlock::new(bcx, datum)
2267 ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
2268 ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
2269 let lval = Lvalue::new("expr::deref_once ptr");
2270 if type_is_sized(bcx.tcx(), content_ty) {
2271 let ptr = datum.to_llscalarish(bcx);
2273 // Always generate an lvalue datum, even if datum.mode is
2274 // an rvalue. This is because datum.mode is only an
2275 // rvalue for non-owning pointers like &T or *T, in which
2276 // case cleanup *is* scheduled elsewhere, by the true
2277 // owner (or, in the case of *T, by the user).
2278 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(lval)))
2280 // A fat pointer and a DST lvalue have the same representation
2281 // just different types.
2282 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr(lval)))
2287 bcx.tcx().sess.span_bug(
2289 &format!("deref invoked on expr of invalid type {:?}",
2294 debug!("deref_once(expr={}, method_call={:?}, result={})",
2295 expr.id, method_call, r.datum.to_string(ccx));
2310 fn codegen_strategy(&self) -> OverflowCodegen {
2311 use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2313 OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2314 OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2315 OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2317 OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2318 OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2323 enum OverflowCodegen {
2324 ViaIntrinsic(OverflowOpViaIntrinsic),
2325 ViaInputCheck(OverflowOpViaInputCheck),
2328 enum OverflowOpViaInputCheck { Shl, Shr, }
2331 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2333 impl OverflowOpViaIntrinsic {
2334 fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2335 let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2336 bcx.ccx().get_intrinsic(&name)
2338 fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str {
2339 use syntax::ast::IntTy::*;
2340 use syntax::ast::UintTy::*;
2341 use middle::ty::{TyInt, TyUint};
2343 let new_sty = match ty.sty {
2344 TyInt(TyIs) => match &tcx.sess.target.target.target_pointer_width[..] {
2345 "32" => TyInt(TyI32),
2346 "64" => TyInt(TyI64),
2347 _ => panic!("unsupported target word size")
2349 TyUint(TyUs) => match &tcx.sess.target.target.target_pointer_width[..] {
2350 "32" => TyUint(TyU32),
2351 "64" => TyUint(TyU64),
2352 _ => panic!("unsupported target word size")
2354 ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2355 _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2360 OverflowOpViaIntrinsic::Add => match new_sty {
2361 TyInt(TyI8) => "llvm.sadd.with.overflow.i8",
2362 TyInt(TyI16) => "llvm.sadd.with.overflow.i16",
2363 TyInt(TyI32) => "llvm.sadd.with.overflow.i32",
2364 TyInt(TyI64) => "llvm.sadd.with.overflow.i64",
2366 TyUint(TyU8) => "llvm.uadd.with.overflow.i8",
2367 TyUint(TyU16) => "llvm.uadd.with.overflow.i16",
2368 TyUint(TyU32) => "llvm.uadd.with.overflow.i32",
2369 TyUint(TyU64) => "llvm.uadd.with.overflow.i64",
2371 _ => unreachable!(),
2373 OverflowOpViaIntrinsic::Sub => match new_sty {
2374 TyInt(TyI8) => "llvm.ssub.with.overflow.i8",
2375 TyInt(TyI16) => "llvm.ssub.with.overflow.i16",
2376 TyInt(TyI32) => "llvm.ssub.with.overflow.i32",
2377 TyInt(TyI64) => "llvm.ssub.with.overflow.i64",
2379 TyUint(TyU8) => "llvm.usub.with.overflow.i8",
2380 TyUint(TyU16) => "llvm.usub.with.overflow.i16",
2381 TyUint(TyU32) => "llvm.usub.with.overflow.i32",
2382 TyUint(TyU64) => "llvm.usub.with.overflow.i64",
2384 _ => unreachable!(),
2386 OverflowOpViaIntrinsic::Mul => match new_sty {
2387 TyInt(TyI8) => "llvm.smul.with.overflow.i8",
2388 TyInt(TyI16) => "llvm.smul.with.overflow.i16",
2389 TyInt(TyI32) => "llvm.smul.with.overflow.i32",
2390 TyInt(TyI64) => "llvm.smul.with.overflow.i64",
2392 TyUint(TyU8) => "llvm.umul.with.overflow.i8",
2393 TyUint(TyU16) => "llvm.umul.with.overflow.i16",
2394 TyUint(TyU32) => "llvm.umul.with.overflow.i32",
2395 TyUint(TyU64) => "llvm.umul.with.overflow.i64",
2397 _ => unreachable!(),
2402 fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2403 info: NodeIdAndSpan,
2404 lhs_t: Ty<'tcx>, lhs: ValueRef,
2406 binop_debug_loc: DebugLoc)
2407 -> (Block<'blk, 'tcx>, ValueRef) {
2408 let llfn = self.to_intrinsic(bcx, lhs_t);
2410 let val = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
2411 let result = ExtractValue(bcx, val, 0); // iN operation result
2412 let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2414 let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2417 let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2418 Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2419 None, binop_debug_loc);
2422 base::with_cond(bcx, cond, |bcx|
2423 controlflow::trans_fail(bcx, info,
2424 InternedString::new("arithmetic operation overflowed")));
2430 impl OverflowOpViaInputCheck {
2431 fn build_with_input_check<'blk, 'tcx>(&self,
2432 bcx: Block<'blk, 'tcx>,
2433 info: NodeIdAndSpan,
2437 binop_debug_loc: DebugLoc)
2438 -> (Block<'blk, 'tcx>, ValueRef)
2440 let lhs_llty = val_ty(lhs);
2441 let rhs_llty = val_ty(rhs);
2443 // Panic if any bits are set outside of bits that we always
2446 // Note that the mask's value is derived from the LHS type
2447 // (since that is where the 32/64 distinction is relevant) but
2448 // the mask's type must match the RHS type (since they will
2449 // both be fed into a and-binop)
2450 let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2452 let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2453 let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2454 let result = match *self {
2455 OverflowOpViaInputCheck::Shl =>
2456 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2457 OverflowOpViaInputCheck::Shr =>
2458 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2461 base::with_cond(bcx, cond, |bcx|
2462 controlflow::trans_fail(bcx, info,
2463 InternedString::new("shift operation overflowed")));
2469 fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2472 invert: bool) -> ValueRef {
2473 let kind = llty.kind();
2475 TypeKind::Integer => {
2476 // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
2477 let val = llty.int_width() - 1;
2479 C_integral(mask_llty, !val, true)
2481 C_integral(mask_llty, val, false)
2484 TypeKind::Vector => {
2485 let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
2486 VectorSplat(bcx, mask_llty.vector_length(), mask)
2488 _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
2492 // Check if an integer or vector contains a nonzero element.
2493 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2495 binop_debug_loc: DebugLoc) -> ValueRef {
2496 let llty = val_ty(value);
2497 let kind = llty.kind();
2499 TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2500 TypeKind::Vector => {
2501 // Check if any elements of the vector are nonzero by treating
2502 // it as a wide integer and checking if the integer is nonzero.
2503 let width = llty.vector_length() as u64 * llty.element_type().int_width();
2504 let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2505 build_nonzero_check(bcx, int_value, binop_debug_loc)
2507 _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2511 // To avoid UB from LLVM, these two functions mask RHS with an
2512 // appropriate mask unconditionally (i.e. the fallback behavior for
2513 // all shifts). For 32- and 64-bit types, this matches the semantics
2514 // of Java. (See related discussion on #1877 and #10183.)
2516 fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2519 binop_debug_loc: DebugLoc) -> ValueRef {
2520 let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShl, lhs, rhs);
2521 // #1877, #10183: Ensure that input is always valid
2522 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2523 Shl(bcx, lhs, rhs, binop_debug_loc)
2526 fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2530 binop_debug_loc: DebugLoc) -> ValueRef {
2531 let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShr, lhs, rhs);
2532 // #1877, #10183: Ensure that input is always valid
2533 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2534 let tcx = bcx.tcx();
2535 let is_simd = lhs_t.is_simd();
2536 let intype = if is_simd {
2537 lhs_t.simd_type(tcx)
2541 let is_signed = intype.is_signed();
2543 AShr(bcx, lhs, rhs, binop_debug_loc)
2545 LShr(bcx, lhs, rhs, binop_debug_loc)
2549 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2551 debug_loc: DebugLoc) -> ValueRef {
2552 let rhs_llty = val_ty(rhs);
2553 And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
2556 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2557 lhs_t: Ty<'tcx>, lhs: ValueRef,
2559 binop_debug_loc: DebugLoc)
2560 -> (Block<'blk, 'tcx>, ValueRef) {
2561 if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2562 if bcx.ccx().check_overflow() {
2564 match oop.codegen_strategy() {
2565 OverflowCodegen::ViaIntrinsic(oop) =>
2566 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2567 OverflowCodegen::ViaInputCheck(oop) =>
2568 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2571 let res = match oop {
2572 OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2573 OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2574 OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2577 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2579 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2585 /// We categorize expressions into three kinds. The distinction between
2586 /// lvalue/rvalue is fundamental to the language. The distinction between the
2587 /// two kinds of rvalues is an artifact of trans which reflects how we will
2588 /// generate code for that kind of expression. See trans/expr.rs for more
2590 #[derive(Copy, Clone)]
2598 fn expr_kind(tcx: &ty::ctxt, expr: &ast::Expr) -> ExprKind {
2599 if tcx.is_method_call(expr.id) {
2600 // Overloaded operations are generally calls, and hence they are
2601 // generated via DPS, but there are a few exceptions:
2602 return match expr.node {
2603 // `a += b` has a unit result.
2604 ast::ExprAssignOp(..) => ExprKind::RvalueStmt,
2606 // the deref method invoked for `*a` always yields an `&T`
2607 ast::ExprUnary(ast::UnDeref, _) => ExprKind::Lvalue,
2609 // the index method invoked for `a[i]` always yields an `&T`
2610 ast::ExprIndex(..) => ExprKind::Lvalue,
2612 // in the general case, result could be any type, use DPS
2613 _ => ExprKind::RvalueDps
2618 ast::ExprPath(..) => {
2619 match tcx.resolve_expr(expr) {
2620 def::DefStruct(_) | def::DefVariant(..) => {
2621 if let ty::TyBareFn(..) = tcx.node_id_to_type(expr.id).sty {
2623 ExprKind::RvalueDatum
2629 // Special case: A unit like struct's constructor must be called without () at the
2630 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
2631 // of unit structs this is should not be interpreted as function pointer but as
2632 // call to the constructor.
2633 def::DefFn(_, true) => ExprKind::RvalueDps,
2635 // Fn pointers are just scalar values.
2636 def::DefFn(..) | def::DefMethod(..) => ExprKind::RvalueDatum,
2638 // Note: there is actually a good case to be made that
2639 // DefArg's, particularly those of immediate type, ought to
2640 // considered rvalues.
2641 def::DefStatic(..) |
2643 def::DefLocal(..) => ExprKind::Lvalue,
2646 def::DefAssociatedConst(..) => ExprKind::RvalueDatum,
2651 &format!("uncategorized def for expr {}: {:?}",
2658 ast::ExprUnary(ast::UnDeref, _) |
2659 ast::ExprField(..) |
2660 ast::ExprTupField(..) |
2661 ast::ExprIndex(..) => {
2666 ast::ExprMethodCall(..) |
2667 ast::ExprStruct(..) |
2668 ast::ExprRange(..) |
2671 ast::ExprMatch(..) |
2672 ast::ExprClosure(..) |
2673 ast::ExprBlock(..) |
2674 ast::ExprRepeat(..) |
2675 ast::ExprVec(..) => {
2679 ast::ExprIfLet(..) => {
2680 tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
2682 ast::ExprWhileLet(..) => {
2683 tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
2686 ast::ExprForLoop(..) => {
2687 tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
2690 ast::ExprLit(ref lit) if ast_util::lit_is_str(&**lit) => {
2694 ast::ExprBreak(..) |
2695 ast::ExprAgain(..) |
2697 ast::ExprWhile(..) |
2699 ast::ExprAssign(..) |
2700 ast::ExprInlineAsm(..) |
2701 ast::ExprAssignOp(..) => {
2702 ExprKind::RvalueStmt
2705 ast::ExprLit(_) | // Note: LitStr is carved out above
2706 ast::ExprUnary(..) |
2707 ast::ExprBox(None, _) |
2708 ast::ExprAddrOf(..) |
2709 ast::ExprBinary(..) |
2710 ast::ExprCast(..) => {
2711 ExprKind::RvalueDatum
2714 ast::ExprBox(Some(ref place), _) => {
2715 // Special case `Box<T>` for now:
2716 let def_id = match tcx.def_map.borrow().get(&place.id) {
2717 Some(def) => def.def_id(),
2718 None => panic!("no def for place"),
2720 if tcx.lang_items.exchange_heap() == Some(def_id) {
2721 ExprKind::RvalueDatum
2727 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
2729 ast::ExprMac(..) => {
2732 "macro expression remains after expansion");