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.
12 use rustc::middle::ty::{self, Ty};
13 use middle::ty::cast::{CastTy, IntTy};
14 use rustc::mir::repr as mir;
18 use trans::common::{self, BlockAndBuilder, Result};
19 use trans::debuginfo::DebugLoc;
24 use trans::type_::Type;
29 use super::MirContext;
30 use super::operand::{OperandRef, OperandValue};
31 use super::lvalue::LvalueRef;
33 impl<'bcx, 'tcx> MirContext<'bcx, 'tcx> {
34 pub fn trans_rvalue(&mut self,
35 bcx: BlockAndBuilder<'bcx, 'tcx>,
36 dest: LvalueRef<'tcx>,
37 rvalue: &mir::Rvalue<'tcx>)
38 -> BlockAndBuilder<'bcx, 'tcx>
40 debug!("trans_rvalue(dest.llval={}, rvalue={:?})",
41 bcx.val_to_string(dest.llval),
45 mir::Rvalue::Use(ref operand) => {
46 let tr_operand = self.trans_operand(&bcx, operand);
47 // FIXME: consider not copying constants through stack. (fixable by translating
48 // constants into OperandValue::Ref, why don’t we do that yet if we don’t?)
49 self.store_operand(&bcx, dest.llval, tr_operand);
50 self.set_operand_dropped(&bcx, operand);
54 mir::Rvalue::Cast(mir::CastKind::Unsize, ref operand, cast_ty) => {
55 if common::type_is_fat_ptr(bcx.tcx(), cast_ty) {
56 // into-coerce of a thin pointer to a fat pointer - just
57 // use the operand path.
58 let (bcx, temp) = self.trans_rvalue_operand(bcx, rvalue);
59 self.store_operand(&bcx, dest.llval, temp);
63 // Unsize of a nontrivial struct. I would prefer for
64 // this to be eliminated by MIR translation, but
65 // `CoerceUnsized` can be passed by a where-clause,
66 // so the (generic) MIR may not be able to expand it.
67 let operand = self.trans_operand(&bcx, operand);
68 bcx.with_block(|bcx| {
70 OperandValue::FatPtr(..) => unreachable!(),
71 OperandValue::Immediate(llval) => {
72 // unsize from an immediate structure. We don't
73 // really need a temporary alloca here, but
74 // avoiding it would require us to have
75 // `coerce_unsized_into` use extractvalue to
76 // index into the struct, and this case isn't
77 // important enough for it.
78 debug!("trans_rvalue: creating ugly alloca");
79 let lltemp = base::alloc_ty(bcx, operand.ty, "__unsize_temp");
80 base::store_ty(bcx, llval, lltemp, operand.ty);
81 base::coerce_unsized_into(bcx,
85 OperandValue::Ref(llref) => {
86 base::coerce_unsized_into(bcx,
95 mir::Rvalue::Repeat(ref elem, ref count) => {
96 let tr_elem = self.trans_operand(&bcx, elem);
97 let size = self.trans_constval(&bcx, &count.value, count.ty).immediate();
98 let bcx = bcx.map_block(|block| {
99 let base = expr::get_dataptr(block, dest.llval);
100 tvec::iter_vec_raw(block, base, tr_elem.ty, size, |block, llslot, _| {
101 self.store_operand_direct(block, llslot, tr_elem);
105 self.set_operand_dropped(&bcx, elem);
109 mir::Rvalue::Aggregate(ref kind, ref operands) => {
111 mir::AggregateKind::Adt(adt_def, index, _) => {
112 let repr = adt::represent_type(bcx.ccx(), dest.ty.to_ty(bcx.tcx()));
113 let disr = Disr::from(adt_def.variants[index].disr_val);
114 bcx.with_block(|bcx| {
115 adt::trans_set_discr(bcx, &repr, dest.llval, Disr::from(disr));
117 for (i, operand) in operands.iter().enumerate() {
118 let op = self.trans_operand(&bcx, operand);
119 // Do not generate stores and GEPis for zero-sized fields.
120 if !common::type_is_zero_size(bcx.ccx(), op.ty) {
121 let val = adt::MaybeSizedValue::sized(dest.llval);
122 let lldest_i = bcx.with_block(|bcx| {
123 adt::trans_field_ptr(bcx, &repr, val, disr, i)
125 self.store_operand(&bcx, lldest_i, op);
126 self.set_operand_dropped(&bcx, operand);
131 for (i, operand) in operands.iter().enumerate() {
132 let op = self.trans_operand(&bcx, operand);
133 // Do not generate stores and GEPis for zero-sized fields.
134 if !common::type_is_zero_size(bcx.ccx(), op.ty) {
135 // Note: perhaps this should be StructGep, but
136 // note that in some cases the values here will
137 // not be structs but arrays.
138 let dest = bcx.gepi(dest.llval, &[0, i]);
139 self.store_operand(&bcx, dest, op);
140 self.set_operand_dropped(&bcx, operand);
148 mir::Rvalue::Slice { ref input, from_start, from_end } => {
150 let input = self.trans_lvalue(&bcx, input);
151 let (llbase, lllen) = bcx.with_block(|bcx| {
152 tvec::get_base_and_len(bcx,
154 input.ty.to_ty(bcx.tcx()))
156 let llbase1 = bcx.gepi(llbase, &[from_start]);
157 let adj = common::C_uint(ccx, from_start + from_end);
158 let lllen1 = bcx.sub(lllen, adj);
159 let (lladdrdest, llmetadest) = bcx.with_block(|bcx| {
160 (expr::get_dataptr(bcx, dest.llval), expr::get_meta(bcx, dest.llval))
162 bcx.store(llbase1, lladdrdest);
163 bcx.store(lllen1, llmetadest);
167 mir::Rvalue::InlineAsm(ref inline_asm) => {
168 bcx.map_block(|bcx| {
169 asm::trans_inline_asm(bcx, inline_asm)
174 assert!(rvalue_creates_operand(rvalue));
175 let (bcx, temp) = self.trans_rvalue_operand(bcx, rvalue);
176 self.store_operand(&bcx, dest.llval, temp);
182 pub fn trans_rvalue_operand(&mut self,
183 bcx: BlockAndBuilder<'bcx, 'tcx>,
184 rvalue: &mir::Rvalue<'tcx>)
185 -> (BlockAndBuilder<'bcx, 'tcx>, OperandRef<'tcx>)
187 assert!(rvalue_creates_operand(rvalue), "cannot trans {:?} to operand", rvalue);
190 mir::Rvalue::Cast(ref kind, ref operand, cast_ty) => {
191 let operand = self.trans_operand(&bcx, operand);
192 debug!("cast operand is {}", operand.repr(&bcx));
193 let cast_ty = bcx.monomorphize(&cast_ty);
195 let val = match *kind {
196 mir::CastKind::ReifyFnPointer |
197 mir::CastKind::UnsafeFnPointer => {
198 // these are no-ops at the LLVM level
201 mir::CastKind::Unsize => {
202 // unsize targets other than to a fat pointer currently
203 // can't be operands.
204 assert!(common::type_is_fat_ptr(bcx.tcx(), cast_ty));
207 OperandValue::FatPtr(..) => {
208 // unsize from a fat pointer - this is a
209 // "trait-object-to-supertrait" coercion, for
211 // &'a fmt::Debug+Send => &'a fmt::Debug,
212 // and is a no-op at the LLVM level
215 OperandValue::Immediate(lldata) => {
217 let (lldata, llextra) = bcx.with_block(|bcx| {
218 base::unsize_thin_ptr(bcx, lldata,
221 OperandValue::FatPtr(lldata, llextra)
223 OperandValue::Ref(_) => {
225 &format!("by-ref operand {} in trans_rvalue_operand",
226 operand.repr(&bcx)));
230 mir::CastKind::Misc if common::type_is_immediate(bcx.ccx(), operand.ty) => {
231 debug_assert!(common::type_is_immediate(bcx.ccx(), cast_ty));
232 let r_t_in = CastTy::from_ty(operand.ty).expect("bad input type for cast");
233 let r_t_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
234 let ll_t_in = type_of::arg_type_of(bcx.ccx(), operand.ty);
235 let ll_t_out = type_of::arg_type_of(bcx.ccx(), cast_ty);
236 let (llval, ll_t_in, signed) = if let CastTy::Int(IntTy::CEnum) = r_t_in {
237 let repr = adt::represent_type(bcx.ccx(), operand.ty);
238 let llval = operand.immediate();
239 let discr = bcx.with_block(|bcx| {
240 adt::trans_get_discr(bcx, &repr, llval, None, true)
242 (discr, common::val_ty(discr), adt::is_discr_signed(&repr))
244 (operand.immediate(), ll_t_in, operand.ty.is_signed())
247 let newval = match (r_t_in, r_t_out) {
248 (CastTy::Int(_), CastTy::Int(_)) => {
249 let srcsz = ll_t_in.int_width();
250 let dstsz = ll_t_out.int_width();
252 bcx.bitcast(llval, ll_t_out)
253 } else if srcsz > dstsz {
254 bcx.trunc(llval, ll_t_out)
256 bcx.sext(llval, ll_t_out)
258 bcx.zext(llval, ll_t_out)
261 (CastTy::Float, CastTy::Float) => {
262 let srcsz = ll_t_in.float_width();
263 let dstsz = ll_t_out.float_width();
265 bcx.fpext(llval, ll_t_out)
266 } else if srcsz > dstsz {
267 bcx.fptrunc(llval, ll_t_out)
272 (CastTy::Ptr(_), CastTy::Ptr(_)) |
273 (CastTy::FnPtr, CastTy::Ptr(_)) |
274 (CastTy::RPtr(_), CastTy::Ptr(_)) =>
275 bcx.pointercast(llval, ll_t_out),
276 (CastTy::Ptr(_), CastTy::Int(_)) |
277 (CastTy::FnPtr, CastTy::Int(_)) =>
278 bcx.ptrtoint(llval, ll_t_out),
279 (CastTy::Int(_), CastTy::Ptr(_)) =>
280 bcx.inttoptr(llval, ll_t_out),
281 (CastTy::Int(_), CastTy::Float) if signed =>
282 bcx.sitofp(llval, ll_t_out),
283 (CastTy::Int(_), CastTy::Float) =>
284 bcx.uitofp(llval, ll_t_out),
285 (CastTy::Float, CastTy::Int(IntTy::I)) =>
286 bcx.fptosi(llval, ll_t_out),
287 (CastTy::Float, CastTy::Int(_)) =>
288 bcx.fptoui(llval, ll_t_out),
289 _ => bcx.ccx().sess().bug(
290 &format!("unsupported cast: {:?} to {:?}", operand.ty, cast_ty)
293 OperandValue::Immediate(newval)
295 mir::CastKind::Misc => { // Casts from a fat-ptr.
296 let ll_cast_ty = type_of::arg_type_of(bcx.ccx(), cast_ty);
297 let ll_from_ty = type_of::arg_type_of(bcx.ccx(), operand.ty);
298 if let OperandValue::FatPtr(data_ptr, meta_ptr) = operand.val {
299 if common::type_is_fat_ptr(bcx.tcx(), cast_ty) {
300 let ll_cft = ll_cast_ty.field_types();
301 let ll_fft = ll_from_ty.field_types();
302 let data_cast = bcx.pointercast(data_ptr, ll_cft[0]);
303 assert_eq!(ll_cft[1].kind(), ll_fft[1].kind());
304 OperandValue::FatPtr(data_cast, meta_ptr)
305 } else { // cast to thin-ptr
306 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
307 // pointer-cast of that pointer to desired pointer type.
308 let llval = bcx.pointercast(data_ptr, ll_cast_ty);
309 OperandValue::Immediate(llval)
312 panic!("Unexpected non-FatPtr operand")
316 let operand = OperandRef {
323 mir::Rvalue::Ref(_, bk, ref lvalue) => {
324 let tr_lvalue = self.trans_lvalue(&bcx, lvalue);
326 let ty = tr_lvalue.ty.to_ty(bcx.tcx());
327 let ref_ty = bcx.tcx().mk_ref(
328 bcx.tcx().mk_region(ty::ReStatic),
329 ty::TypeAndMut { ty: ty, mutbl: bk.to_mutbl_lossy() }
332 // Note: lvalues are indirect, so storing the `llval` into the
333 // destination effectively creates a reference.
334 let operand = if common::type_is_sized(bcx.tcx(), ty) {
336 val: OperandValue::Immediate(tr_lvalue.llval),
341 val: OperandValue::FatPtr(tr_lvalue.llval,
349 mir::Rvalue::Len(ref lvalue) => {
350 let tr_lvalue = self.trans_lvalue(&bcx, lvalue);
351 let operand = OperandRef {
352 val: OperandValue::Immediate(self.lvalue_len(&bcx, tr_lvalue)),
353 ty: bcx.tcx().types.usize,
358 mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
359 let lhs = self.trans_operand(&bcx, lhs);
360 let rhs = self.trans_operand(&bcx, rhs);
361 let llresult = if common::type_is_fat_ptr(bcx.tcx(), lhs.ty) {
362 match (lhs.val, rhs.val) {
363 (OperandValue::FatPtr(lhs_addr, lhs_extra),
364 OperandValue::FatPtr(rhs_addr, rhs_extra)) => {
365 bcx.with_block(|bcx| {
366 base::compare_fat_ptrs(bcx,
369 lhs.ty, op.to_hir_binop(),
377 self.trans_scalar_binop(&bcx, op,
378 lhs.immediate(), rhs.immediate(),
381 let operand = OperandRef {
382 val: OperandValue::Immediate(llresult),
383 ty: self.mir.binop_ty(bcx.tcx(), op, lhs.ty, rhs.ty),
388 mir::Rvalue::UnaryOp(op, ref operand) => {
389 let operand = self.trans_operand(&bcx, operand);
390 let lloperand = operand.immediate();
391 let is_float = operand.ty.is_fp();
392 let llval = match op {
393 mir::UnOp::Not => bcx.not(lloperand),
394 mir::UnOp::Neg => if is_float {
401 val: OperandValue::Immediate(llval),
406 mir::Rvalue::Box(content_ty) => {
407 let content_ty: Ty<'tcx> = bcx.monomorphize(&content_ty);
408 let llty = type_of::type_of(bcx.ccx(), content_ty);
409 let llsize = machine::llsize_of(bcx.ccx(), llty);
410 let align = type_of::align_of(bcx.ccx(), content_ty);
411 let llalign = common::C_uint(bcx.ccx(), align);
412 let llty_ptr = llty.ptr_to();
413 let box_ty = bcx.tcx().mk_box(content_ty);
414 let mut llval = None;
415 let bcx = bcx.map_block(|bcx| {
416 let Result { bcx, val } = base::malloc_raw_dyn(bcx,
425 let operand = OperandRef {
426 val: OperandValue::Immediate(llval.unwrap()),
432 mir::Rvalue::Use(..) |
433 mir::Rvalue::Repeat(..) |
434 mir::Rvalue::Aggregate(..) |
435 mir::Rvalue::Slice { .. } |
436 mir::Rvalue::InlineAsm(..) => {
437 bcx.tcx().sess.bug(&format!("cannot generate operand from rvalue {:?}", rvalue));
442 pub fn trans_scalar_binop(&mut self,
443 bcx: &BlockAndBuilder<'bcx, 'tcx>,
447 input_ty: Ty<'tcx>) -> ValueRef {
448 let is_float = input_ty.is_fp();
449 let is_signed = input_ty.is_signed();
451 mir::BinOp::Add => if is_float {
456 mir::BinOp::Sub => if is_float {
461 mir::BinOp::Mul => if is_float {
466 mir::BinOp::Div => if is_float {
468 } else if is_signed {
473 mir::BinOp::Rem => if is_float {
474 // LLVM currently always lowers the `frem` instructions appropriate
475 // library calls typically found in libm. Notably f64 gets wired up
476 // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
477 // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
478 // instead just an inline function in a header that goes up to a
479 // f64, uses `fmod`, and then comes back down to a f32.
481 // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
482 // still unconditionally lower frem instructions over 32-bit floats
483 // to a call to `fmodf`. To work around this we special case MSVC
484 // 32-bit float rem instructions and instead do the call out to
487 // Note that this is currently duplicated with src/libcore/ops.rs
488 // which does the same thing, and it would be nice to perhaps unify
489 // these two implementations one day! Also note that we call `fmod`
490 // for both 32 and 64-bit floats because if we emit any FRem
491 // instruction at all then LLVM is capable of optimizing it into a
492 // 32-bit FRem (which we're trying to avoid).
494 let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
495 tcx.sess.target.target.arch == "x86";
497 let f64t = Type::f64(bcx.ccx());
498 let fty = Type::func(&[f64t, f64t], &f64t);
499 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty,
501 if input_ty == tcx.types.f32 {
502 let lllhs = bcx.fpext(lhs, f64t);
503 let llrhs = bcx.fpext(rhs, f64t);
504 let llres = bcx.call(llfn, &[lllhs, llrhs], None, None);
505 bcx.fptrunc(llres, Type::f32(bcx.ccx()))
507 bcx.call(llfn, &[lhs, rhs], None, None)
512 } else if is_signed {
517 mir::BinOp::BitOr => bcx.or(lhs, rhs),
518 mir::BinOp::BitAnd => bcx.and(lhs, rhs),
519 mir::BinOp::BitXor => bcx.xor(lhs, rhs),
521 bcx.with_block(|bcx| {
522 common::build_unchecked_lshift(bcx,
529 bcx.with_block(|bcx| {
530 common::build_unchecked_rshift(bcx,
537 mir::BinOp::Eq | mir::BinOp::Lt | mir::BinOp::Gt |
538 mir::BinOp::Ne | mir::BinOp::Le | mir::BinOp::Ge => {
539 bcx.with_block(|bcx| {
540 base::compare_scalar_types(bcx, lhs, rhs, input_ty,
541 op.to_hir_binop(), DebugLoc::None)
548 pub fn rvalue_creates_operand<'tcx>(rvalue: &mir::Rvalue<'tcx>) -> bool {
550 mir::Rvalue::Ref(..) |
551 mir::Rvalue::Len(..) |
552 mir::Rvalue::Cast(..) | // (*)
553 mir::Rvalue::BinaryOp(..) |
554 mir::Rvalue::UnaryOp(..) |
555 mir::Rvalue::Box(..) =>
557 mir::Rvalue::Use(..) | // (**)
558 mir::Rvalue::Repeat(..) |
559 mir::Rvalue::Aggregate(..) |
560 mir::Rvalue::Slice { .. } |
561 mir::Rvalue::InlineAsm(..) =>
565 // (*) this is only true if the type is suitable
566 // (**) we need to zero-out the source operand after moving, so we are restricted to either
567 // ensuring all users of `Use` zero it out themselves or not allowing to “create” operand for