1 use rustc::ty::{self, Ty};
2 use rustc::ty::cast::{CastTy, IntTy};
3 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt};
5 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
6 use rustc_apfloat::{ieee, Float, Status, Round};
12 use crate::common::{self, RealPredicate, IntPredicate};
13 use rustc_mir::monomorphize;
17 use super::{FunctionCx, LocalRef};
18 use super::operand::{OperandRef, OperandValue};
19 use super::place::PlaceRef;
21 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
22 pub fn codegen_rvalue(
25 dest: PlaceRef<'tcx, Bx::Value>,
26 rvalue: &mir::Rvalue<'tcx>
28 debug!("codegen_rvalue(dest.llval={:?}, rvalue={:?})",
32 mir::Rvalue::Use(ref operand) => {
33 let cg_operand = self.codegen_operand(&mut bx, operand);
34 // FIXME: consider not copying constants through stack. (fixable by codegenning
35 // constants into OperandValue::Ref, why don’t we do that yet if we don’t?)
36 cg_operand.val.store(&mut bx, dest);
40 mir::Rvalue::Cast(mir::CastKind::Unsize, ref source, _) => {
41 // The destination necessarily contains a fat pointer, so if
42 // it's a scalar pair, it's a fat pointer or newtype thereof.
43 if bx.cx().is_backend_scalar_pair(dest.layout) {
44 // into-coerce of a thin pointer to a fat pointer - just
45 // use the operand path.
46 let (mut bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
47 temp.val.store(&mut bx, dest);
51 // Unsize of a nontrivial struct. I would prefer for
52 // this to be eliminated by MIR building, but
53 // `CoerceUnsized` can be passed by a where-clause,
54 // so the (generic) MIR may not be able to expand it.
55 let operand = self.codegen_operand(&mut bx, source);
57 OperandValue::Pair(..) |
58 OperandValue::Immediate(_) => {
59 // unsize from an immediate structure. We don't
60 // really need a temporary alloca here, but
61 // avoiding it would require us to have
62 // `coerce_unsized_into` use extractvalue to
63 // index into the struct, and this case isn't
64 // important enough for it.
65 debug!("codegen_rvalue: creating ugly alloca");
66 let scratch = PlaceRef::alloca(&mut bx, operand.layout, "__unsize_temp");
67 scratch.storage_live(&mut bx);
68 operand.val.store(&mut bx, scratch);
69 base::coerce_unsized_into(&mut bx, scratch, dest);
70 scratch.storage_dead(&mut bx);
72 OperandValue::Ref(llref, None, align) => {
73 let source = PlaceRef::new_sized(llref, operand.layout, align);
74 base::coerce_unsized_into(&mut bx, source, dest);
76 OperandValue::Ref(_, Some(_), _) => {
77 bug!("unsized coercion on an unsized rvalue")
83 mir::Rvalue::Repeat(ref elem, count) => {
84 let cg_elem = self.codegen_operand(&mut bx, elem);
86 // Do not generate the loop for zero-sized elements or empty arrays.
87 if dest.layout.is_zst() {
90 let zero = bx.cx().const_usize(0);
91 let start = dest.project_index(&mut bx, zero).llval;
93 if let OperandValue::Immediate(v) = cg_elem.val {
94 let size = bx.cx().const_usize(dest.layout.size.bytes());
96 // Use llvm.memset.p0i8.* to initialize all zero arrays
97 if bx.cx().is_const_integral(v) && bx.cx().const_to_uint(v) == 0 {
98 let fill = bx.cx().const_u8(0);
99 bx.memset(start, fill, size, dest.align, MemFlags::empty());
103 // Use llvm.memset.p0i8.* to initialize byte arrays
104 let v = base::from_immediate(&mut bx, v);
105 if bx.cx().val_ty(v) == bx.cx().type_i8() {
106 bx.memset(start, v, size, dest.align, MemFlags::empty());
111 let count = bx.cx().const_usize(count);
112 let end = dest.project_index(&mut bx, count).llval;
114 let mut header_bx = bx.build_sibling_block("repeat_loop_header");
115 let mut body_bx = bx.build_sibling_block("repeat_loop_body");
116 let next_bx = bx.build_sibling_block("repeat_loop_next");
118 bx.br(header_bx.llbb());
119 let current = header_bx.phi(bx.cx().val_ty(start), &[start], &[bx.llbb()]);
121 let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
122 header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
124 let align = dest.align.restrict_for_offset(dest.layout.field(bx.cx(), 0).size);
125 cg_elem.val.store(&mut body_bx,
126 PlaceRef::new_sized(current, cg_elem.layout, align));
128 let next = body_bx.inbounds_gep(current, &[bx.cx().const_usize(1)]);
129 body_bx.br(header_bx.llbb());
130 header_bx.add_incoming_to_phi(current, next, body_bx.llbb());
135 mir::Rvalue::Aggregate(ref kind, ref operands) => {
136 let (dest, active_field_index) = match **kind {
137 mir::AggregateKind::Adt(adt_def, variant_index, _, _, active_field_index) => {
138 dest.codegen_set_discr(&mut bx, variant_index);
139 if adt_def.is_enum() {
140 (dest.project_downcast(&mut bx, variant_index), active_field_index)
142 (dest, active_field_index)
147 for (i, operand) in operands.iter().enumerate() {
148 let op = self.codegen_operand(&mut bx, operand);
149 // Do not generate stores and GEPis for zero-sized fields.
150 if !op.layout.is_zst() {
151 let field_index = active_field_index.unwrap_or(i);
152 let field = dest.project_field(&mut bx, field_index);
153 op.val.store(&mut bx, field);
160 assert!(self.rvalue_creates_operand(rvalue));
161 let (mut bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
162 temp.val.store(&mut bx, dest);
168 pub fn codegen_rvalue_unsized(
171 indirect_dest: PlaceRef<'tcx, Bx::Value>,
172 rvalue: &mir::Rvalue<'tcx>,
174 debug!("codegen_rvalue_unsized(indirect_dest.llval={:?}, rvalue={:?})",
175 indirect_dest.llval, rvalue);
178 mir::Rvalue::Use(ref operand) => {
179 let cg_operand = self.codegen_operand(&mut bx, operand);
180 cg_operand.val.store_unsized(&mut bx, indirect_dest);
184 _ => bug!("unsized assignment other than Rvalue::Use"),
188 pub fn codegen_rvalue_operand(
191 rvalue: &mir::Rvalue<'tcx>
192 ) -> (Bx, OperandRef<'tcx, Bx::Value>) {
193 assert!(self.rvalue_creates_operand(rvalue), "cannot codegen {:?} to operand", rvalue);
196 mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
197 let operand = self.codegen_operand(&mut bx, source);
198 debug!("cast operand is {:?}", operand);
199 let cast = bx.cx().layout_of(self.monomorphize(&mir_cast_ty));
201 let val = match *kind {
202 mir::CastKind::ReifyFnPointer => {
203 match operand.layout.ty.sty {
204 ty::FnDef(def_id, substs) => {
205 if bx.cx().tcx().has_attr(def_id, "rustc_args_required_const") {
206 bug!("reifying a fn ptr that requires \
209 OperandValue::Immediate(
210 callee::resolve_and_get_fn(bx.cx(), def_id, substs))
213 bug!("{} cannot be reified to a fn ptr", operand.layout.ty)
217 mir::CastKind::ClosureFnPointer => {
218 match operand.layout.ty.sty {
219 ty::Closure(def_id, substs) => {
220 let instance = monomorphize::resolve_closure(
221 bx.cx().tcx(), def_id, substs, ty::ClosureKind::FnOnce);
222 OperandValue::Immediate(bx.cx().get_fn(instance))
225 bug!("{} cannot be cast to a fn ptr", operand.layout.ty)
229 mir::CastKind::UnsafeFnPointer => {
230 // this is a no-op at the LLVM level
233 mir::CastKind::Unsize => {
234 assert!(bx.cx().is_backend_scalar_pair(cast));
236 OperandValue::Pair(lldata, llextra) => {
237 // unsize from a fat pointer - this is a
238 // "trait-object-to-supertrait" coercion, for
240 // &'a fmt::Debug+Send => &'a fmt::Debug,
242 // HACK(eddyb) have to bitcast pointers
243 // until LLVM removes pointee types.
244 let lldata = bx.pointercast(lldata,
245 bx.cx().scalar_pair_element_backend_type(cast, 0, true));
246 OperandValue::Pair(lldata, llextra)
248 OperandValue::Immediate(lldata) => {
250 let (lldata, llextra) = base::unsize_thin_ptr(&mut bx, lldata,
251 operand.layout.ty, cast.ty);
252 OperandValue::Pair(lldata, llextra)
254 OperandValue::Ref(..) => {
255 bug!("by-ref operand {:?} in codegen_rvalue_operand",
260 mir::CastKind::Misc if bx.cx().is_backend_scalar_pair(operand.layout) => {
261 if let OperandValue::Pair(data_ptr, meta) = operand.val {
262 if bx.cx().is_backend_scalar_pair(cast) {
263 let data_cast = bx.pointercast(data_ptr,
264 bx.cx().scalar_pair_element_backend_type(cast, 0, true));
265 OperandValue::Pair(data_cast, meta)
266 } else { // cast to thin-ptr
267 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
268 // pointer-cast of that pointer to desired pointer type.
269 let llcast_ty = bx.cx().immediate_backend_type(cast);
270 let llval = bx.pointercast(data_ptr, llcast_ty);
271 OperandValue::Immediate(llval)
274 bug!("Unexpected non-Pair operand")
277 mir::CastKind::Misc => {
278 assert!(bx.cx().is_backend_immediate(cast));
279 let ll_t_out = bx.cx().immediate_backend_type(cast);
280 if operand.layout.abi.is_uninhabited() {
281 let val = OperandValue::Immediate(bx.cx().const_undef(ll_t_out));
282 return (bx, OperandRef {
287 let r_t_in = CastTy::from_ty(operand.layout.ty)
288 .expect("bad input type for cast");
289 let r_t_out = CastTy::from_ty(cast.ty).expect("bad output type for cast");
290 let ll_t_in = bx.cx().immediate_backend_type(operand.layout);
291 match operand.layout.variants {
292 layout::Variants::Single { index } => {
293 if let Some(def) = operand.layout.ty.ty_adt_def() {
295 .discriminant_for_variant(bx.cx().tcx(), index)
297 let discr = bx.cx().const_uint_big(ll_t_out, discr_val);
298 return (bx, OperandRef {
299 val: OperandValue::Immediate(discr),
304 layout::Variants::Tagged { .. } |
305 layout::Variants::NicheFilling { .. } => {},
307 let llval = operand.immediate();
309 let mut signed = false;
310 if let layout::Abi::Scalar(ref scalar) = operand.layout.abi {
311 if let layout::Int(_, s) = scalar.value {
312 // We use `i1` for bytes that are always `0` or `1`,
313 // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
314 // let LLVM interpret the `i1` as signed, because
315 // then `i1 1` (i.e., E::B) is effectively `i8 -1`.
316 signed = !scalar.is_bool() && s;
318 let er = scalar.valid_range_exclusive(bx.cx());
319 if er.end != er.start &&
320 scalar.valid_range.end() > scalar.valid_range.start() {
321 // We want `table[e as usize]` to not
322 // have bound checks, and this is the most
323 // convenient place to put the `assume`.
325 bx.cx().const_uint_big(ll_t_in, *scalar.valid_range.end());
327 IntPredicate::IntULE,
336 let newval = match (r_t_in, r_t_out) {
337 (CastTy::Int(_), CastTy::Int(_)) => {
338 bx.intcast(llval, ll_t_out, signed)
340 (CastTy::Float, CastTy::Float) => {
341 let srcsz = bx.cx().float_width(ll_t_in);
342 let dstsz = bx.cx().float_width(ll_t_out);
344 bx.fpext(llval, ll_t_out)
345 } else if srcsz > dstsz {
346 bx.fptrunc(llval, ll_t_out)
351 (CastTy::Ptr(_), CastTy::Ptr(_)) |
352 (CastTy::FnPtr, CastTy::Ptr(_)) |
353 (CastTy::RPtr(_), CastTy::Ptr(_)) =>
354 bx.pointercast(llval, ll_t_out),
355 (CastTy::Ptr(_), CastTy::Int(_)) |
356 (CastTy::FnPtr, CastTy::Int(_)) =>
357 bx.ptrtoint(llval, ll_t_out),
358 (CastTy::Int(_), CastTy::Ptr(_)) => {
359 let usize_llval = bx.intcast(llval, bx.cx().type_isize(), signed);
360 bx.inttoptr(usize_llval, ll_t_out)
362 (CastTy::Int(_), CastTy::Float) =>
363 cast_int_to_float(&mut bx, signed, llval, ll_t_in, ll_t_out),
364 (CastTy::Float, CastTy::Int(IntTy::I)) =>
365 cast_float_to_int(&mut bx, true, llval, ll_t_in, ll_t_out),
366 (CastTy::Float, CastTy::Int(_)) =>
367 cast_float_to_int(&mut bx, false, llval, ll_t_in, ll_t_out),
368 _ => bug!("unsupported cast: {:?} to {:?}", operand.layout.ty, cast.ty)
370 OperandValue::Immediate(newval)
379 mir::Rvalue::Ref(_, bk, ref place) => {
380 let cg_place = self.codegen_place(&mut bx, place);
382 let ty = cg_place.layout.ty;
384 // Note: places are indirect, so storing the `llval` into the
385 // destination effectively creates a reference.
386 let val = if !bx.cx().type_has_metadata(ty) {
387 OperandValue::Immediate(cg_place.llval)
389 OperandValue::Pair(cg_place.llval, cg_place.llextra.unwrap())
393 layout: self.cx.layout_of(self.cx.tcx().mk_ref(
394 self.cx.tcx().types.re_erased,
395 ty::TypeAndMut { ty, mutbl: bk.to_mutbl_lossy() }
400 mir::Rvalue::Len(ref place) => {
401 let size = self.evaluate_array_len(&mut bx, place);
402 let operand = OperandRef {
403 val: OperandValue::Immediate(size),
404 layout: bx.cx().layout_of(bx.tcx().types.usize),
409 mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
410 let lhs = self.codegen_operand(&mut bx, lhs);
411 let rhs = self.codegen_operand(&mut bx, rhs);
412 let llresult = match (lhs.val, rhs.val) {
413 (OperandValue::Pair(lhs_addr, lhs_extra),
414 OperandValue::Pair(rhs_addr, rhs_extra)) => {
415 self.codegen_fat_ptr_binop(&mut bx, op,
421 (OperandValue::Immediate(lhs_val),
422 OperandValue::Immediate(rhs_val)) => {
423 self.codegen_scalar_binop(&mut bx, op, lhs_val, rhs_val, lhs.layout.ty)
428 let operand = OperandRef {
429 val: OperandValue::Immediate(llresult),
430 layout: bx.cx().layout_of(
431 op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
435 mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
436 let lhs = self.codegen_operand(&mut bx, lhs);
437 let rhs = self.codegen_operand(&mut bx, rhs);
438 let result = self.codegen_scalar_checked_binop(&mut bx, op,
439 lhs.immediate(), rhs.immediate(),
441 let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
442 let operand_ty = bx.tcx().intern_tup(&[val_ty, bx.tcx().types.bool]);
443 let operand = OperandRef {
445 layout: bx.cx().layout_of(operand_ty)
451 mir::Rvalue::UnaryOp(op, ref operand) => {
452 let operand = self.codegen_operand(&mut bx, operand);
453 let lloperand = operand.immediate();
454 let is_float = operand.layout.ty.is_fp();
455 let llval = match op {
456 mir::UnOp::Not => bx.not(lloperand),
457 mir::UnOp::Neg => if is_float {
464 val: OperandValue::Immediate(llval),
465 layout: operand.layout,
469 mir::Rvalue::Discriminant(ref place) => {
470 let discr_ty = rvalue.ty(&*self.mir, bx.tcx());
471 let discr = self.codegen_place(&mut bx, place)
472 .codegen_get_discr(&mut bx, discr_ty);
474 val: OperandValue::Immediate(discr),
475 layout: self.cx.layout_of(discr_ty)
479 mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
480 assert!(bx.cx().type_is_sized(ty));
481 let val = bx.cx().const_usize(bx.cx().layout_of(ty).size.bytes());
482 let tcx = self.cx.tcx();
484 val: OperandValue::Immediate(val),
485 layout: self.cx.layout_of(tcx.types.usize),
489 mir::Rvalue::NullaryOp(mir::NullOp::Box, content_ty) => {
490 let content_ty = self.monomorphize(&content_ty);
491 let content_layout = bx.cx().layout_of(content_ty);
492 let llsize = bx.cx().const_usize(content_layout.size.bytes());
493 let llalign = bx.cx().const_usize(content_layout.align.abi.bytes());
494 let box_layout = bx.cx().layout_of(bx.tcx().mk_box(content_ty));
495 let llty_ptr = bx.cx().backend_type(box_layout);
498 let def_id = match bx.tcx().lang_items().require(ExchangeMallocFnLangItem) {
501 bx.cx().sess().fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
504 let instance = ty::Instance::mono(bx.tcx(), def_id);
505 let r = bx.cx().get_fn(instance);
506 let call = bx.call(r, &[llsize, llalign], None);
507 let val = bx.pointercast(call, llty_ptr);
509 let operand = OperandRef {
510 val: OperandValue::Immediate(val),
515 mir::Rvalue::Use(ref operand) => {
516 let operand = self.codegen_operand(&mut bx, operand);
519 mir::Rvalue::Repeat(..) |
520 mir::Rvalue::Aggregate(..) => {
521 // According to `rvalue_creates_operand`, only ZST
522 // aggregate rvalues are allowed to be operands.
523 let ty = rvalue.ty(self.mir, self.cx.tcx());
524 (bx, OperandRef::new_zst(self.cx,
525 self.cx.layout_of(self.monomorphize(&ty))))
530 fn evaluate_array_len(
533 place: &mir::Place<'tcx>,
535 // ZST are passed as operands and require special handling
536 // because codegen_place() panics if Local is operand.
537 if let mir::Place::Base(mir::PlaceBase::Local(index)) = *place {
538 if let LocalRef::Operand(Some(op)) = self.locals[index] {
539 if let ty::Array(_, n) = op.layout.ty.sty {
540 let n = n.unwrap_usize(bx.cx().tcx());
541 return bx.cx().const_usize(n);
545 // use common size calculation for non zero-sized types
546 let cg_value = self.codegen_place(bx, place);
547 return cg_value.len(bx.cx());
550 pub fn codegen_scalar_binop(
558 let is_float = input_ty.is_fp();
559 let is_signed = input_ty.is_signed();
560 let is_unit = input_ty.is_unit();
562 mir::BinOp::Add => if is_float {
567 mir::BinOp::Sub => if is_float {
572 mir::BinOp::Mul => if is_float {
577 mir::BinOp::Div => if is_float {
579 } else if is_signed {
584 mir::BinOp::Rem => if is_float {
586 } else if is_signed {
591 mir::BinOp::BitOr => bx.or(lhs, rhs),
592 mir::BinOp::BitAnd => bx.and(lhs, rhs),
593 mir::BinOp::BitXor => bx.xor(lhs, rhs),
594 mir::BinOp::Offset => bx.inbounds_gep(lhs, &[rhs]),
595 mir::BinOp::Shl => common::build_unchecked_lshift(bx, lhs, rhs),
596 mir::BinOp::Shr => common::build_unchecked_rshift(bx, input_ty, lhs, rhs),
597 mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt |
598 mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_unit {
599 bx.cx().const_bool(match op {
600 mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false,
601 mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true,
606 base::bin_op_to_fcmp_predicate(op.to_hir_binop()),
611 base::bin_op_to_icmp_predicate(op.to_hir_binop(), is_signed),
618 pub fn codegen_fat_ptr_binop(
623 lhs_extra: Bx::Value,
625 rhs_extra: Bx::Value,
630 let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
631 let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
635 let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
636 let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
639 mir::BinOp::Le | mir::BinOp::Lt |
640 mir::BinOp::Ge | mir::BinOp::Gt => {
641 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
642 let (op, strict_op) = match op {
643 mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
644 mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
645 mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
646 mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
649 let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
650 let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
651 let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
652 let rhs = bx.and(and_lhs, and_rhs);
656 bug!("unexpected fat ptr binop");
661 pub fn codegen_scalar_checked_binop(
668 ) -> OperandValue<Bx::Value> {
669 // This case can currently arise only from functions marked
670 // with #[rustc_inherit_overflow_checks] and inlined from
671 // another crate (mostly core::num generic/#[inline] fns),
672 // while the current crate doesn't use overflow checks.
673 if !bx.cx().check_overflow() {
674 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
675 return OperandValue::Pair(val, bx.cx().const_bool(false));
678 let (val, of) = match op {
679 // These are checked using intrinsics
680 mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
682 mir::BinOp::Add => OverflowOp::Add,
683 mir::BinOp::Sub => OverflowOp::Sub,
684 mir::BinOp::Mul => OverflowOp::Mul,
687 bx.checked_binop(oop, input_ty, lhs, rhs)
689 mir::BinOp::Shl | mir::BinOp::Shr => {
690 let lhs_llty = bx.cx().val_ty(lhs);
691 let rhs_llty = bx.cx().val_ty(rhs);
692 let invert_mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, true);
693 let outer_bits = bx.and(rhs, invert_mask);
695 let of = bx.icmp(IntPredicate::IntNE, outer_bits, bx.cx().const_null(rhs_llty));
696 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
701 bug!("Operator `{:?}` is not a checkable operator", op)
705 OperandValue::Pair(val, of)
709 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
710 pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool {
712 mir::Rvalue::Ref(..) |
713 mir::Rvalue::Len(..) |
714 mir::Rvalue::Cast(..) | // (*)
715 mir::Rvalue::BinaryOp(..) |
716 mir::Rvalue::CheckedBinaryOp(..) |
717 mir::Rvalue::UnaryOp(..) |
718 mir::Rvalue::Discriminant(..) |
719 mir::Rvalue::NullaryOp(..) |
720 mir::Rvalue::Use(..) => // (*)
722 mir::Rvalue::Repeat(..) |
723 mir::Rvalue::Aggregate(..) => {
724 let ty = rvalue.ty(self.mir, self.cx.tcx());
725 let ty = self.monomorphize(&ty);
726 self.cx.layout_of(ty).is_zst()
730 // (*) this is only true if the type is suitable
734 fn cast_int_to_float<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
741 // Most integer types, even i128, fit into [-f32::MAX, f32::MAX] after rounding.
742 // It's only u128 -> f32 that can cause overflows (i.e., should yield infinity).
743 // LLVM's uitofp produces undef in those cases, so we manually check for that case.
744 let is_u128_to_f32 = !signed &&
745 bx.cx().int_width(int_ty) == 128 &&
746 bx.cx().float_width(float_ty) == 32;
748 // All inputs greater or equal to (f32::MAX + 0.5 ULP) are rounded to infinity,
749 // and for everything else LLVM's uitofp works just fine.
750 use rustc_apfloat::ieee::Single;
751 use rustc_apfloat::Float;
752 const MAX_F32_PLUS_HALF_ULP: u128 = ((1 << (Single::PRECISION + 1)) - 1)
753 << (Single::MAX_EXP - Single::PRECISION as i16);
754 let max = bx.cx().const_uint_big(int_ty, MAX_F32_PLUS_HALF_ULP);
755 let overflow = bx.icmp(IntPredicate::IntUGE, x, max);
756 let infinity_bits = bx.cx().const_u32(ieee::Single::INFINITY.to_bits() as u32);
757 let infinity = bx.bitcast(infinity_bits, float_ty);
758 let fp = bx.uitofp(x, float_ty);
759 bx.select(overflow, infinity, fp)
762 bx.sitofp(x, float_ty)
764 bx.uitofp(x, float_ty)
769 fn cast_float_to_int<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
776 let fptosui_result = if signed {
782 if !bx.cx().sess().opts.debugging_opts.saturating_float_casts {
783 return fptosui_result;
786 let int_width = bx.cx().int_width(int_ty);
787 let float_width = bx.cx().float_width(float_ty);
788 // LLVM's fpto[su]i returns undef when the input x is infinite, NaN, or does not fit into the
789 // destination integer type after rounding towards zero. This `undef` value can cause UB in
790 // safe code (see issue #10184), so we implement a saturating conversion on top of it:
791 // Semantically, the mathematical value of the input is rounded towards zero to the next
792 // mathematical integer, and then the result is clamped into the range of the destination
793 // integer type. Positive and negative infinity are mapped to the maximum and minimum value of
794 // the destination integer type. NaN is mapped to 0.
796 // Define f_min and f_max as the largest and smallest (finite) floats that are exactly equal to
797 // a value representable in int_ty.
798 // They are exactly equal to int_ty::{MIN,MAX} if float_ty has enough significand bits.
799 // Otherwise, int_ty::MAX must be rounded towards zero, as it is one less than a power of two.
800 // int_ty::MIN, however, is either zero or a negative power of two and is thus exactly
801 // representable. Note that this only works if float_ty's exponent range is sufficiently large.
802 // f16 or 256 bit integers would break this property. Right now the smallest float type is f32
803 // with exponents ranging up to 127, which is barely enough for i128::MIN = -2^127.
804 // On the other hand, f_max works even if int_ty::MAX is greater than float_ty::MAX. Because
805 // we're rounding towards zero, we just get float_ty::MAX (which is always an integer).
806 // This already happens today with u128::MAX = 2^128 - 1 > f32::MAX.
807 let int_max = |signed: bool, int_width: u64| -> u128 {
808 let shift_amount = 128 - int_width;
810 i128::MAX as u128 >> shift_amount
812 u128::MAX >> shift_amount
815 let int_min = |signed: bool, int_width: u64| -> i128 {
817 i128::MIN >> (128 - int_width)
823 let compute_clamp_bounds_single =
824 |signed: bool, int_width: u64| -> (u128, u128) {
825 let rounded_min = ieee::Single::from_i128_r(int_min(signed, int_width), Round::TowardZero);
826 assert_eq!(rounded_min.status, Status::OK);
827 let rounded_max = ieee::Single::from_u128_r(int_max(signed, int_width), Round::TowardZero);
828 assert!(rounded_max.value.is_finite());
829 (rounded_min.value.to_bits(), rounded_max.value.to_bits())
831 let compute_clamp_bounds_double =
832 |signed: bool, int_width: u64| -> (u128, u128) {
833 let rounded_min = ieee::Double::from_i128_r(int_min(signed, int_width), Round::TowardZero);
834 assert_eq!(rounded_min.status, Status::OK);
835 let rounded_max = ieee::Double::from_u128_r(int_max(signed, int_width), Round::TowardZero);
836 assert!(rounded_max.value.is_finite());
837 (rounded_min.value.to_bits(), rounded_max.value.to_bits())
840 let mut float_bits_to_llval = |bits| {
841 let bits_llval = match float_width {
842 32 => bx.cx().const_u32(bits as u32),
843 64 => bx.cx().const_u64(bits as u64),
844 n => bug!("unsupported float width {}", n),
846 bx.bitcast(bits_llval, float_ty)
848 let (f_min, f_max) = match float_width {
849 32 => compute_clamp_bounds_single(signed, int_width),
850 64 => compute_clamp_bounds_double(signed, int_width),
851 n => bug!("unsupported float width {}", n),
853 let f_min = float_bits_to_llval(f_min);
854 let f_max = float_bits_to_llval(f_max);
855 // To implement saturation, we perform the following steps:
857 // 1. Cast x to an integer with fpto[su]i. This may result in undef.
858 // 2. Compare x to f_min and f_max, and use the comparison results to select:
859 // a) int_ty::MIN if x < f_min or x is NaN
860 // b) int_ty::MAX if x > f_max
861 // c) the result of fpto[su]i otherwise
862 // 3. If x is NaN, return 0.0, otherwise return the result of step 2.
864 // This avoids resulting undef because values in range [f_min, f_max] by definition fit into the
865 // destination type. It creates an undef temporary, but *producing* undef is not UB. Our use of
866 // undef does not introduce any non-determinism either.
867 // More importantly, the above procedure correctly implements saturating conversion.
869 // If x is NaN, 0 is returned by definition.
870 // Otherwise, x is finite or infinite and thus can be compared with f_min and f_max.
871 // This yields three cases to consider:
872 // (1) if x in [f_min, f_max], the result of fpto[su]i is returned, which agrees with
873 // saturating conversion for inputs in that range.
874 // (2) if x > f_max, then x is larger than int_ty::MAX. This holds even if f_max is rounded
875 // (i.e., if f_max < int_ty::MAX) because in those cases, nextUp(f_max) is already larger
876 // than int_ty::MAX. Because x is larger than int_ty::MAX, the return value of int_ty::MAX
878 // (3) if x < f_min, then x is smaller than int_ty::MIN. As shown earlier, f_min exactly equals
879 // int_ty::MIN and therefore the return value of int_ty::MIN is correct.
882 // Step 1 was already performed above.
884 // Step 2: We use two comparisons and two selects, with %s1 being the result:
885 // %less_or_nan = fcmp ult %x, %f_min
886 // %greater = fcmp olt %x, %f_max
887 // %s0 = select %less_or_nan, int_ty::MIN, %fptosi_result
888 // %s1 = select %greater, int_ty::MAX, %s0
889 // Note that %less_or_nan uses an *unordered* comparison. This comparison is true if the
890 // operands are not comparable (i.e., if x is NaN). The unordered comparison ensures that s1
891 // becomes int_ty::MIN if x is NaN.
892 // Performance note: Unordered comparison can be lowered to a "flipped" comparison and a
893 // negation, and the negation can be merged into the select. Therefore, it not necessarily any
894 // more expensive than a ordered ("normal") comparison. Whether these optimizations will be
895 // performed is ultimately up to the backend, but at least x86 does perform them.
896 let less_or_nan = bx.fcmp(RealPredicate::RealULT, x, f_min);
897 let greater = bx.fcmp(RealPredicate::RealOGT, x, f_max);
898 let int_max = bx.cx().const_uint_big(int_ty, int_max(signed, int_width));
899 let int_min = bx.cx().const_uint_big(int_ty, int_min(signed, int_width) as u128);
900 let s0 = bx.select(less_or_nan, int_min, fptosui_result);
901 let s1 = bx.select(greater, int_max, s0);
903 // Step 3: NaN replacement.
904 // For unsigned types, the above step already yielded int_ty::MIN == 0 if x is NaN.
905 // Therefore we only need to execute this step for signed integer types.
907 // LLVM has no isNaN predicate, so we use (x == x) instead
908 let zero = bx.cx().const_uint(int_ty, 0);
909 let cmp = bx.fcmp(RealPredicate::RealOEQ, x, x);
910 bx.select(cmp, s1, zero)