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 use rustc::ty::{self, Ty};
12 use rustc::ty::cast::{CastTy, IntTy};
13 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt};
15 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
16 use rustc_apfloat::{ieee, Float, Status, Round};
17 use std::{u128, i128};
22 use common::{self, RealPredicate, IntPredicate};
23 use rustc_mir::monomorphize;
27 use super::{FunctionCx, LocalRef};
28 use super::operand::{OperandRef, OperandValue};
29 use super::place::PlaceRef;
31 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
32 pub fn codegen_rvalue(
35 dest: PlaceRef<'tcx, Bx::Value>,
36 rvalue: &mir::Rvalue<'tcx>
38 debug!("codegen_rvalue(dest.llval={:?}, rvalue={:?})",
42 mir::Rvalue::Use(ref operand) => {
43 let cg_operand = self.codegen_operand(&mut bx, operand);
44 // FIXME: consider not copying constants through stack. (fixable by codegenning
45 // constants into OperandValue::Ref, why don’t we do that yet if we don’t?)
46 cg_operand.val.store(&mut bx, dest);
50 mir::Rvalue::Cast(mir::CastKind::Unsize, ref source, _) => {
51 // The destination necessarily contains a fat pointer, so if
52 // it's a scalar pair, it's a fat pointer or newtype thereof.
53 if bx.cx().is_backend_scalar_pair(dest.layout) {
54 // into-coerce of a thin pointer to a fat pointer - just
55 // use the operand path.
56 let (mut bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
57 temp.val.store(&mut bx, dest);
61 // Unsize of a nontrivial struct. I would prefer for
62 // this to be eliminated by MIR building, but
63 // `CoerceUnsized` can be passed by a where-clause,
64 // so the (generic) MIR may not be able to expand it.
65 let operand = self.codegen_operand(&mut bx, source);
67 OperandValue::Pair(..) |
68 OperandValue::Immediate(_) => {
69 // unsize from an immediate structure. We don't
70 // really need a temporary alloca here, but
71 // avoiding it would require us to have
72 // `coerce_unsized_into` use extractvalue to
73 // index into the struct, and this case isn't
74 // important enough for it.
75 debug!("codegen_rvalue: creating ugly alloca");
76 let scratch = PlaceRef::alloca(&mut bx, operand.layout, "__unsize_temp");
77 scratch.storage_live(&mut bx);
78 operand.val.store(&mut bx, scratch);
79 base::coerce_unsized_into(&mut bx, scratch, dest);
80 scratch.storage_dead(&mut bx);
82 OperandValue::Ref(llref, None, align) => {
83 let source = PlaceRef::new_sized(llref, operand.layout, align);
84 base::coerce_unsized_into(&mut bx, source, dest);
86 OperandValue::Ref(_, Some(_), _) => {
87 bug!("unsized coercion on an unsized rvalue")
93 mir::Rvalue::Repeat(ref elem, count) => {
94 let cg_elem = self.codegen_operand(&mut bx, elem);
96 // Do not generate the loop for zero-sized elements or empty arrays.
97 if dest.layout.is_zst() {
100 let zero = bx.cx().const_usize(0);
101 let start = dest.project_index(&mut bx, zero).llval;
103 if let OperandValue::Immediate(v) = cg_elem.val {
104 let size = bx.cx().const_usize(dest.layout.size.bytes());
106 // Use llvm.memset.p0i8.* to initialize all zero arrays
107 if bx.cx().is_const_integral(v) && bx.cx().const_to_uint(v) == 0 {
108 let fill = bx.cx().const_u8(0);
109 bx.memset(start, fill, size, dest.align, MemFlags::empty());
113 // Use llvm.memset.p0i8.* to initialize byte arrays
114 let v = base::from_immediate(&mut bx, v);
115 if bx.cx().val_ty(v) == bx.cx().type_i8() {
116 bx.memset(start, v, size, dest.align, MemFlags::empty());
121 let count = bx.cx().const_usize(count);
122 let end = dest.project_index(&mut bx, count).llval;
124 let mut header_bx = bx.build_sibling_block("repeat_loop_header");
125 let mut body_bx = bx.build_sibling_block("repeat_loop_body");
126 let next_bx = bx.build_sibling_block("repeat_loop_next");
128 bx.br(header_bx.llbb());
129 let current = header_bx.phi(bx.cx().val_ty(start), &[start], &[bx.llbb()]);
131 let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
132 header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
134 cg_elem.val.store(&mut body_bx,
135 PlaceRef::new_sized(current, cg_elem.layout, dest.align));
137 let next = body_bx.inbounds_gep(current, &[bx.cx().const_usize(1)]);
138 body_bx.br(header_bx.llbb());
139 header_bx.add_incoming_to_phi(current, next, body_bx.llbb());
144 mir::Rvalue::Aggregate(ref kind, ref operands) => {
145 let (dest, active_field_index) = match **kind {
146 mir::AggregateKind::Adt(adt_def, variant_index, _, _, active_field_index) => {
147 dest.codegen_set_discr(&mut bx, variant_index);
148 if adt_def.is_enum() {
149 (dest.project_downcast(&mut bx, variant_index), active_field_index)
151 (dest, active_field_index)
156 for (i, operand) in operands.iter().enumerate() {
157 let op = self.codegen_operand(&mut bx, operand);
158 // Do not generate stores and GEPis for zero-sized fields.
159 if !op.layout.is_zst() {
160 let field_index = active_field_index.unwrap_or(i);
161 let field = dest.project_field(&mut bx, field_index);
162 op.val.store(&mut bx, field);
169 assert!(self.rvalue_creates_operand(rvalue));
170 let (mut bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
171 temp.val.store(&mut bx, dest);
177 pub fn codegen_rvalue_unsized(
180 indirect_dest: PlaceRef<'tcx, Bx::Value>,
181 rvalue: &mir::Rvalue<'tcx>,
183 debug!("codegen_rvalue_unsized(indirect_dest.llval={:?}, rvalue={:?})",
184 indirect_dest.llval, rvalue);
187 mir::Rvalue::Use(ref operand) => {
188 let cg_operand = self.codegen_operand(&mut bx, operand);
189 cg_operand.val.store_unsized(&mut bx, indirect_dest);
193 _ => bug!("unsized assignment other than Rvalue::Use"),
197 pub fn codegen_rvalue_operand(
200 rvalue: &mir::Rvalue<'tcx>
201 ) -> (Bx, OperandRef<'tcx, Bx::Value>) {
202 assert!(self.rvalue_creates_operand(rvalue), "cannot codegen {:?} to operand", rvalue);
205 mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
206 let operand = self.codegen_operand(&mut bx, source);
207 debug!("cast operand is {:?}", operand);
208 let cast = bx.cx().layout_of(self.monomorphize(&mir_cast_ty));
210 let val = match *kind {
211 mir::CastKind::ReifyFnPointer => {
212 match operand.layout.ty.sty {
213 ty::FnDef(def_id, substs) => {
214 if bx.cx().tcx().has_attr(def_id, "rustc_args_required_const") {
215 bug!("reifying a fn ptr that requires \
218 OperandValue::Immediate(
219 callee::resolve_and_get_fn(bx.cx(), def_id, substs))
222 bug!("{} cannot be reified to a fn ptr", operand.layout.ty)
226 mir::CastKind::ClosureFnPointer => {
227 match operand.layout.ty.sty {
228 ty::Closure(def_id, substs) => {
229 let instance = monomorphize::resolve_closure(
230 bx.cx().tcx(), def_id, substs, ty::ClosureKind::FnOnce);
231 OperandValue::Immediate(bx.cx().get_fn(instance))
234 bug!("{} cannot be cast to a fn ptr", operand.layout.ty)
238 mir::CastKind::UnsafeFnPointer => {
239 // this is a no-op at the LLVM level
242 mir::CastKind::Unsize => {
243 assert!(bx.cx().is_backend_scalar_pair(cast));
245 OperandValue::Pair(lldata, llextra) => {
246 // unsize from a fat pointer - this is a
247 // "trait-object-to-supertrait" coercion, for
249 // &'a fmt::Debug+Send => &'a fmt::Debug,
251 // HACK(eddyb) have to bitcast pointers
252 // until LLVM removes pointee types.
253 let lldata = bx.pointercast(lldata,
254 bx.cx().scalar_pair_element_backend_type(cast, 0, true));
255 OperandValue::Pair(lldata, llextra)
257 OperandValue::Immediate(lldata) => {
259 let (lldata, llextra) = base::unsize_thin_ptr(&mut bx, lldata,
260 operand.layout.ty, cast.ty);
261 OperandValue::Pair(lldata, llextra)
263 OperandValue::Ref(..) => {
264 bug!("by-ref operand {:?} in codegen_rvalue_operand",
269 mir::CastKind::Misc if bx.cx().is_backend_scalar_pair(operand.layout) => {
270 if let OperandValue::Pair(data_ptr, meta) = operand.val {
271 if bx.cx().is_backend_scalar_pair(cast) {
272 let data_cast = bx.pointercast(data_ptr,
273 bx.cx().scalar_pair_element_backend_type(cast, 0, true));
274 OperandValue::Pair(data_cast, meta)
275 } else { // cast to thin-ptr
276 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
277 // pointer-cast of that pointer to desired pointer type.
278 let llcast_ty = bx.cx().immediate_backend_type(cast);
279 let llval = bx.pointercast(data_ptr, llcast_ty);
280 OperandValue::Immediate(llval)
283 bug!("Unexpected non-Pair operand")
286 mir::CastKind::Misc => {
287 assert!(bx.cx().is_backend_immediate(cast));
288 let ll_t_out = bx.cx().immediate_backend_type(cast);
289 if operand.layout.abi.is_uninhabited() {
290 let val = OperandValue::Immediate(bx.cx().const_undef(ll_t_out));
291 return (bx, OperandRef {
296 let r_t_in = CastTy::from_ty(operand.layout.ty)
297 .expect("bad input type for cast");
298 let r_t_out = CastTy::from_ty(cast.ty).expect("bad output type for cast");
299 let ll_t_in = bx.cx().immediate_backend_type(operand.layout);
300 match operand.layout.variants {
301 layout::Variants::Single { index } => {
302 if let Some(def) = operand.layout.ty.ty_adt_def() {
304 .discriminant_for_variant(bx.cx().tcx(), index)
306 let discr = bx.cx().const_uint_big(ll_t_out, discr_val);
307 return (bx, OperandRef {
308 val: OperandValue::Immediate(discr),
313 layout::Variants::Tagged { .. } |
314 layout::Variants::NicheFilling { .. } => {},
316 let llval = operand.immediate();
318 let mut signed = false;
319 if let layout::Abi::Scalar(ref scalar) = operand.layout.abi {
320 if let layout::Int(_, s) = scalar.value {
321 // We use `i1` for bytes that are always `0` or `1`,
322 // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
323 // let LLVM interpret the `i1` as signed, because
324 // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
325 signed = !scalar.is_bool() && s;
327 let er = scalar.valid_range_exclusive(bx.cx());
328 if er.end != er.start &&
329 scalar.valid_range.end() > scalar.valid_range.start() {
330 // We want `table[e as usize]` to not
331 // have bound checks, and this is the most
332 // convenient place to put the `assume`.
334 bx.cx().const_uint_big(ll_t_in, *scalar.valid_range.end());
336 IntPredicate::IntULE,
345 let newval = match (r_t_in, r_t_out) {
346 (CastTy::Int(_), CastTy::Int(_)) => {
347 bx.intcast(llval, ll_t_out, signed)
349 (CastTy::Float, CastTy::Float) => {
350 let srcsz = bx.cx().float_width(ll_t_in);
351 let dstsz = bx.cx().float_width(ll_t_out);
353 bx.fpext(llval, ll_t_out)
354 } else if srcsz > dstsz {
355 bx.fptrunc(llval, ll_t_out)
360 (CastTy::Ptr(_), CastTy::Ptr(_)) |
361 (CastTy::FnPtr, CastTy::Ptr(_)) |
362 (CastTy::RPtr(_), CastTy::Ptr(_)) =>
363 bx.pointercast(llval, ll_t_out),
364 (CastTy::Ptr(_), CastTy::Int(_)) |
365 (CastTy::FnPtr, CastTy::Int(_)) =>
366 bx.ptrtoint(llval, ll_t_out),
367 (CastTy::Int(_), CastTy::Ptr(_)) => {
368 let usize_llval = bx.intcast(llval, bx.cx().type_isize(), signed);
369 bx.inttoptr(usize_llval, ll_t_out)
371 (CastTy::Int(_), CastTy::Float) =>
372 cast_int_to_float(&mut bx, signed, llval, ll_t_in, ll_t_out),
373 (CastTy::Float, CastTy::Int(IntTy::I)) =>
374 cast_float_to_int(&mut bx, true, llval, ll_t_in, ll_t_out),
375 (CastTy::Float, CastTy::Int(_)) =>
376 cast_float_to_int(&mut bx, false, llval, ll_t_in, ll_t_out),
377 _ => bug!("unsupported cast: {:?} to {:?}", operand.layout.ty, cast.ty)
379 OperandValue::Immediate(newval)
388 mir::Rvalue::Ref(_, bk, ref place) => {
389 let cg_place = self.codegen_place(&mut bx, place);
391 let ty = cg_place.layout.ty;
393 // Note: places are indirect, so storing the `llval` into the
394 // destination effectively creates a reference.
395 let val = if !bx.cx().type_has_metadata(ty) {
396 OperandValue::Immediate(cg_place.llval)
398 OperandValue::Pair(cg_place.llval, cg_place.llextra.unwrap())
402 layout: self.cx.layout_of(self.cx.tcx().mk_ref(
403 self.cx.tcx().types.re_erased,
404 ty::TypeAndMut { ty, mutbl: bk.to_mutbl_lossy() }
409 mir::Rvalue::Len(ref place) => {
410 let size = self.evaluate_array_len(&mut bx, place);
411 let operand = OperandRef {
412 val: OperandValue::Immediate(size),
413 layout: bx.cx().layout_of(bx.tcx().types.usize),
418 mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
419 let lhs = self.codegen_operand(&mut bx, lhs);
420 let rhs = self.codegen_operand(&mut bx, rhs);
421 let llresult = match (lhs.val, rhs.val) {
422 (OperandValue::Pair(lhs_addr, lhs_extra),
423 OperandValue::Pair(rhs_addr, rhs_extra)) => {
424 self.codegen_fat_ptr_binop(&mut bx, op,
430 (OperandValue::Immediate(lhs_val),
431 OperandValue::Immediate(rhs_val)) => {
432 self.codegen_scalar_binop(&mut bx, op, lhs_val, rhs_val, lhs.layout.ty)
437 let operand = OperandRef {
438 val: OperandValue::Immediate(llresult),
439 layout: bx.cx().layout_of(
440 op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
444 mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
445 let lhs = self.codegen_operand(&mut bx, lhs);
446 let rhs = self.codegen_operand(&mut bx, rhs);
447 let result = self.codegen_scalar_checked_binop(&mut bx, op,
448 lhs.immediate(), rhs.immediate(),
450 let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
451 let operand_ty = bx.tcx().intern_tup(&[val_ty, bx.tcx().types.bool]);
452 let operand = OperandRef {
454 layout: bx.cx().layout_of(operand_ty)
460 mir::Rvalue::UnaryOp(op, ref operand) => {
461 let operand = self.codegen_operand(&mut bx, operand);
462 let lloperand = operand.immediate();
463 let is_float = operand.layout.ty.is_fp();
464 let llval = match op {
465 mir::UnOp::Not => bx.not(lloperand),
466 mir::UnOp::Neg => if is_float {
473 val: OperandValue::Immediate(llval),
474 layout: operand.layout,
478 mir::Rvalue::Discriminant(ref place) => {
479 let discr_ty = rvalue.ty(&*self.mir, bx.tcx());
480 let discr = self.codegen_place(&mut bx, place)
481 .codegen_get_discr(&mut bx, discr_ty);
483 val: OperandValue::Immediate(discr),
484 layout: self.cx.layout_of(discr_ty)
488 mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
489 assert!(bx.cx().type_is_sized(ty));
490 let val = bx.cx().const_usize(bx.cx().layout_of(ty).size.bytes());
491 let tcx = self.cx.tcx();
493 val: OperandValue::Immediate(val),
494 layout: self.cx.layout_of(tcx.types.usize),
498 mir::Rvalue::NullaryOp(mir::NullOp::Box, content_ty) => {
499 let content_ty = self.monomorphize(&content_ty);
500 let content_layout = bx.cx().layout_of(content_ty);
501 let llsize = bx.cx().const_usize(content_layout.size.bytes());
502 let llalign = bx.cx().const_usize(content_layout.align.abi.bytes());
503 let box_layout = bx.cx().layout_of(bx.tcx().mk_box(content_ty));
504 let llty_ptr = bx.cx().backend_type(box_layout);
507 let def_id = match bx.tcx().lang_items().require(ExchangeMallocFnLangItem) {
510 bx.cx().sess().fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
513 let instance = ty::Instance::mono(bx.tcx(), def_id);
514 let r = bx.cx().get_fn(instance);
515 let call = bx.call(r, &[llsize, llalign], None);
516 let val = bx.pointercast(call, llty_ptr);
518 let operand = OperandRef {
519 val: OperandValue::Immediate(val),
524 mir::Rvalue::Use(ref operand) => {
525 let operand = self.codegen_operand(&mut bx, operand);
528 mir::Rvalue::Repeat(..) |
529 mir::Rvalue::Aggregate(..) => {
530 // According to `rvalue_creates_operand`, only ZST
531 // aggregate rvalues are allowed to be operands.
532 let ty = rvalue.ty(self.mir, self.cx.tcx());
533 (bx, OperandRef::new_zst(self.cx,
534 self.cx.layout_of(self.monomorphize(&ty))))
539 fn evaluate_array_len(
542 place: &mir::Place<'tcx>,
544 // ZST are passed as operands and require special handling
545 // because codegen_place() panics if Local is operand.
546 if let mir::Place::Local(index) = *place {
547 if let LocalRef::Operand(Some(op)) = self.locals[index] {
548 if let ty::Array(_, n) = op.layout.ty.sty {
549 let n = n.unwrap_usize(bx.cx().tcx());
550 return bx.cx().const_usize(n);
554 // use common size calculation for non zero-sized types
555 let cg_value = self.codegen_place(bx, place);
556 return cg_value.len(bx.cx());
559 pub fn codegen_scalar_binop(
567 let is_float = input_ty.is_fp();
568 let is_signed = input_ty.is_signed();
569 let is_unit = input_ty.is_unit();
571 mir::BinOp::Add => if is_float {
576 mir::BinOp::Sub => if is_float {
581 mir::BinOp::Mul => if is_float {
586 mir::BinOp::Div => if is_float {
588 } else if is_signed {
593 mir::BinOp::Rem => if is_float {
595 } else if is_signed {
600 mir::BinOp::BitOr => bx.or(lhs, rhs),
601 mir::BinOp::BitAnd => bx.and(lhs, rhs),
602 mir::BinOp::BitXor => bx.xor(lhs, rhs),
603 mir::BinOp::Offset => bx.inbounds_gep(lhs, &[rhs]),
604 mir::BinOp::Shl => common::build_unchecked_lshift(bx, lhs, rhs),
605 mir::BinOp::Shr => common::build_unchecked_rshift(bx, input_ty, lhs, rhs),
606 mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt |
607 mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_unit {
608 bx.cx().const_bool(match op {
609 mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false,
610 mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true,
615 base::bin_op_to_fcmp_predicate(op.to_hir_binop()),
620 base::bin_op_to_icmp_predicate(op.to_hir_binop(), is_signed),
627 pub fn codegen_fat_ptr_binop(
632 lhs_extra: Bx::Value,
634 rhs_extra: Bx::Value,
639 let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
640 let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
644 let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
645 let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
648 mir::BinOp::Le | mir::BinOp::Lt |
649 mir::BinOp::Ge | mir::BinOp::Gt => {
650 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
651 let (op, strict_op) = match op {
652 mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
653 mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
654 mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
655 mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
658 let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
659 let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
660 let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
661 let rhs = bx.and(and_lhs, and_rhs);
665 bug!("unexpected fat ptr binop");
670 pub fn codegen_scalar_checked_binop(
677 ) -> OperandValue<Bx::Value> {
678 // This case can currently arise only from functions marked
679 // with #[rustc_inherit_overflow_checks] and inlined from
680 // another crate (mostly core::num generic/#[inline] fns),
681 // while the current crate doesn't use overflow checks.
682 if !bx.cx().check_overflow() {
683 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
684 return OperandValue::Pair(val, bx.cx().const_bool(false));
687 let (val, of) = match op {
688 // These are checked using intrinsics
689 mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
691 mir::BinOp::Add => OverflowOp::Add,
692 mir::BinOp::Sub => OverflowOp::Sub,
693 mir::BinOp::Mul => OverflowOp::Mul,
696 bx.call_overflow_intrinsic(oop, input_ty, lhs, rhs)
698 mir::BinOp::Shl | mir::BinOp::Shr => {
699 let lhs_llty = bx.cx().val_ty(lhs);
700 let rhs_llty = bx.cx().val_ty(rhs);
701 let invert_mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, true);
702 let outer_bits = bx.and(rhs, invert_mask);
704 let of = bx.icmp(IntPredicate::IntNE, outer_bits, bx.cx().const_null(rhs_llty));
705 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
710 bug!("Operator `{:?}` is not a checkable operator", op)
714 OperandValue::Pair(val, of)
718 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
719 pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool {
721 mir::Rvalue::Ref(..) |
722 mir::Rvalue::Len(..) |
723 mir::Rvalue::Cast(..) | // (*)
724 mir::Rvalue::BinaryOp(..) |
725 mir::Rvalue::CheckedBinaryOp(..) |
726 mir::Rvalue::UnaryOp(..) |
727 mir::Rvalue::Discriminant(..) |
728 mir::Rvalue::NullaryOp(..) |
729 mir::Rvalue::Use(..) => // (*)
731 mir::Rvalue::Repeat(..) |
732 mir::Rvalue::Aggregate(..) => {
733 let ty = rvalue.ty(self.mir, self.cx.tcx());
734 let ty = self.monomorphize(&ty);
735 self.cx.layout_of(ty).is_zst()
739 // (*) this is only true if the type is suitable
743 fn cast_int_to_float<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
750 // Most integer types, even i128, fit into [-f32::MAX, f32::MAX] after rounding.
751 // It's only u128 -> f32 that can cause overflows (i.e., should yield infinity).
752 // LLVM's uitofp produces undef in those cases, so we manually check for that case.
753 let is_u128_to_f32 = !signed &&
754 bx.cx().int_width(int_ty) == 128 &&
755 bx.cx().float_width(float_ty) == 32;
757 // All inputs greater or equal to (f32::MAX + 0.5 ULP) are rounded to infinity,
758 // and for everything else LLVM's uitofp works just fine.
759 use rustc_apfloat::ieee::Single;
760 use rustc_apfloat::Float;
761 const MAX_F32_PLUS_HALF_ULP: u128 = ((1 << (Single::PRECISION + 1)) - 1)
762 << (Single::MAX_EXP - Single::PRECISION as i16);
763 let max = bx.cx().const_uint_big(int_ty, MAX_F32_PLUS_HALF_ULP);
764 let overflow = bx.icmp(IntPredicate::IntUGE, x, max);
765 let infinity_bits = bx.cx().const_u32(ieee::Single::INFINITY.to_bits() as u32);
766 let infinity = bx.bitcast(infinity_bits, float_ty);
767 let fp = bx.uitofp(x, float_ty);
768 bx.select(overflow, infinity, fp)
771 bx.sitofp(x, float_ty)
773 bx.uitofp(x, float_ty)
778 fn cast_float_to_int<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
785 let fptosui_result = if signed {
791 if !bx.cx().sess().opts.debugging_opts.saturating_float_casts {
792 return fptosui_result;
795 let int_width = bx.cx().int_width(int_ty);
796 let float_width = bx.cx().float_width(float_ty);
797 // LLVM's fpto[su]i returns undef when the input x is infinite, NaN, or does not fit into the
798 // destination integer type after rounding towards zero. This `undef` value can cause UB in
799 // safe code (see issue #10184), so we implement a saturating conversion on top of it:
800 // Semantically, the mathematical value of the input is rounded towards zero to the next
801 // mathematical integer, and then the result is clamped into the range of the destination
802 // integer type. Positive and negative infinity are mapped to the maximum and minimum value of
803 // the destination integer type. NaN is mapped to 0.
805 // Define f_min and f_max as the largest and smallest (finite) floats that are exactly equal to
806 // a value representable in int_ty.
807 // They are exactly equal to int_ty::{MIN,MAX} if float_ty has enough significand bits.
808 // Otherwise, int_ty::MAX must be rounded towards zero, as it is one less than a power of two.
809 // int_ty::MIN, however, is either zero or a negative power of two and is thus exactly
810 // representable. Note that this only works if float_ty's exponent range is sufficiently large.
811 // f16 or 256 bit integers would break this property. Right now the smallest float type is f32
812 // with exponents ranging up to 127, which is barely enough for i128::MIN = -2^127.
813 // On the other hand, f_max works even if int_ty::MAX is greater than float_ty::MAX. Because
814 // we're rounding towards zero, we just get float_ty::MAX (which is always an integer).
815 // This already happens today with u128::MAX = 2^128 - 1 > f32::MAX.
816 let int_max = |signed: bool, int_width: u64| -> u128 {
817 let shift_amount = 128 - int_width;
819 i128::MAX as u128 >> shift_amount
821 u128::MAX >> shift_amount
824 let int_min = |signed: bool, int_width: u64| -> i128 {
826 i128::MIN >> (128 - int_width)
832 let compute_clamp_bounds_single =
833 |signed: bool, int_width: u64| -> (u128, u128) {
834 let rounded_min = ieee::Single::from_i128_r(int_min(signed, int_width), Round::TowardZero);
835 assert_eq!(rounded_min.status, Status::OK);
836 let rounded_max = ieee::Single::from_u128_r(int_max(signed, int_width), Round::TowardZero);
837 assert!(rounded_max.value.is_finite());
838 (rounded_min.value.to_bits(), rounded_max.value.to_bits())
840 let compute_clamp_bounds_double =
841 |signed: bool, int_width: u64| -> (u128, u128) {
842 let rounded_min = ieee::Double::from_i128_r(int_min(signed, int_width), Round::TowardZero);
843 assert_eq!(rounded_min.status, Status::OK);
844 let rounded_max = ieee::Double::from_u128_r(int_max(signed, int_width), Round::TowardZero);
845 assert!(rounded_max.value.is_finite());
846 (rounded_min.value.to_bits(), rounded_max.value.to_bits())
849 let mut float_bits_to_llval = |bits| {
850 let bits_llval = match float_width {
851 32 => bx.cx().const_u32(bits as u32),
852 64 => bx.cx().const_u64(bits as u64),
853 n => bug!("unsupported float width {}", n),
855 bx.bitcast(bits_llval, float_ty)
857 let (f_min, f_max) = match float_width {
858 32 => compute_clamp_bounds_single(signed, int_width),
859 64 => compute_clamp_bounds_double(signed, int_width),
860 n => bug!("unsupported float width {}", n),
862 let f_min = float_bits_to_llval(f_min);
863 let f_max = float_bits_to_llval(f_max);
864 // To implement saturation, we perform the following steps:
866 // 1. Cast x to an integer with fpto[su]i. This may result in undef.
867 // 2. Compare x to f_min and f_max, and use the comparison results to select:
868 // a) int_ty::MIN if x < f_min or x is NaN
869 // b) int_ty::MAX if x > f_max
870 // c) the result of fpto[su]i otherwise
871 // 3. If x is NaN, return 0.0, otherwise return the result of step 2.
873 // This avoids resulting undef because values in range [f_min, f_max] by definition fit into the
874 // destination type. It creates an undef temporary, but *producing* undef is not UB. Our use of
875 // undef does not introduce any non-determinism either.
876 // More importantly, the above procedure correctly implements saturating conversion.
878 // If x is NaN, 0 is returned by definition.
879 // Otherwise, x is finite or infinite and thus can be compared with f_min and f_max.
880 // This yields three cases to consider:
881 // (1) if x in [f_min, f_max], the result of fpto[su]i is returned, which agrees with
882 // saturating conversion for inputs in that range.
883 // (2) if x > f_max, then x is larger than int_ty::MAX. This holds even if f_max is rounded
884 // (i.e., if f_max < int_ty::MAX) because in those cases, nextUp(f_max) is already larger
885 // than int_ty::MAX. Because x is larger than int_ty::MAX, the return value of int_ty::MAX
887 // (3) if x < f_min, then x is smaller than int_ty::MIN. As shown earlier, f_min exactly equals
888 // int_ty::MIN and therefore the return value of int_ty::MIN is correct.
891 // Step 1 was already performed above.
893 // Step 2: We use two comparisons and two selects, with %s1 being the result:
894 // %less_or_nan = fcmp ult %x, %f_min
895 // %greater = fcmp olt %x, %f_max
896 // %s0 = select %less_or_nan, int_ty::MIN, %fptosi_result
897 // %s1 = select %greater, int_ty::MAX, %s0
898 // Note that %less_or_nan uses an *unordered* comparison. This comparison is true if the
899 // operands are not comparable (i.e., if x is NaN). The unordered comparison ensures that s1
900 // becomes int_ty::MIN if x is NaN.
901 // Performance note: Unordered comparison can be lowered to a "flipped" comparison and a
902 // negation, and the negation can be merged into the select. Therefore, it not necessarily any
903 // more expensive than a ordered ("normal") comparison. Whether these optimizations will be
904 // performed is ultimately up to the backend, but at least x86 does perform them.
905 let less_or_nan = bx.fcmp(RealPredicate::RealULT, x, f_min);
906 let greater = bx.fcmp(RealPredicate::RealOGT, x, f_max);
907 let int_max = bx.cx().const_uint_big(int_ty, int_max(signed, int_width));
908 let int_min = bx.cx().const_uint_big(int_ty, int_min(signed, int_width) as u128);
909 let s0 = bx.select(less_or_nan, int_min, fptosui_result);
910 let s1 = bx.select(greater, int_max, s0);
912 // Step 3: NaN replacement.
913 // For unsigned types, the above step already yielded int_ty::MIN == 0 if x is NaN.
914 // Therefore we only need to execute this step for signed integer types.
916 // LLVM has no isNaN predicate, so we use (x == x) instead
917 let zero = bx.cx().const_uint(int_ty, 0);
918 let cmp = bx.fcmp(RealPredicate::RealOEQ, x, x);
919 bx.select(cmp, s1, zero)