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;
85 use syntax::{ast, codemap};
86 use syntax::parse::token::InternedString;
88 use syntax::parse::token;
93 // These are passed around by the code generating functions to track the
94 // destination of a computation's value.
96 #[derive(Copy, Clone, PartialEq)]
103 pub fn to_string(&self, ccx: &CrateContext) -> String {
105 SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
106 Ignore => "Ignore".to_string()
111 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
112 /// better optimized LLVM code.
113 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
116 -> Block<'blk, 'tcx> {
119 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
121 if bcx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
122 // use trans, which may be less efficient but
123 // which will perform the adjustments:
124 let datum = unpack_datum!(bcx, trans(bcx, expr));
125 return datum.store_to_dest(bcx, dest, expr.id);
128 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
129 if !qualif.intersects(
130 check_const::ConstQualif::NOT_CONST |
131 check_const::ConstQualif::NEEDS_DROP
133 if !qualif.intersects(check_const::ConstQualif::PREFER_IN_PLACE) {
134 if let SaveIn(lldest) = dest {
135 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
136 bcx.fcx.param_substs);
137 // Cast pointer to destination, because constants
138 // have different types.
139 let lldest = PointerCast(bcx, lldest, val_ty(global));
140 memcpy_ty(bcx, lldest, global, expr_ty_adjusted(bcx, expr));
143 // Even if we don't have a value to emit, and the expression
144 // doesn't have any side-effects, we still have to translate the
145 // body of any closures.
146 // FIXME: Find a better way of handling this case.
148 // The only way we're going to see a `const` at this point is if
149 // it prefers in-place instantiation, likely because it contains
150 // `[x; N]` somewhere within.
152 hir::ExprPath(..) => {
153 match bcx.def(expr.id) {
154 def::DefConst(did) => {
155 let const_expr = consts::get_const_expr(bcx.ccx(), did, expr);
156 // Temporarily get cleanup scopes out of the way,
157 // as they require sub-expressions to be contained
158 // inside the current AST scope.
159 // These should record no cleanups anyways, `const`
160 // can't have destructors.
161 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
163 // Lock emitted debug locations to the location of
164 // the constant reference expression.
165 debuginfo::with_source_location_override(bcx.fcx,
168 bcx = trans_into(bcx, const_expr, dest)
170 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
172 assert!(scopes.is_empty());
183 debug!("trans_into() expr={:?}", expr);
185 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
189 bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
191 let kind = expr_kind(bcx.tcx(), expr);
193 ExprKind::Lvalue | ExprKind::RvalueDatum => {
194 trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
196 ExprKind::RvalueDps => {
197 trans_rvalue_dps_unadjusted(bcx, expr, dest)
199 ExprKind::RvalueStmt => {
200 trans_rvalue_stmt_unadjusted(bcx, expr)
204 bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
207 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
208 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
210 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
212 -> DatumBlock<'blk, 'tcx, Expr> {
213 debug!("trans(expr={:?})", expr);
217 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
218 let adjusted_global = !qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS);
219 let global = if !qualif.intersects(
220 check_const::ConstQualif::NOT_CONST |
221 check_const::ConstQualif::NEEDS_DROP
223 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
224 bcx.fcx.param_substs);
226 if qualif.intersects(check_const::ConstQualif::HAS_STATIC_BORROWS) {
227 // Is borrowed as 'static, must return lvalue.
229 // Cast pointer to global, because constants have different types.
230 let const_ty = expr_ty_adjusted(bcx, expr);
231 let llty = type_of::type_of(bcx.ccx(), const_ty);
232 let global = PointerCast(bcx, global, llty.ptr_to());
233 let datum = Datum::new(global, const_ty, Lvalue::new("expr::trans"));
234 return DatumBlock::new(bcx, datum.to_expr_datum());
237 // Otherwise, keep around and perform adjustments, if needed.
238 let const_ty = if adjusted_global {
239 expr_ty_adjusted(bcx, expr)
244 // This could use a better heuristic.
245 Some(if type_is_immediate(bcx.ccx(), const_ty) {
246 // Cast pointer to global, because constants have different types.
247 let llty = type_of::type_of(bcx.ccx(), const_ty);
248 let global = PointerCast(bcx, global, llty.ptr_to());
249 // Maybe just get the value directly, instead of loading it?
250 immediate_rvalue(load_ty(bcx, global, const_ty), const_ty)
252 let scratch = alloc_ty(bcx, const_ty, "const");
253 call_lifetime_start(bcx, scratch);
254 let lldest = if !const_ty.is_structural() {
255 // Cast pointer to slot, because constants have different types.
256 PointerCast(bcx, scratch, val_ty(global))
258 // In this case, memcpy_ty calls llvm.memcpy after casting both
259 // source and destination to i8*, so we don't need any casts.
262 memcpy_ty(bcx, lldest, global, const_ty);
263 Datum::new(scratch, const_ty, Rvalue::new(ByRef))
269 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
273 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
274 let datum = match global {
275 Some(rvalue) => rvalue.to_expr_datum(),
276 None => unpack_datum!(bcx, trans_unadjusted(bcx, expr))
278 let datum = if adjusted_global {
279 datum // trans::consts already performed adjustments.
281 unpack_datum!(bcx, apply_adjustments(bcx, expr, datum))
283 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
284 return DatumBlock::new(bcx, datum);
287 pub fn get_meta(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
288 StructGEP(bcx, fat_ptr, abi::FAT_PTR_EXTRA)
291 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
292 StructGEP(bcx, fat_ptr, abi::FAT_PTR_ADDR)
295 pub fn copy_fat_ptr(bcx: Block, src_ptr: ValueRef, dst_ptr: ValueRef) {
296 Store(bcx, Load(bcx, get_dataptr(bcx, src_ptr)), get_dataptr(bcx, dst_ptr));
297 Store(bcx, Load(bcx, get_meta(bcx, src_ptr)), get_meta(bcx, dst_ptr));
300 /// Retrieve the information we are losing (making dynamic) in an unsizing
303 /// The `old_info` argument is a bit funny. It is intended for use
304 /// in an upcast, where the new vtable for an object will be drived
305 /// from the old one.
306 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
309 old_info: Option<ValueRef>,
310 param_substs: &'tcx Substs<'tcx>)
312 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
313 match (&source.sty, &target.sty) {
314 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
315 (&ty::TyTrait(_), &ty::TyTrait(_)) => {
316 // For now, upcasts are limited to changes in marker
317 // traits, and hence never actually require an actual
318 // change to the vtable.
319 old_info.expect("unsized_info: missing old info for trait upcast")
321 (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
322 // Note that we preserve binding levels here:
323 let substs = principal.0.substs.with_self_ty(source).erase_regions();
324 let substs = ccx.tcx().mk_substs(substs);
325 let trait_ref = ty::Binder(ty::TraitRef { def_id: principal.def_id(),
327 consts::ptrcast(meth::get_vtable(ccx, trait_ref, param_substs),
328 Type::vtable_ptr(ccx))
330 _ => ccx.sess().bug(&format!("unsized_info: invalid unsizing {:?} -> {:?}",
336 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
337 /// translation of `expr`.
338 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
340 datum: Datum<'tcx, Expr>)
341 -> DatumBlock<'blk, 'tcx, Expr>
344 let mut datum = datum;
345 let adjustment = match bcx.tcx().tables.borrow().adjustments.get(&expr.id).cloned() {
347 return DatumBlock::new(bcx, datum);
351 debug!("unadjusted datum for expr {:?}: {} adjustment={:?}",
353 datum.to_string(bcx.ccx()),
356 AdjustReifyFnPointer => {
357 // FIXME(#19925) once fn item types are
358 // zero-sized, we'll need to do something here
360 AdjustUnsafeFnPointer => {
361 // purely a type-level thing
363 AdjustDerefRef(ref adj) => {
364 let skip_reborrows = if adj.autoderefs == 1 && adj.autoref.is_some() {
365 // We are a bit paranoid about adjustments and thus might have a re-
366 // borrow here which merely derefs and then refs again (it might have
367 // a different region or mutability, but we don't care here).
369 // Don't skip a conversion from Box<T> to &T, etc.
371 if bcx.tcx().is_overloaded_autoderef(expr.id, 0) {
372 // Don't skip an overloaded deref.
384 if adj.autoderefs > skip_reborrows {
386 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
387 datum = unpack_datum!(bcx, deref_multiple(bcx, expr,
388 lval.to_expr_datum(),
389 adj.autoderefs - skip_reborrows));
392 // (You might think there is a more elegant way to do this than a
393 // skip_reborrows bool, but then you remember that the borrow checker exists).
394 if skip_reborrows == 0 && adj.autoref.is_some() {
395 datum = unpack_datum!(bcx, auto_ref(bcx, datum, expr));
398 if let Some(target) = adj.unsize {
399 // We do not arrange cleanup ourselves; if we already are an
400 // L-value, then cleanup will have already been scheduled (and
401 // the `datum.to_rvalue_datum` call below will emit code to zero
402 // the drop flag when moving out of the L-value). If we are an
403 // R-value, then we do not need to schedule cleanup.
404 let source_datum = unpack_datum!(bcx,
405 datum.to_rvalue_datum(bcx, "__coerce_source"));
407 let target = bcx.monomorphize(&target);
409 let scratch = alloc_ty(bcx, target, "__coerce_target");
410 call_lifetime_start(bcx, scratch);
411 let target_datum = Datum::new(scratch, target,
413 bcx = coerce_unsized(bcx, expr.span, source_datum, target_datum);
414 datum = Datum::new(scratch, target,
415 RvalueExpr(Rvalue::new(ByRef)));
419 debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
420 DatumBlock::new(bcx, datum)
423 fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
425 source: Datum<'tcx, Rvalue>,
426 target: Datum<'tcx, Rvalue>)
427 -> Block<'blk, 'tcx> {
429 debug!("coerce_unsized({} -> {})",
430 source.to_string(bcx.ccx()),
431 target.to_string(bcx.ccx()));
433 match (&source.ty.sty, &target.ty.sty) {
434 (&ty::TyBox(a), &ty::TyBox(b)) |
435 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
436 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
437 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
438 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
439 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
440 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
441 let (inner_source, inner_target) = (a, b);
443 let (base, old_info) = if !type_is_sized(bcx.tcx(), inner_source) {
444 // Normally, the source is a thin pointer and we are
445 // adding extra info to make a fat pointer. The exception
446 // is when we are upcasting an existing object fat pointer
447 // to use a different vtable. In that case, we want to
448 // load out the original data pointer so we can repackage
450 (Load(bcx, get_dataptr(bcx, source.val)),
451 Some(Load(bcx, get_meta(bcx, source.val))))
453 let val = if source.kind.is_by_ref() {
454 load_ty(bcx, source.val, source.ty)
461 let info = unsized_info(bcx.ccx(), inner_source, inner_target,
462 old_info, bcx.fcx.param_substs);
464 // Compute the base pointer. This doesn't change the pointer value,
465 // but merely its type.
466 let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), inner_target).ptr_to();
467 let base = PointerCast(bcx, base, ptr_ty);
469 Store(bcx, base, get_dataptr(bcx, target.val));
470 Store(bcx, info, get_meta(bcx, target.val));
473 // This can be extended to enums and tuples in the future.
474 // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
475 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
476 assert_eq!(def_id_a, def_id_b);
478 // The target is already by-ref because it's to be written to.
479 let source = unpack_datum!(bcx, source.to_ref_datum(bcx));
480 assert!(target.kind.is_by_ref());
482 let trait_substs = Substs::erased(VecPerParamSpace::new(vec![target.ty],
485 let trait_ref = ty::Binder(ty::TraitRef {
486 def_id: langcall(bcx, Some(span), "coercion",
487 CoerceUnsizedTraitLangItem),
488 substs: bcx.tcx().mk_substs(trait_substs)
491 let kind = match fulfill_obligation(bcx.ccx(), span, trait_ref) {
492 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
493 bcx.tcx().custom_coerce_unsized_kind(impl_def_id)
496 bcx.sess().span_bug(span, &format!("invalid CoerceUnsized vtable: {:?}",
501 let repr_source = adt::represent_type(bcx.ccx(), source.ty);
502 let src_fields = match &*repr_source {
503 &adt::Repr::Univariant(ref s, _) => &s.fields,
504 _ => bcx.sess().span_bug(span,
505 &format!("Non univariant struct? (repr_source: {:?})",
508 let repr_target = adt::represent_type(bcx.ccx(), target.ty);
509 let target_fields = match &*repr_target {
510 &adt::Repr::Univariant(ref s, _) => &s.fields,
511 _ => bcx.sess().span_bug(span,
512 &format!("Non univariant struct? (repr_target: {:?})",
516 let coerce_index = match kind {
517 ty::CustomCoerceUnsized::Struct(i) => i
519 assert!(coerce_index < src_fields.len() && src_fields.len() == target_fields.len());
521 let iter = src_fields.iter().zip(target_fields).enumerate();
522 for (i, (src_ty, target_ty)) in iter {
523 let ll_source = adt::trans_field_ptr(bcx, &repr_source, source.val, 0, i);
524 let ll_target = adt::trans_field_ptr(bcx, &repr_target, target.val, 0, i);
526 // If this is the field we need to coerce, recurse on it.
527 if i == coerce_index {
528 coerce_unsized(bcx, span,
529 Datum::new(ll_source, src_ty,
531 Datum::new(ll_target, target_ty,
532 Rvalue::new(ByRef)));
534 // Otherwise, simply copy the data from the source.
535 assert_eq!(src_ty, target_ty);
536 memcpy_ty(bcx, ll_target, ll_source, src_ty);
540 _ => bcx.sess().bug(&format!("coerce_unsized: invalid coercion {:?} -> {:?}",
547 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
548 /// that the expr represents.
550 /// If this expression is an rvalue, this implies introducing a temporary. In other words,
551 /// something like `x().f` is translated into roughly the equivalent of
553 /// { tmp = x(); tmp.f }
554 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
557 -> DatumBlock<'blk, 'tcx, Lvalue> {
559 let datum = unpack_datum!(bcx, trans(bcx, expr));
560 return datum.to_lvalue_datum(bcx, name, expr.id);
563 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
565 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
567 -> DatumBlock<'blk, 'tcx, Expr> {
570 debug!("trans_unadjusted(expr={:?})", expr);
571 let _indenter = indenter();
573 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
575 return match expr_kind(bcx.tcx(), expr) {
576 ExprKind::Lvalue | ExprKind::RvalueDatum => {
577 let datum = unpack_datum!(bcx, {
578 trans_datum_unadjusted(bcx, expr)
581 DatumBlock {bcx: bcx, datum: datum}
584 ExprKind::RvalueStmt => {
585 bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
586 nil(bcx, expr_ty(bcx, expr))
589 ExprKind::RvalueDps => {
590 let ty = expr_ty(bcx, expr);
591 if type_is_zero_size(bcx.ccx(), ty) {
592 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
595 let scratch = rvalue_scratch_datum(bcx, ty, "");
596 bcx = trans_rvalue_dps_unadjusted(
597 bcx, expr, SaveIn(scratch.val));
599 // Note: this is not obviously a good idea. It causes
600 // immediate values to be loaded immediately after a
601 // return from a call or other similar expression,
602 // which in turn leads to alloca's having shorter
603 // lifetimes and hence larger stack frames. However,
604 // in turn it can lead to more register pressure.
605 // Still, in practice it seems to increase
606 // performance, since we have fewer problems with
608 let scratch = unpack_datum!(
609 bcx, scratch.to_appropriate_datum(bcx));
611 DatumBlock::new(bcx, scratch.to_expr_datum())
616 fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
617 -> DatumBlock<'blk, 'tcx, Expr> {
618 let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
619 let datum = immediate_rvalue(llval, ty);
620 DatumBlock::new(bcx, datum.to_expr_datum())
624 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
626 -> DatumBlock<'blk, 'tcx, Expr> {
629 let _icx = push_ctxt("trans_datum_unadjusted");
632 hir::ExprParen(ref e) => {
635 hir::ExprPath(..) => {
636 trans_def(bcx, expr, bcx.def(expr.id))
638 hir::ExprField(ref base, ident) => {
639 trans_rec_field(bcx, &**base, ident.node.name)
641 hir::ExprTupField(ref base, idx) => {
642 trans_rec_tup_field(bcx, &**base, idx.node)
644 hir::ExprIndex(ref base, ref idx) => {
645 trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
647 hir::ExprBox(_, ref contents) => {
648 // Special case for `Box<T>`
649 let box_ty = expr_ty(bcx, expr);
650 let contents_ty = expr_ty(bcx, &**contents);
653 trans_uniq_expr(bcx, expr, box_ty, &**contents, contents_ty)
655 _ => bcx.sess().span_bug(expr.span,
656 "expected unique box")
660 hir::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
661 hir::ExprBinary(op, ref lhs, ref rhs) => {
662 trans_binary(bcx, expr, op, &**lhs, &**rhs)
664 hir::ExprUnary(op, ref x) => {
665 trans_unary(bcx, expr, op, &**x)
667 hir::ExprAddrOf(_, ref x) => {
669 hir::ExprRepeat(..) | hir::ExprVec(..) => {
670 // Special case for slices.
671 let cleanup_debug_loc =
672 debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
676 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
677 let datum = unpack_datum!(
678 bcx, tvec::trans_slice_vec(bcx, expr, &**x));
679 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
680 DatumBlock::new(bcx, datum)
683 trans_addr_of(bcx, expr, &**x)
687 hir::ExprCast(ref val, _) => {
688 // Datum output mode means this is a scalar cast:
689 trans_imm_cast(bcx, &**val, expr.id)
692 bcx.tcx().sess.span_bug(
694 &format!("trans_rvalue_datum_unadjusted reached \
695 fall-through case: {:?}",
701 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
704 -> DatumBlock<'blk, 'tcx, Expr> where
705 F: FnOnce(&'blk ty::ctxt<'tcx>, &VariantInfo<'tcx>) -> usize,
708 let _icx = push_ctxt("trans_rec_field");
710 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
711 let bare_ty = base_datum.ty;
712 let repr = adt::represent_type(bcx.ccx(), bare_ty);
713 let vinfo = VariantInfo::from_ty(bcx.tcx(), bare_ty, None);
715 let ix = get_idx(bcx.tcx(), &vinfo);
716 let d = base_datum.get_element(
719 |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, vinfo.discr, ix));
721 if type_is_sized(bcx.tcx(), d.ty) {
722 DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
724 let scratch = rvalue_scratch_datum(bcx, d.ty, "");
725 Store(bcx, d.val, get_dataptr(bcx, scratch.val));
726 let info = Load(bcx, get_meta(bcx, base_datum.val));
727 Store(bcx, info, get_meta(bcx, scratch.val));
729 // Always generate an lvalue datum, because this pointer doesn't own
730 // the data and cleanup is scheduled elsewhere.
731 DatumBlock::new(bcx, Datum::new(scratch.val, scratch.ty, LvalueExpr(d.kind)))
735 /// Translates `base.field`.
736 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
739 -> DatumBlock<'blk, 'tcx, Expr> {
740 trans_field(bcx, base, |_, vinfo| vinfo.field_index(field))
743 /// Translates `base.<idx>`.
744 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
747 -> DatumBlock<'blk, 'tcx, Expr> {
748 trans_field(bcx, base, |_, _| idx)
751 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
752 index_expr: &hir::Expr,
755 method_call: MethodCall)
756 -> DatumBlock<'blk, 'tcx, Expr> {
757 //! Translates `base[idx]`.
759 let _icx = push_ctxt("trans_index");
763 let index_expr_debug_loc = index_expr.debug_loc();
765 // Check for overloaded index.
766 let method_ty = ccx.tcx()
771 .map(|method| method.ty);
772 let elt_datum = match method_ty {
774 let method_ty = monomorphize_type(bcx, method_ty);
776 let base_datum = unpack_datum!(bcx, trans(bcx, base));
778 // Translate index expression.
779 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
781 let ref_ty = // invoked methods have LB regions instantiated:
782 bcx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
783 let elt_ty = match ref_ty.builtin_deref(true, ty::NoPreference) {
785 bcx.tcx().sess.span_bug(index_expr.span,
786 "index method didn't return a \
787 dereferenceable type?!")
789 Some(elt_tm) => elt_tm.ty,
792 // Overloaded. Evaluate `trans_overloaded_op`, which will
793 // invoke the user's index() method, which basically yields
794 // a `&T` pointer. We can then proceed down the normal
795 // path (below) to dereference that `&T`.
796 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
798 trans_overloaded_op(bcx,
802 Some((ix_datum, idx.id)),
803 Some(SaveIn(scratch.val)),
805 let datum = scratch.to_expr_datum();
806 let lval = Lvalue::new("expr::trans_index overload");
807 if type_is_sized(bcx.tcx(), elt_ty) {
808 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr(lval))
810 Datum::new(datum.val, elt_ty, LvalueExpr(lval))
814 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
818 // Translate index expression and cast to a suitable LLVM integer.
819 // Rust is less strict than LLVM in this regard.
820 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
821 let ix_val = ix_datum.to_llscalarish(bcx);
822 let ix_size = machine::llbitsize_of_real(bcx.ccx(),
824 let int_size = machine::llbitsize_of_real(bcx.ccx(),
827 if ix_size < int_size {
828 if expr_ty(bcx, idx).is_signed() {
829 SExt(bcx, ix_val, ccx.int_type())
830 } else { ZExt(bcx, ix_val, ccx.int_type()) }
831 } else if ix_size > int_size {
832 Trunc(bcx, ix_val, ccx.int_type())
838 let unit_ty = base_datum.ty.sequence_element_type(bcx.tcx());
840 let (base, len) = base_datum.get_vec_base_and_len(bcx);
842 debug!("trans_index: base {}", bcx.val_to_string(base));
843 debug!("trans_index: len {}", bcx.val_to_string(len));
845 let bounds_check = ICmp(bcx,
849 index_expr_debug_loc);
850 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
851 let expected = Call(bcx,
853 &[bounds_check, C_bool(ccx, false)],
855 index_expr_debug_loc);
856 bcx = with_cond(bcx, expected, |bcx| {
857 controlflow::trans_fail_bounds_check(bcx,
858 expr_info(index_expr),
862 let elt = InBoundsGEP(bcx, base, &[ix_val]);
863 let elt = PointerCast(bcx, elt, type_of::type_of(ccx, unit_ty).ptr_to());
864 let lval = Lvalue::new("expr::trans_index fallback");
865 Datum::new(elt, unit_ty, LvalueExpr(lval))
869 DatumBlock::new(bcx, elt_datum)
872 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
873 ref_expr: &hir::Expr,
875 -> DatumBlock<'blk, 'tcx, Expr> {
876 //! Translates a reference to a path.
878 let _icx = push_ctxt("trans_def_lvalue");
880 def::DefFn(..) | def::DefMethod(..) |
881 def::DefStruct(_) | def::DefVariant(..) => {
882 let datum = trans_def_fn_unadjusted(bcx.ccx(), ref_expr, def,
883 bcx.fcx.param_substs);
884 DatumBlock::new(bcx, datum.to_expr_datum())
886 def::DefStatic(did, _) => {
887 // There are two things that may happen here:
888 // 1) If the static item is defined in this crate, it will be
889 // translated using `get_item_val`, and we return a pointer to
891 // 2) If the static item is defined in another crate then we add
892 // (or reuse) a declaration of an external global, and return a
894 let const_ty = expr_ty(bcx, ref_expr);
896 // For external constants, we don't inline.
897 let val = if did.is_local() {
900 // The LLVM global has the type of its initializer,
901 // which may not be equal to the enum's type for
903 let val = base::get_item_val(bcx.ccx(), did.node);
904 let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
905 PointerCast(bcx, val, pty)
908 base::get_extern_const(bcx.ccx(), did, const_ty)
910 let lval = Lvalue::new("expr::trans_def");
911 DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr(lval)))
913 def::DefConst(_) => {
914 bcx.sess().span_bug(ref_expr.span,
915 "constant expression should not reach expr::trans_def")
918 DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
923 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
925 -> Block<'blk, 'tcx> {
927 let _icx = push_ctxt("trans_rvalue_stmt");
929 if bcx.unreachable.get() {
933 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
936 hir::ExprParen(ref e) => {
937 trans_into(bcx, &**e, Ignore)
939 hir::ExprBreak(label_opt) => {
940 controlflow::trans_break(bcx, expr, label_opt.map(|l| l.node))
942 hir::ExprAgain(label_opt) => {
943 controlflow::trans_cont(bcx, expr, label_opt.map(|l| l.node))
945 hir::ExprRet(ref ex) => {
946 // Check to see if the return expression itself is reachable.
947 // This can occur when the inner expression contains a return
948 let reachable = if let Some(ref cfg) = bcx.fcx.cfg {
949 cfg.node_is_reachable(expr.id)
955 controlflow::trans_ret(bcx, expr, ex.as_ref().map(|e| &**e))
957 // If it's not reachable, just translate the inner expression
958 // directly. This avoids having to manage a return slot when
959 // it won't actually be used anyway.
960 if let &Some(ref x) = ex {
961 bcx = trans_into(bcx, &**x, Ignore);
963 // Mark the end of the block as unreachable. Once we get to
964 // a return expression, there's no more we should be doing
970 hir::ExprWhile(ref cond, ref body, _) => {
971 controlflow::trans_while(bcx, expr, &**cond, &**body)
973 hir::ExprLoop(ref body, _) => {
974 controlflow::trans_loop(bcx, expr, &**body)
976 hir::ExprAssign(ref dst, ref src) => {
977 let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
978 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
980 if bcx.fcx.type_needs_drop(dst_datum.ty) {
981 // If there are destructors involved, make sure we
982 // are copying from an rvalue, since that cannot possible
983 // alias an lvalue. We are concerned about code like:
991 // where e.g. a : Option<Foo> and a.b :
992 // Option<Foo>. In that case, freeing `a` before the
993 // assignment may also free `a.b`!
995 // We could avoid this intermediary with some analysis
996 // to determine whether `dst` may possibly own `src`.
997 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
998 let src_datum = unpack_datum!(
999 bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
1000 let opt_hint_datum = dst_datum.kind.drop_flag_info.hint_datum(bcx);
1001 let opt_hint_val = opt_hint_datum.map(|d|d.to_value());
1003 // 1. Drop the data at the destination, passing the
1004 // drop-hint in case the lvalue has already been
1005 // dropped or moved.
1006 bcx = glue::drop_ty_core(bcx,
1013 // 2. We are overwriting the destination; ensure that
1014 // its drop-hint (if any) says "initialized."
1015 if let Some(hint_val) = opt_hint_val {
1016 let hint_llval = hint_val.value();
1017 let drop_needed = C_u8(bcx.fcx.ccx, adt::DTOR_NEEDED_HINT);
1018 Store(bcx, drop_needed, hint_llval);
1020 src_datum.store_to(bcx, dst_datum.val)
1022 src_datum.store_to(bcx, dst_datum.val)
1025 hir::ExprAssignOp(op, ref dst, ref src) => {
1026 trans_assign_op(bcx, expr, op, &**dst, &**src)
1028 hir::ExprInlineAsm(ref a) => {
1029 asm::trans_inline_asm(bcx, a)
1032 bcx.tcx().sess.span_bug(
1034 &format!("trans_rvalue_stmt_unadjusted reached \
1035 fall-through case: {:?}",
1041 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1044 -> Block<'blk, 'tcx> {
1045 let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
1047 let tcx = bcx.tcx();
1049 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1052 hir::ExprParen(ref e) => {
1053 trans_into(bcx, &**e, dest)
1055 hir::ExprPath(..) => {
1056 trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1058 hir::ExprIf(ref cond, ref thn, ref els) => {
1059 controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1061 hir::ExprMatch(ref discr, ref arms, _) => {
1062 _match::trans_match(bcx, expr, &**discr, &arms[..], dest)
1064 hir::ExprBlock(ref blk) => {
1065 controlflow::trans_block(bcx, &**blk, dest)
1067 hir::ExprStruct(_, ref fields, ref base) => {
1070 base.as_ref().map(|e| &**e),
1073 node_id_type(bcx, expr.id),
1076 hir::ExprRange(ref start, ref end) => {
1077 // FIXME it is just not right that we are synthesising ast nodes in
1079 fn make_field(field_name: &str, expr: P<hir::Expr>) -> hir::Field {
1081 ident: codemap::dummy_spanned(token::str_to_ident(field_name)),
1083 span: codemap::DUMMY_SP,
1087 // A range just desugars into a struct.
1088 // Note that the type of the start and end may not be the same, but
1089 // they should only differ in their lifetime, which should not matter
1091 let (did, fields, ty_params) = match (start, end) {
1092 (&Some(ref start), &Some(ref end)) => {
1094 let fields = vec![make_field("start", start.clone()),
1095 make_field("end", end.clone())];
1096 (tcx.lang_items.range_struct(), fields, vec![node_id_type(bcx, start.id)])
1098 (&Some(ref start), &None) => {
1099 // Desugar to RangeFrom
1100 let fields = vec![make_field("start", start.clone())];
1101 (tcx.lang_items.range_from_struct(), fields, vec![node_id_type(bcx, start.id)])
1103 (&None, &Some(ref end)) => {
1104 // Desugar to RangeTo
1105 let fields = vec![make_field("end", end.clone())];
1106 (tcx.lang_items.range_to_struct(), fields, vec![node_id_type(bcx, end.id)])
1109 // Desugar to RangeFull
1110 (tcx.lang_items.range_full_struct(), vec![], vec![])
1114 if let Some(did) = did {
1115 let substs = Substs::new_type(ty_params, vec![]);
1121 tcx.mk_struct(tcx.lookup_adt_def(did),
1122 tcx.mk_substs(substs)),
1125 tcx.sess.span_bug(expr.span,
1126 "No lang item for ranges (how did we get this far?)")
1129 hir::ExprTup(ref args) => {
1130 let numbered_fields: Vec<(usize, &hir::Expr)> =
1131 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1135 &numbered_fields[..],
1140 hir::ExprLit(ref lit) => {
1142 hir::LitStr(ref s, _) => {
1143 tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1148 .span_bug(expr.span,
1149 "trans_rvalue_dps_unadjusted shouldn't be \
1150 translating this type of literal")
1154 hir::ExprVec(..) | hir::ExprRepeat(..) => {
1155 tvec::trans_fixed_vstore(bcx, expr, dest)
1157 hir::ExprClosure(_, ref decl, ref body) => {
1158 let dest = match dest {
1159 SaveIn(lldest) => closure::Dest::SaveIn(bcx, lldest),
1160 Ignore => closure::Dest::Ignore(bcx.ccx())
1162 let substs = match expr_ty(bcx, expr).sty {
1163 ty::TyClosure(_, ref substs) => substs,
1165 bcx.tcx().sess.span_bug(
1167 &format!("closure expr without closure type: {:?}", t)),
1169 closure::trans_closure_expr(dest, decl, body, expr.id, substs).unwrap_or(bcx)
1171 hir::ExprCall(ref f, ref args) => {
1172 if bcx.tcx().is_method_call(expr.id) {
1173 trans_overloaded_call(bcx,
1179 callee::trans_call(bcx,
1182 callee::ArgExprs(&args[..]),
1186 hir::ExprMethodCall(_, _, ref args) => {
1187 callee::trans_method_call(bcx,
1190 callee::ArgExprs(&args[..]),
1193 hir::ExprBinary(op, ref lhs, ref rhs) => {
1194 // if not overloaded, would be RvalueDatumExpr
1195 let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1196 let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1197 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1198 Some((rhs_datum, rhs.id)), Some(dest),
1199 !rustc_front::util::is_by_value_binop(op.node)).bcx
1201 hir::ExprUnary(op, ref subexpr) => {
1202 // if not overloaded, would be RvalueDatumExpr
1203 let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1204 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1205 arg, None, Some(dest), !rustc_front::util::is_by_value_unop(op)).bcx
1207 hir::ExprIndex(ref base, ref idx) => {
1208 // if not overloaded, would be RvalueDatumExpr
1209 let base = unpack_datum!(bcx, trans(bcx, &**base));
1210 let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1211 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1212 Some((idx_datum, idx.id)), Some(dest), true).bcx
1214 hir::ExprCast(..) => {
1215 // Trait casts used to come this way, now they should be coercions.
1216 bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
1218 hir::ExprAssignOp(op, ref dst, ref src) => {
1219 trans_assign_op(bcx, expr, op, &**dst, &**src)
1222 bcx.tcx().sess.span_bug(
1224 &format!("trans_rvalue_dps_unadjusted reached fall-through \
1231 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1232 ref_expr: &hir::Expr,
1235 -> Block<'blk, 'tcx> {
1236 let _icx = push_ctxt("trans_def_dps_unadjusted");
1238 let lldest = match dest {
1239 SaveIn(lldest) => lldest,
1240 Ignore => { return bcx; }
1244 def::DefVariant(tid, vid, _) => {
1245 let variant = bcx.tcx().lookup_adt_def(tid).variant_with_id(vid);
1246 if let ty::VariantKind::Tuple = variant.kind() {
1248 let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
1249 ExprId(ref_expr.id),
1250 bcx.fcx.param_substs).val;
1251 Store(bcx, llfn, lldest);
1255 let ty = expr_ty(bcx, ref_expr);
1256 let repr = adt::represent_type(bcx.ccx(), ty);
1257 adt::trans_set_discr(bcx, &*repr, lldest, variant.disr_val);
1261 def::DefStruct(_) => {
1262 let ty = expr_ty(bcx, ref_expr);
1264 ty::TyStruct(def, _) if def.has_dtor() => {
1265 let repr = adt::represent_type(bcx.ccx(), ty);
1266 adt::trans_set_discr(bcx, &*repr, lldest, 0);
1273 bcx.tcx().sess.span_bug(ref_expr.span, &format!(
1274 "Non-DPS def {:?} referened by {}",
1275 def, bcx.node_id_to_string(ref_expr.id)));
1280 pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1281 ref_expr: &hir::Expr,
1283 param_substs: &'tcx Substs<'tcx>)
1284 -> Datum<'tcx, Rvalue> {
1285 let _icx = push_ctxt("trans_def_datum_unadjusted");
1288 def::DefFn(did, _) |
1289 def::DefStruct(did) | def::DefVariant(_, did, _) => {
1290 callee::trans_fn_ref(ccx, did, ExprId(ref_expr.id), param_substs)
1292 def::DefMethod(method_did) => {
1293 match ccx.tcx().impl_or_trait_item(method_did).container() {
1294 ty::ImplContainer(_) => {
1295 callee::trans_fn_ref(ccx, method_did,
1296 ExprId(ref_expr.id),
1299 ty::TraitContainer(trait_did) => {
1300 meth::trans_static_method_callee(ccx, method_did,
1301 trait_did, ref_expr.id,
1307 ccx.tcx().sess.span_bug(ref_expr.span, &format!(
1308 "trans_def_fn_unadjusted invoked on: {:?} for {:?}",
1315 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1316 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1318 -> Datum<'tcx, Lvalue> {
1319 let _icx = push_ctxt("trans_local_var");
1322 def::DefUpvar(nid, _) => {
1323 // Can't move upvars, so this is never a ZeroMemLastUse.
1324 let local_ty = node_id_type(bcx, nid);
1325 let lval = Lvalue::new_with_hint("expr::trans_local_var (upvar)",
1326 bcx, nid, HintKind::ZeroAndMaintain);
1327 match bcx.fcx.llupvars.borrow().get(&nid) {
1328 Some(&val) => Datum::new(val, local_ty, lval),
1330 bcx.sess().bug(&format!(
1331 "trans_local_var: no llval for upvar {} found",
1336 def::DefLocal(nid) => {
1337 let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1340 bcx.sess().bug(&format!(
1341 "trans_local_var: no datum for local/arg {} found",
1345 debug!("take_local(nid={}, v={}, ty={})",
1346 nid, bcx.val_to_string(datum.val), datum.ty);
1350 bcx.sess().unimpl(&format!(
1351 "unsupported def type in trans_local_var: {:?}",
1357 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1358 fields: &[hir::Field],
1359 base: Option<&hir::Expr>,
1360 expr_span: codemap::Span,
1361 expr_id: ast::NodeId,
1363 dest: Dest) -> Block<'blk, 'tcx> {
1364 let _icx = push_ctxt("trans_rec");
1366 let tcx = bcx.tcx();
1367 let vinfo = VariantInfo::of_node(tcx, ty, expr_id);
1369 let mut need_base = vec![true; vinfo.fields.len()];
1371 let numbered_fields = fields.iter().map(|field| {
1372 let pos = vinfo.field_index(field.ident.node.name);
1373 need_base[pos] = false;
1375 }).collect::<Vec<_>>();
1377 let optbase = match base {
1378 Some(base_expr) => {
1379 let mut leftovers = Vec::new();
1380 for (i, b) in need_base.iter().enumerate() {
1382 leftovers.push((i, vinfo.fields[i].1));
1385 Some(StructBaseInfo {expr: base_expr,
1386 fields: leftovers })
1389 if need_base.iter().any(|b| *b) {
1390 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1402 DebugLoc::At(expr_id, expr_span))
1405 /// Information that `trans_adt` needs in order to fill in the fields
1406 /// of a struct copied from a base struct (e.g., from an expression
1407 /// like `Foo { a: b, ..base }`.
1409 /// Note that `fields` may be empty; the base expression must always be
1410 /// evaluated for side-effects.
1411 pub struct StructBaseInfo<'a, 'tcx> {
1412 /// The base expression; will be evaluated after all explicit fields.
1413 expr: &'a hir::Expr,
1414 /// The indices of fields to copy paired with their types.
1415 fields: Vec<(usize, Ty<'tcx>)>
1418 /// Constructs an ADT instance:
1420 /// - `fields` should be a list of field indices paired with the
1421 /// expression to store into that field. The initializers will be
1422 /// evaluated in the order specified by `fields`.
1424 /// - `optbase` contains information on the base struct (if any) from
1425 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1426 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1429 fields: &[(usize, &hir::Expr)],
1430 optbase: Option<StructBaseInfo<'a, 'tcx>>,
1432 debug_location: DebugLoc)
1433 -> Block<'blk, 'tcx> {
1434 let _icx = push_ctxt("trans_adt");
1436 let repr = adt::represent_type(bcx.ccx(), ty);
1438 debug_location.apply(bcx.fcx);
1440 // If we don't care about the result, just make a
1441 // temporary stack slot
1442 let addr = match dest {
1445 let llresult = alloc_ty(bcx, ty, "temp");
1446 call_lifetime_start(bcx, llresult);
1451 // This scope holds intermediates that must be cleaned should
1452 // panic occur before the ADT as a whole is ready.
1453 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1456 // Issue 23112: The original logic appeared vulnerable to same
1457 // order-of-eval bug. But, SIMD values are tuple-structs;
1458 // i.e. functional record update (FRU) syntax is unavailable.
1460 // To be safe, double-check that we did not get here via FRU.
1461 assert!(optbase.is_none());
1463 // This is the constructor of a SIMD type, such types are
1464 // always primitive machine types and so do not have a
1465 // destructor or require any clean-up.
1466 let llty = type_of::type_of(bcx.ccx(), ty);
1468 // keep a vector as a register, and running through the field
1469 // `insertelement`ing them directly into that register
1470 // (i.e. avoid GEPi and `store`s to an alloca) .
1471 let mut vec_val = C_undef(llty);
1473 for &(i, ref e) in fields {
1474 let block_datum = trans(bcx, &**e);
1475 bcx = block_datum.bcx;
1476 let position = C_uint(bcx.ccx(), i);
1477 let value = block_datum.datum.to_llscalarish(bcx);
1478 vec_val = InsertElement(bcx, vec_val, value, position);
1480 Store(bcx, vec_val, addr);
1481 } else if let Some(base) = optbase {
1482 // Issue 23112: If there is a base, then order-of-eval
1483 // requires field expressions eval'ed before base expression.
1485 // First, trans field expressions to temporary scratch values.
1486 let scratch_vals: Vec<_> = fields.iter().map(|&(i, ref e)| {
1487 let datum = unpack_datum!(bcx, trans(bcx, &**e));
1491 debug_location.apply(bcx.fcx);
1493 // Second, trans the base to the dest.
1494 assert_eq!(discr, 0);
1496 match expr_kind(bcx.tcx(), &*base.expr) {
1497 ExprKind::RvalueDps | ExprKind::RvalueDatum if !bcx.fcx.type_needs_drop(ty) => {
1498 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1500 ExprKind::RvalueStmt => {
1501 bcx.tcx().sess.bug("unexpected expr kind for struct base expr")
1504 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1505 for &(i, t) in &base.fields {
1506 let datum = base_datum.get_element(
1507 bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1508 assert!(type_is_sized(bcx.tcx(), datum.ty));
1509 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1510 bcx = datum.store_to(bcx, dest);
1515 // Finally, move scratch field values into actual field locations
1516 for (i, datum) in scratch_vals {
1517 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1518 bcx = datum.store_to(bcx, dest);
1521 // No base means we can write all fields directly in place.
1522 for &(i, ref e) in fields {
1523 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1524 let e_ty = expr_ty_adjusted(bcx, &**e);
1525 bcx = trans_into(bcx, &**e, SaveIn(dest));
1526 let scope = cleanup::CustomScope(custom_cleanup_scope);
1527 fcx.schedule_lifetime_end(scope, dest);
1528 // FIXME: nonzeroing move should generalize to fields
1529 fcx.schedule_drop_mem(scope, dest, e_ty, None);
1533 adt::trans_set_discr(bcx, &*repr, addr, discr);
1535 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1537 // If we don't care about the result drop the temporary we made
1541 bcx = glue::drop_ty(bcx, addr, ty, debug_location);
1542 base::call_lifetime_end(bcx, addr);
1549 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1552 -> DatumBlock<'blk, 'tcx, Expr> {
1553 // must not be a string constant, that is a RvalueDpsExpr
1554 let _icx = push_ctxt("trans_immediate_lit");
1555 let ty = expr_ty(bcx, expr);
1556 let v = consts::const_lit(bcx.ccx(), expr, lit);
1557 immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1560 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1563 sub_expr: &hir::Expr)
1564 -> DatumBlock<'blk, 'tcx, Expr> {
1565 let ccx = bcx.ccx();
1567 let _icx = push_ctxt("trans_unary_datum");
1569 let method_call = MethodCall::expr(expr.id);
1571 // The only overloaded operator that is translated to a datum
1572 // is an overloaded deref, since it is always yields a `&T`.
1573 // Otherwise, we should be in the RvalueDpsExpr path.
1574 assert!(op == hir::UnDeref || !ccx.tcx().is_method_call(expr.id));
1576 let un_ty = expr_ty(bcx, expr);
1578 let debug_loc = expr.debug_loc();
1582 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1583 let llresult = Not(bcx, datum.to_llscalarish(bcx), debug_loc);
1584 immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1587 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1588 let val = datum.to_llscalarish(bcx);
1589 let (bcx, llneg) = {
1591 let result = FNeg(bcx, val, debug_loc);
1594 let is_signed = un_ty.is_signed();
1595 let result = Neg(bcx, val, debug_loc);
1596 let bcx = if bcx.ccx().check_overflow() && is_signed {
1597 let (llty, min) = base::llty_and_min_for_signed_ty(bcx, un_ty);
1598 let is_min = ICmp(bcx, llvm::IntEQ, val,
1599 C_integral(llty, min, true), debug_loc);
1600 with_cond(bcx, is_min, |bcx| {
1601 let msg = InternedString::new(
1602 "attempted to negate with overflow");
1603 controlflow::trans_fail(bcx, expr_info(expr), msg)
1611 immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1614 trans_uniq_expr(bcx, expr, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1617 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1618 deref_once(bcx, expr, datum, method_call)
1623 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1624 box_expr: &hir::Expr,
1626 contents: &hir::Expr,
1627 contents_ty: Ty<'tcx>)
1628 -> DatumBlock<'blk, 'tcx, Expr> {
1629 let _icx = push_ctxt("trans_uniq_expr");
1631 assert!(type_is_sized(bcx.tcx(), contents_ty));
1632 let llty = type_of::type_of(bcx.ccx(), contents_ty);
1633 let size = llsize_of(bcx.ccx(), llty);
1634 let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1635 let llty_ptr = llty.ptr_to();
1636 let Result { bcx, val } = malloc_raw_dyn(bcx,
1641 box_expr.debug_loc());
1642 // Unique boxes do not allocate for zero-size types. The standard library
1643 // may assume that `free` is never called on the pointer returned for
1644 // `Box<ZeroSizeType>`.
1645 let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1646 trans_into(bcx, contents, SaveIn(val))
1648 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1649 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1650 val, cleanup::HeapExchange, contents_ty);
1651 let bcx = trans_into(bcx, contents, SaveIn(val));
1652 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1655 immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1658 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1659 lval: Datum<'tcx, Lvalue>)
1660 -> DatumBlock<'blk, 'tcx, Expr> {
1661 let dest_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), lval.ty);
1662 let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
1663 memcpy_ty(bcx, scratch.val, lval.val, scratch.ty);
1665 DatumBlock::new(bcx, scratch.to_expr_datum())
1668 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1670 subexpr: &hir::Expr)
1671 -> DatumBlock<'blk, 'tcx, Expr> {
1672 let _icx = push_ctxt("trans_addr_of");
1674 let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1675 if !type_is_sized(bcx.tcx(), sub_datum.ty) {
1676 // DST lvalue, close to a fat pointer
1677 ref_fat_ptr(bcx, sub_datum)
1679 // Sized value, ref to a thin pointer
1680 let ty = expr_ty(bcx, expr);
1681 immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1685 // Important to get types for both lhs and rhs, because one might be _|_
1686 // and the other not.
1687 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1688 binop_expr: &hir::Expr,
1695 -> DatumBlock<'blk, 'tcx, Expr> {
1696 let _icx = push_ctxt("trans_eager_binop");
1698 let tcx = bcx.tcx();
1699 assert!(!lhs_t.is_simd());
1700 let is_float = lhs_t.is_fp();
1701 let is_signed = lhs_t.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 let (newbcx, res) = with_overflow_check(
1713 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1720 FSub(bcx, lhs, rhs, binop_debug_loc)
1722 let (newbcx, res) = with_overflow_check(
1723 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1730 FMul(bcx, lhs, rhs, binop_debug_loc)
1732 let (newbcx, res) = with_overflow_check(
1733 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1740 FDiv(bcx, lhs, rhs, binop_debug_loc)
1742 // Only zero-check integers; fp /0 is NaN
1743 bcx = base::fail_if_zero_or_overflows(bcx,
1744 expr_info(binop_expr),
1750 SDiv(bcx, lhs, rhs, binop_debug_loc)
1752 UDiv(bcx, lhs, rhs, binop_debug_loc)
1758 // LLVM currently always lowers the `frem` instructions appropriate
1759 // library calls typically found in libm. Notably f64 gets wired up
1760 // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
1761 // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
1762 // instead just an inline function in a header that goes up to a
1763 // f64, uses `fmod`, and then comes back down to a f32.
1765 // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
1766 // still unconditionally lower frem instructions over 32-bit floats
1767 // to a call to `fmodf`. To work around this we special case MSVC
1768 // 32-bit float rem instructions and instead do the call out to
1769 // `fmod` ourselves.
1771 // Note that this is currently duplicated with src/libcore/ops.rs
1772 // which does the same thing, and it would be nice to perhaps unify
1773 // these two implementations on day! Also note that we call `fmod`
1774 // for both 32 and 64-bit floats because if we emit any FRem
1775 // instruction at all then LLVM is capable of optimizing it into a
1776 // 32-bit FRem (which we're trying to avoid).
1777 let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
1778 tcx.sess.target.target.arch == "x86";
1780 let f64t = Type::f64(bcx.ccx());
1781 let fty = Type::func(&[f64t, f64t], &f64t);
1782 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty,
1784 if lhs_t == tcx.types.f32 {
1785 let lhs = FPExt(bcx, lhs, f64t);
1786 let rhs = FPExt(bcx, rhs, f64t);
1787 let res = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
1788 FPTrunc(bcx, res, Type::f32(bcx.ccx()))
1790 Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc)
1793 FRem(bcx, lhs, rhs, binop_debug_loc)
1796 // Only zero-check integers; fp %0 is NaN
1797 bcx = base::fail_if_zero_or_overflows(bcx,
1798 expr_info(binop_expr),
1799 op, lhs, rhs, rhs_t);
1801 SRem(bcx, lhs, rhs, binop_debug_loc)
1803 URem(bcx, lhs, rhs, binop_debug_loc)
1807 hir::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1808 hir::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1809 hir::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1811 let (newbcx, res) = with_overflow_check(
1812 bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1817 let (newbcx, res) = with_overflow_check(
1818 bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1822 hir::BiEq | hir::BiNe | hir::BiLt | hir::BiGe | hir::BiLe | hir::BiGt => {
1823 base::compare_scalar_types(bcx, lhs, rhs, lhs_t, op.node, binop_debug_loc)
1826 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1830 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1833 // refinement types would obviate the need for this
1834 enum lazy_binop_ty {
1839 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1840 binop_expr: &hir::Expr,
1844 -> DatumBlock<'blk, 'tcx, Expr> {
1845 let _icx = push_ctxt("trans_lazy_binop");
1846 let binop_ty = expr_ty(bcx, binop_expr);
1849 let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1850 let lhs = lhs.to_llscalarish(past_lhs);
1852 if past_lhs.unreachable.get() {
1853 return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1856 let join = fcx.new_id_block("join", binop_expr.id);
1857 let before_rhs = fcx.new_id_block("before_rhs", b.id);
1860 lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1861 lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1864 let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1865 let rhs = rhs.to_llscalarish(past_rhs);
1867 if past_rhs.unreachable.get() {
1868 return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1871 Br(past_rhs, join.llbb, DebugLoc::None);
1872 let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1873 &[past_lhs.llbb, past_rhs.llbb]);
1875 return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1878 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1883 -> DatumBlock<'blk, 'tcx, Expr> {
1884 let _icx = push_ctxt("trans_binary");
1885 let ccx = bcx.ccx();
1887 // if overloaded, would be RvalueDpsExpr
1888 assert!(!ccx.tcx().is_method_call(expr.id));
1892 trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1895 trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1899 let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1900 let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1901 let binop_ty = expr_ty(bcx, expr);
1903 debug!("trans_binary (expr {}): lhs_datum={}",
1905 lhs_datum.to_string(ccx));
1906 let lhs_ty = lhs_datum.ty;
1907 let lhs = lhs_datum.to_llscalarish(bcx);
1909 debug!("trans_binary (expr {}): rhs_datum={}",
1911 rhs_datum.to_string(ccx));
1912 let rhs_ty = rhs_datum.ty;
1913 let rhs = rhs_datum.to_llscalarish(bcx);
1914 trans_eager_binop(bcx, expr, binop_ty, op,
1915 lhs_ty, lhs, rhs_ty, rhs)
1920 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1922 method_call: MethodCall,
1923 lhs: Datum<'tcx, Expr>,
1924 rhs: Option<(Datum<'tcx, Expr>, ast::NodeId)>,
1927 -> Result<'blk, 'tcx> {
1928 callee::trans_call_inner(bcx,
1930 |bcx, arg_cleanup_scope| {
1931 meth::trans_method_callee(bcx,
1936 callee::ArgOverloadedOp(lhs, rhs, autoref),
1940 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1942 callee: &'a hir::Expr,
1943 args: &'a [P<hir::Expr>],
1945 -> Block<'blk, 'tcx> {
1946 debug!("trans_overloaded_call {}", expr.id);
1947 let method_call = MethodCall::expr(expr.id);
1948 let mut all_args = vec!(callee);
1949 all_args.extend(args.iter().map(|e| &**e));
1951 callee::trans_call_inner(bcx,
1953 |bcx, arg_cleanup_scope| {
1954 meth::trans_method_callee(
1960 callee::ArgOverloadedCall(all_args),
1965 pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
1970 if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
1974 match (t_in.builtin_deref(true, ty::NoPreference),
1975 t_out.builtin_deref(true, ty::NoPreference)) {
1976 (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
1980 // This condition isn't redundant with the check for CoercionCast:
1981 // different types can be substituted into the same type, and
1982 // == equality can be overconservative if there are regions.
1988 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1991 -> DatumBlock<'blk, 'tcx, Expr>
1993 use middle::cast::CastTy::*;
1994 use middle::cast::IntTy::*;
1996 fn int_cast(bcx: Block,
2003 let _icx = push_ctxt("int_cast");
2004 let srcsz = llsrctype.int_width();
2005 let dstsz = lldsttype.int_width();
2006 return if dstsz == srcsz {
2007 BitCast(bcx, llsrc, lldsttype)
2008 } else if srcsz > dstsz {
2009 TruncOrBitCast(bcx, llsrc, lldsttype)
2011 SExtOrBitCast(bcx, llsrc, lldsttype)
2013 ZExtOrBitCast(bcx, llsrc, lldsttype)
2017 fn float_cast(bcx: Block,
2023 let _icx = push_ctxt("float_cast");
2024 let srcsz = llsrctype.float_width();
2025 let dstsz = lldsttype.float_width();
2026 return if dstsz > srcsz {
2027 FPExt(bcx, llsrc, lldsttype)
2028 } else if srcsz > dstsz {
2029 FPTrunc(bcx, llsrc, lldsttype)
2033 let _icx = push_ctxt("trans_cast");
2035 let ccx = bcx.ccx();
2037 let t_in = expr_ty_adjusted(bcx, expr);
2038 let t_out = node_id_type(bcx, id);
2040 debug!("trans_cast({:?} as {:?})", t_in, t_out);
2041 let mut ll_t_in = type_of::arg_type_of(ccx, t_in);
2042 let ll_t_out = type_of::arg_type_of(ccx, t_out);
2043 // Convert the value to be cast into a ValueRef, either by-ref or
2044 // by-value as appropriate given its type:
2045 let mut datum = unpack_datum!(bcx, trans(bcx, expr));
2047 let datum_ty = monomorphize_type(bcx, datum.ty);
2049 if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
2051 return DatumBlock::new(bcx, datum);
2054 if type_is_fat_ptr(bcx.tcx(), t_in) {
2055 assert!(datum.kind.is_by_ref());
2056 if type_is_fat_ptr(bcx.tcx(), t_out) {
2057 return DatumBlock::new(bcx, Datum::new(
2058 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
2061 )).to_expr_datumblock();
2063 // Return the address
2064 return immediate_rvalue_bcx(bcx,
2066 Load(bcx, get_dataptr(bcx, datum.val)),
2068 t_out).to_expr_datumblock();
2072 let r_t_in = CastTy::from_ty(t_in).expect("bad input type for cast");
2073 let r_t_out = CastTy::from_ty(t_out).expect("bad output type for cast");
2075 let (llexpr, signed) = if let Int(CEnum) = r_t_in {
2076 let repr = adt::represent_type(ccx, t_in);
2077 let datum = unpack_datum!(
2078 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2079 let llexpr_ptr = datum.to_llref();
2080 let discr = adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2081 ll_t_in = val_ty(discr);
2082 (discr, adt::is_discr_signed(&*repr))
2084 (datum.to_llscalarish(bcx), t_in.is_signed())
2087 let newval = match (r_t_in, r_t_out) {
2088 (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
2089 PointerCast(bcx, llexpr, ll_t_out)
2091 (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
2092 (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
2094 (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
2095 (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
2096 (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
2097 (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
2098 (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
2099 (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
2101 _ => ccx.sess().span_bug(expr.span,
2102 &format!("translating unsupported cast: \
2108 return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2111 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2116 -> Block<'blk, 'tcx> {
2117 let _icx = push_ctxt("trans_assign_op");
2120 debug!("trans_assign_op(expr={:?})", expr);
2122 // User-defined operator methods cannot be used with `+=` etc right now
2123 assert!(!bcx.tcx().is_method_call(expr.id));
2125 // Evaluate LHS (destination), which should be an lvalue
2126 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2127 assert!(!bcx.fcx.type_needs_drop(dst_datum.ty));
2128 let dst_ty = dst_datum.ty;
2129 let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2132 let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2133 let rhs_ty = rhs_datum.ty;
2134 let rhs = rhs_datum.to_llscalarish(bcx);
2136 // Perform computation and store the result
2137 let result_datum = unpack_datum!(
2138 bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2139 dst_ty, dst, rhs_ty, rhs));
2140 return result_datum.store_to(bcx, dst_datum.val);
2143 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2144 datum: Datum<'tcx, Expr>,
2146 -> DatumBlock<'blk, 'tcx, Expr> {
2149 // Ensure cleanup of `datum` if not already scheduled and obtain
2150 // a "by ref" pointer.
2151 let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2153 // Compute final type. Note that we are loose with the region and
2154 // mutability, since those things don't matter in trans.
2155 let referent_ty = lv_datum.ty;
2156 let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2159 let llref = lv_datum.to_llref();
2161 // Construct the resulting datum, using what was the "by ref"
2162 // ValueRef of type `referent_ty` to be the "by value" ValueRef
2163 // of type `&referent_ty`.
2164 // Pointers to DST types are non-immediate, and therefore still use ByRef.
2165 let kind = if type_is_sized(bcx.tcx(), referent_ty) { ByValue } else { ByRef };
2166 DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(kind))))
2169 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2171 datum: Datum<'tcx, Expr>,
2173 -> DatumBlock<'blk, 'tcx, Expr> {
2175 let mut datum = datum;
2177 let method_call = MethodCall::autoderef(expr.id, i as u32);
2178 datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2180 DatumBlock { bcx: bcx, datum: datum }
2183 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2185 datum: Datum<'tcx, Expr>,
2186 method_call: MethodCall)
2187 -> DatumBlock<'blk, 'tcx, Expr> {
2188 let ccx = bcx.ccx();
2190 debug!("deref_once(expr={:?}, datum={}, method_call={:?})",
2192 datum.to_string(ccx),
2197 // Check for overloaded deref.
2198 let method_ty = ccx.tcx()
2202 .get(&method_call).map(|method| method.ty);
2204 let datum = match method_ty {
2205 Some(method_ty) => {
2206 let method_ty = monomorphize_type(bcx, method_ty);
2208 // Overloaded. Evaluate `trans_overloaded_op`, which will
2209 // invoke the user's deref() method, which basically
2210 // converts from the `Smaht<T>` pointer that we have into
2211 // a `&T` pointer. We can then proceed down the normal
2212 // path (below) to dereference that `&T`.
2213 let datum = if method_call.autoderef == 0 {
2216 // Always perform an AutoPtr when applying an overloaded auto-deref
2217 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2220 let ref_ty = // invoked methods have their LB regions instantiated
2221 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2222 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2224 unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2225 datum, None, Some(SaveIn(scratch.val)),
2227 scratch.to_expr_datum()
2230 // Not overloaded. We already have a pointer we know how to deref.
2235 let r = match datum.ty.sty {
2236 ty::TyBox(content_ty) => {
2237 // Make sure we have an lvalue datum here to get the
2238 // proper cleanups scheduled
2239 let datum = unpack_datum!(
2240 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2242 if type_is_sized(bcx.tcx(), content_ty) {
2243 let ptr = load_ty(bcx, datum.val, datum.ty);
2244 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(datum.kind)))
2246 // A fat pointer and a DST lvalue have the same representation
2247 // just different types. Since there is no temporary for `*e`
2248 // here (because it is unsized), we cannot emulate the sized
2249 // object code path for running drop glue and free. Instead,
2250 // we schedule cleanup for `e`, turning it into an lvalue.
2252 let lval = Lvalue::new("expr::deref_once ty_uniq");
2253 let datum = Datum::new(datum.val, content_ty, LvalueExpr(lval));
2254 DatumBlock::new(bcx, datum)
2258 ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
2259 ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
2260 let lval = Lvalue::new("expr::deref_once ptr");
2261 if type_is_sized(bcx.tcx(), content_ty) {
2262 let ptr = datum.to_llscalarish(bcx);
2264 // Always generate an lvalue datum, even if datum.mode is
2265 // an rvalue. This is because datum.mode is only an
2266 // rvalue for non-owning pointers like &T or *T, in which
2267 // case cleanup *is* scheduled elsewhere, by the true
2268 // owner (or, in the case of *T, by the user).
2269 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(lval)))
2271 // A fat pointer and a DST lvalue have the same representation
2272 // just different types.
2273 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr(lval)))
2278 bcx.tcx().sess.span_bug(
2280 &format!("deref invoked on expr of invalid type {:?}",
2285 debug!("deref_once(expr={}, method_call={:?}, result={})",
2286 expr.id, method_call, r.datum.to_string(ccx));
2301 fn codegen_strategy(&self) -> OverflowCodegen {
2302 use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2304 OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2305 OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2306 OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2308 OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2309 OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2314 enum OverflowCodegen {
2315 ViaIntrinsic(OverflowOpViaIntrinsic),
2316 ViaInputCheck(OverflowOpViaInputCheck),
2319 enum OverflowOpViaInputCheck { Shl, Shr, }
2322 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2324 impl OverflowOpViaIntrinsic {
2325 fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2326 let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2327 bcx.ccx().get_intrinsic(&name)
2329 fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str {
2330 use rustc_front::hir::IntTy::*;
2331 use rustc_front::hir::UintTy::*;
2332 use middle::ty::{TyInt, TyUint};
2334 let new_sty = match ty.sty {
2335 TyInt(TyIs) => match &tcx.sess.target.target.target_pointer_width[..] {
2336 "32" => TyInt(TyI32),
2337 "64" => TyInt(TyI64),
2338 _ => panic!("unsupported target word size")
2340 TyUint(TyUs) => match &tcx.sess.target.target.target_pointer_width[..] {
2341 "32" => TyUint(TyU32),
2342 "64" => TyUint(TyU64),
2343 _ => panic!("unsupported target word size")
2345 ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2346 _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2351 OverflowOpViaIntrinsic::Add => match new_sty {
2352 TyInt(TyI8) => "llvm.sadd.with.overflow.i8",
2353 TyInt(TyI16) => "llvm.sadd.with.overflow.i16",
2354 TyInt(TyI32) => "llvm.sadd.with.overflow.i32",
2355 TyInt(TyI64) => "llvm.sadd.with.overflow.i64",
2357 TyUint(TyU8) => "llvm.uadd.with.overflow.i8",
2358 TyUint(TyU16) => "llvm.uadd.with.overflow.i16",
2359 TyUint(TyU32) => "llvm.uadd.with.overflow.i32",
2360 TyUint(TyU64) => "llvm.uadd.with.overflow.i64",
2362 _ => unreachable!(),
2364 OverflowOpViaIntrinsic::Sub => match new_sty {
2365 TyInt(TyI8) => "llvm.ssub.with.overflow.i8",
2366 TyInt(TyI16) => "llvm.ssub.with.overflow.i16",
2367 TyInt(TyI32) => "llvm.ssub.with.overflow.i32",
2368 TyInt(TyI64) => "llvm.ssub.with.overflow.i64",
2370 TyUint(TyU8) => "llvm.usub.with.overflow.i8",
2371 TyUint(TyU16) => "llvm.usub.with.overflow.i16",
2372 TyUint(TyU32) => "llvm.usub.with.overflow.i32",
2373 TyUint(TyU64) => "llvm.usub.with.overflow.i64",
2375 _ => unreachable!(),
2377 OverflowOpViaIntrinsic::Mul => match new_sty {
2378 TyInt(TyI8) => "llvm.smul.with.overflow.i8",
2379 TyInt(TyI16) => "llvm.smul.with.overflow.i16",
2380 TyInt(TyI32) => "llvm.smul.with.overflow.i32",
2381 TyInt(TyI64) => "llvm.smul.with.overflow.i64",
2383 TyUint(TyU8) => "llvm.umul.with.overflow.i8",
2384 TyUint(TyU16) => "llvm.umul.with.overflow.i16",
2385 TyUint(TyU32) => "llvm.umul.with.overflow.i32",
2386 TyUint(TyU64) => "llvm.umul.with.overflow.i64",
2388 _ => unreachable!(),
2393 fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2394 info: NodeIdAndSpan,
2395 lhs_t: Ty<'tcx>, lhs: ValueRef,
2397 binop_debug_loc: DebugLoc)
2398 -> (Block<'blk, 'tcx>, ValueRef) {
2399 let llfn = self.to_intrinsic(bcx, lhs_t);
2401 let val = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
2402 let result = ExtractValue(bcx, val, 0); // iN operation result
2403 let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2405 let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2408 let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2409 Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2410 None, binop_debug_loc);
2413 base::with_cond(bcx, cond, |bcx|
2414 controlflow::trans_fail(bcx, info,
2415 InternedString::new("arithmetic operation overflowed")));
2421 impl OverflowOpViaInputCheck {
2422 fn build_with_input_check<'blk, 'tcx>(&self,
2423 bcx: Block<'blk, 'tcx>,
2424 info: NodeIdAndSpan,
2428 binop_debug_loc: DebugLoc)
2429 -> (Block<'blk, 'tcx>, ValueRef)
2431 let lhs_llty = val_ty(lhs);
2432 let rhs_llty = val_ty(rhs);
2434 // Panic if any bits are set outside of bits that we always
2437 // Note that the mask's value is derived from the LHS type
2438 // (since that is where the 32/64 distinction is relevant) but
2439 // the mask's type must match the RHS type (since they will
2440 // both be fed into a and-binop)
2441 let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2443 let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2444 let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2445 let result = match *self {
2446 OverflowOpViaInputCheck::Shl =>
2447 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2448 OverflowOpViaInputCheck::Shr =>
2449 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2452 base::with_cond(bcx, cond, |bcx|
2453 controlflow::trans_fail(bcx, info,
2454 InternedString::new("shift operation overflowed")));
2460 fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2463 invert: bool) -> ValueRef {
2464 let kind = llty.kind();
2466 TypeKind::Integer => {
2467 // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
2468 let val = llty.int_width() - 1;
2470 C_integral(mask_llty, !val, true)
2472 C_integral(mask_llty, val, false)
2475 TypeKind::Vector => {
2476 let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
2477 VectorSplat(bcx, mask_llty.vector_length(), mask)
2479 _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
2483 // Check if an integer or vector contains a nonzero element.
2484 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2486 binop_debug_loc: DebugLoc) -> ValueRef {
2487 let llty = val_ty(value);
2488 let kind = llty.kind();
2490 TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2491 TypeKind::Vector => {
2492 // Check if any elements of the vector are nonzero by treating
2493 // it as a wide integer and checking if the integer is nonzero.
2494 let width = llty.vector_length() as u64 * llty.element_type().int_width();
2495 let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2496 build_nonzero_check(bcx, int_value, binop_debug_loc)
2498 _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2502 // To avoid UB from LLVM, these two functions mask RHS with an
2503 // appropriate mask unconditionally (i.e. the fallback behavior for
2504 // all shifts). For 32- and 64-bit types, this matches the semantics
2505 // of Java. (See related discussion on #1877 and #10183.)
2507 fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2510 binop_debug_loc: DebugLoc) -> ValueRef {
2511 let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShl, lhs, rhs);
2512 // #1877, #10183: Ensure that input is always valid
2513 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2514 Shl(bcx, lhs, rhs, binop_debug_loc)
2517 fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2521 binop_debug_loc: DebugLoc) -> ValueRef {
2522 let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs);
2523 // #1877, #10183: Ensure that input is always valid
2524 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2525 let is_signed = lhs_t.is_signed();
2527 AShr(bcx, lhs, rhs, binop_debug_loc)
2529 LShr(bcx, lhs, rhs, binop_debug_loc)
2533 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2535 debug_loc: DebugLoc) -> ValueRef {
2536 let rhs_llty = val_ty(rhs);
2537 And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
2540 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2541 lhs_t: Ty<'tcx>, lhs: ValueRef,
2543 binop_debug_loc: DebugLoc)
2544 -> (Block<'blk, 'tcx>, ValueRef) {
2545 if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2546 if bcx.ccx().check_overflow() {
2548 match oop.codegen_strategy() {
2549 OverflowCodegen::ViaIntrinsic(oop) =>
2550 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2551 OverflowCodegen::ViaInputCheck(oop) =>
2552 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2555 let res = match oop {
2556 OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2557 OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2558 OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2561 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2563 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2569 /// We categorize expressions into three kinds. The distinction between
2570 /// lvalue/rvalue is fundamental to the language. The distinction between the
2571 /// two kinds of rvalues is an artifact of trans which reflects how we will
2572 /// generate code for that kind of expression. See trans/expr.rs for more
2574 #[derive(Copy, Clone)]
2582 fn expr_kind(tcx: &ty::ctxt, expr: &hir::Expr) -> ExprKind {
2583 if tcx.is_method_call(expr.id) {
2584 // Overloaded operations are generally calls, and hence they are
2585 // generated via DPS, but there are a few exceptions:
2586 return match expr.node {
2587 // `a += b` has a unit result.
2588 hir::ExprAssignOp(..) => ExprKind::RvalueStmt,
2590 // the deref method invoked for `*a` always yields an `&T`
2591 hir::ExprUnary(hir::UnDeref, _) => ExprKind::Lvalue,
2593 // the index method invoked for `a[i]` always yields an `&T`
2594 hir::ExprIndex(..) => ExprKind::Lvalue,
2596 // in the general case, result could be any type, use DPS
2597 _ => ExprKind::RvalueDps
2602 hir::ExprPath(..) => {
2603 match tcx.resolve_expr(expr) {
2604 def::DefStruct(_) | def::DefVariant(..) => {
2605 if let ty::TyBareFn(..) = tcx.node_id_to_type(expr.id).sty {
2607 ExprKind::RvalueDatum
2613 // Special case: A unit like struct's constructor must be called without () at the
2614 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
2615 // of unit structs this is should not be interpreted as function pointer but as
2616 // call to the constructor.
2617 def::DefFn(_, true) => ExprKind::RvalueDps,
2619 // Fn pointers are just scalar values.
2620 def::DefFn(..) | def::DefMethod(..) => ExprKind::RvalueDatum,
2622 // Note: there is actually a good case to be made that
2623 // DefArg's, particularly those of immediate type, ought to
2624 // considered rvalues.
2625 def::DefStatic(..) |
2627 def::DefLocal(..) => ExprKind::Lvalue,
2630 def::DefAssociatedConst(..) => ExprKind::RvalueDatum,
2635 &format!("uncategorized def for expr {}: {:?}",
2642 hir::ExprUnary(hir::UnDeref, _) |
2643 hir::ExprField(..) |
2644 hir::ExprTupField(..) |
2645 hir::ExprIndex(..) => {
2650 hir::ExprMethodCall(..) |
2651 hir::ExprStruct(..) |
2652 hir::ExprRange(..) |
2655 hir::ExprMatch(..) |
2656 hir::ExprClosure(..) |
2657 hir::ExprBlock(..) |
2658 hir::ExprRepeat(..) |
2659 hir::ExprVec(..) => {
2663 hir::ExprLit(ref lit) if rustc_front::util::lit_is_str(&**lit) => {
2667 hir::ExprBreak(..) |
2668 hir::ExprAgain(..) |
2670 hir::ExprWhile(..) |
2672 hir::ExprAssign(..) |
2673 hir::ExprInlineAsm(..) |
2674 hir::ExprAssignOp(..) => {
2675 ExprKind::RvalueStmt
2678 hir::ExprLit(_) | // Note: LitStr is carved out above
2679 hir::ExprUnary(..) |
2680 hir::ExprBox(None, _) |
2681 hir::ExprAddrOf(..) |
2682 hir::ExprBinary(..) |
2683 hir::ExprCast(..) => {
2684 ExprKind::RvalueDatum
2687 hir::ExprBox(Some(ref place), _) => {
2688 // Special case `Box<T>` for now:
2689 let def_id = match tcx.def_map.borrow().get(&place.id) {
2690 Some(def) => def.def_id(),
2691 None => panic!("no def for place"),
2693 if tcx.lang_items.exchange_heap() == Some(def_id) {
2694 ExprKind::RvalueDatum
2700 hir::ExprParen(ref e) => expr_kind(tcx, &**e),