]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/rvalue.rs
Skip checking for unused mutable locals that have no name
[rust.git] / src / librustc_trans / mir / rvalue.rs
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.
4 //
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.
10
11 use llvm::{self, ValueRef};
12 use rustc::ty::{self, Ty};
13 use rustc::ty::cast::{CastTy, IntTy};
14 use rustc::ty::layout::{self, LayoutOf};
15 use rustc::mir;
16 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
17 use rustc_apfloat::{ieee, Float, Status, Round};
18 use rustc_const_math::MAX_F32_PLUS_HALF_ULP;
19 use std::{u128, i128};
20
21 use base;
22 use builder::Builder;
23 use callee;
24 use common::{self, val_ty};
25 use common::{C_bool, C_u8, C_i32, C_u32, C_u64, C_undef, C_null, C_usize, C_uint, C_uint_big};
26 use consts;
27 use monomorphize;
28 use type_::Type;
29 use type_of::LayoutLlvmExt;
30 use value::Value;
31
32 use super::{FunctionCx, LocalRef};
33 use super::operand::{OperandRef, OperandValue};
34 use super::place::PlaceRef;
35
36 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
37     pub fn trans_rvalue(&mut self,
38                         bx: Builder<'a, 'tcx>,
39                         dest: PlaceRef<'tcx>,
40                         rvalue: &mir::Rvalue<'tcx>)
41                         -> Builder<'a, 'tcx>
42     {
43         debug!("trans_rvalue(dest.llval={:?}, rvalue={:?})",
44                Value(dest.llval), rvalue);
45
46         match *rvalue {
47            mir::Rvalue::Use(ref operand) => {
48                let tr_operand = self.trans_operand(&bx, operand);
49                // FIXME: consider not copying constants through stack. (fixable by translating
50                // constants into OperandValue::Ref, why don’t we do that yet if we don’t?)
51                tr_operand.val.store(&bx, dest);
52                bx
53            }
54
55             mir::Rvalue::Cast(mir::CastKind::Unsize, ref source, _) => {
56                 // The destination necessarily contains a fat pointer, so if
57                 // it's a scalar pair, it's a fat pointer or newtype thereof.
58                 if dest.layout.is_llvm_scalar_pair() {
59                     // into-coerce of a thin pointer to a fat pointer - just
60                     // use the operand path.
61                     let (bx, temp) = self.trans_rvalue_operand(bx, rvalue);
62                     temp.val.store(&bx, dest);
63                     return bx;
64                 }
65
66                 // Unsize of a nontrivial struct. I would prefer for
67                 // this to be eliminated by MIR translation, but
68                 // `CoerceUnsized` can be passed by a where-clause,
69                 // so the (generic) MIR may not be able to expand it.
70                 let operand = self.trans_operand(&bx, source);
71                 match operand.val {
72                     OperandValue::Pair(..) |
73                     OperandValue::Immediate(_) => {
74                         // unsize from an immediate structure. We don't
75                         // really need a temporary alloca here, but
76                         // avoiding it would require us to have
77                         // `coerce_unsized_into` use extractvalue to
78                         // index into the struct, and this case isn't
79                         // important enough for it.
80                         debug!("trans_rvalue: creating ugly alloca");
81                         let scratch = PlaceRef::alloca(&bx, operand.layout, "__unsize_temp");
82                         scratch.storage_live(&bx);
83                         operand.val.store(&bx, scratch);
84                         base::coerce_unsized_into(&bx, scratch, dest);
85                         scratch.storage_dead(&bx);
86                     }
87                     OperandValue::Ref(llref, align) => {
88                         let source = PlaceRef::new_sized(llref, operand.layout, align);
89                         base::coerce_unsized_into(&bx, source, dest);
90                     }
91                 }
92                 bx
93             }
94
95             mir::Rvalue::Repeat(ref elem, count) => {
96                 let tr_elem = self.trans_operand(&bx, elem);
97
98                 // Do not generate the loop for zero-sized elements or empty arrays.
99                 if dest.layout.is_zst() {
100                     return bx;
101                 }
102
103                 let start = dest.project_index(&bx, C_usize(bx.cx, 0)).llval;
104
105                 if let OperandValue::Immediate(v) = tr_elem.val {
106                     let align = C_i32(bx.cx, dest.align.abi() as i32);
107                     let size = C_usize(bx.cx, dest.layout.size.bytes());
108
109                     // Use llvm.memset.p0i8.* to initialize all zero arrays
110                     if common::is_const_integral(v) && common::const_to_uint(v) == 0 {
111                         let fill = C_u8(bx.cx, 0);
112                         base::call_memset(&bx, start, fill, size, align, false);
113                         return bx;
114                     }
115
116                     // Use llvm.memset.p0i8.* to initialize byte arrays
117                     let v = base::from_immediate(&bx, v);
118                     if common::val_ty(v) == Type::i8(bx.cx) {
119                         base::call_memset(&bx, start, v, size, align, false);
120                         return bx;
121                     }
122                 }
123
124                 let count = C_usize(bx.cx, count);
125                 let end = dest.project_index(&bx, count).llval;
126
127                 let header_bx = bx.build_sibling_block("repeat_loop_header");
128                 let body_bx = bx.build_sibling_block("repeat_loop_body");
129                 let next_bx = bx.build_sibling_block("repeat_loop_next");
130
131                 bx.br(header_bx.llbb());
132                 let current = header_bx.phi(common::val_ty(start), &[start], &[bx.llbb()]);
133
134                 let keep_going = header_bx.icmp(llvm::IntNE, current, end);
135                 header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
136
137                 tr_elem.val.store(&body_bx,
138                     PlaceRef::new_sized(current, tr_elem.layout, dest.align));
139
140                 let next = body_bx.inbounds_gep(current, &[C_usize(bx.cx, 1)]);
141                 body_bx.br(header_bx.llbb());
142                 header_bx.add_incoming_to_phi(current, next, body_bx.llbb());
143
144                 next_bx
145             }
146
147             mir::Rvalue::Aggregate(ref kind, ref operands) => {
148                 let (dest, active_field_index) = match **kind {
149                     mir::AggregateKind::Adt(adt_def, variant_index, _, active_field_index) => {
150                         dest.trans_set_discr(&bx, variant_index);
151                         if adt_def.is_enum() {
152                             (dest.project_downcast(&bx, variant_index), active_field_index)
153                         } else {
154                             (dest, active_field_index)
155                         }
156                     }
157                     _ => (dest, None)
158                 };
159                 for (i, operand) in operands.iter().enumerate() {
160                     let op = self.trans_operand(&bx, operand);
161                     // Do not generate stores and GEPis for zero-sized fields.
162                     if !op.layout.is_zst() {
163                         let field_index = active_field_index.unwrap_or(i);
164                         op.val.store(&bx, dest.project_field(&bx, field_index));
165                     }
166                 }
167                 bx
168             }
169
170             _ => {
171                 assert!(self.rvalue_creates_operand(rvalue));
172                 let (bx, temp) = self.trans_rvalue_operand(bx, rvalue);
173                 temp.val.store(&bx, dest);
174                 bx
175             }
176         }
177     }
178
179     pub fn trans_rvalue_operand(&mut self,
180                                 bx: Builder<'a, 'tcx>,
181                                 rvalue: &mir::Rvalue<'tcx>)
182                                 -> (Builder<'a, 'tcx>, OperandRef<'tcx>)
183     {
184         assert!(self.rvalue_creates_operand(rvalue), "cannot trans {:?} to operand", rvalue);
185
186         match *rvalue {
187             mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
188                 let operand = self.trans_operand(&bx, source);
189                 debug!("cast operand is {:?}", operand);
190                 let cast = bx.cx.layout_of(self.monomorphize(&mir_cast_ty));
191
192                 let val = match *kind {
193                     mir::CastKind::ReifyFnPointer => {
194                         match operand.layout.ty.sty {
195                             ty::TyFnDef(def_id, substs) => {
196                                 if bx.cx.tcx.has_attr(def_id, "rustc_args_required_const") {
197                                     bug!("reifying a fn ptr that requires \
198                                           const arguments");
199                                 }
200                                 OperandValue::Immediate(
201                                     callee::resolve_and_get_fn(bx.cx, def_id, substs))
202                             }
203                             _ => {
204                                 bug!("{} cannot be reified to a fn ptr", operand.layout.ty)
205                             }
206                         }
207                     }
208                     mir::CastKind::ClosureFnPointer => {
209                         match operand.layout.ty.sty {
210                             ty::TyClosure(def_id, substs) => {
211                                 let instance = monomorphize::resolve_closure(
212                                     bx.cx.tcx, def_id, substs, ty::ClosureKind::FnOnce);
213                                 OperandValue::Immediate(callee::get_fn(bx.cx, instance))
214                             }
215                             _ => {
216                                 bug!("{} cannot be cast to a fn ptr", operand.layout.ty)
217                             }
218                         }
219                     }
220                     mir::CastKind::UnsafeFnPointer => {
221                         // this is a no-op at the LLVM level
222                         operand.val
223                     }
224                     mir::CastKind::Unsize => {
225                         assert!(cast.is_llvm_scalar_pair());
226                         match operand.val {
227                             OperandValue::Pair(lldata, llextra) => {
228                                 // unsize from a fat pointer - this is a
229                                 // "trait-object-to-supertrait" coercion, for
230                                 // example,
231                                 //   &'a fmt::Debug+Send => &'a fmt::Debug,
232
233                                 // HACK(eddyb) have to bitcast pointers
234                                 // until LLVM removes pointee types.
235                                 let lldata = bx.pointercast(lldata,
236                                     cast.scalar_pair_element_llvm_type(bx.cx, 0));
237                                 OperandValue::Pair(lldata, llextra)
238                             }
239                             OperandValue::Immediate(lldata) => {
240                                 // "standard" unsize
241                                 let (lldata, llextra) = base::unsize_thin_ptr(&bx, lldata,
242                                     operand.layout.ty, cast.ty);
243                                 OperandValue::Pair(lldata, llextra)
244                             }
245                             OperandValue::Ref(..) => {
246                                 bug!("by-ref operand {:?} in trans_rvalue_operand",
247                                      operand);
248                             }
249                         }
250                     }
251                     mir::CastKind::Misc if operand.layout.is_llvm_scalar_pair() => {
252                         if let OperandValue::Pair(data_ptr, meta) = operand.val {
253                             if cast.is_llvm_scalar_pair() {
254                                 let data_cast = bx.pointercast(data_ptr,
255                                     cast.scalar_pair_element_llvm_type(bx.cx, 0));
256                                 OperandValue::Pair(data_cast, meta)
257                             } else { // cast to thin-ptr
258                                 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
259                                 // pointer-cast of that pointer to desired pointer type.
260                                 let llcast_ty = cast.immediate_llvm_type(bx.cx);
261                                 let llval = bx.pointercast(data_ptr, llcast_ty);
262                                 OperandValue::Immediate(llval)
263                             }
264                         } else {
265                             bug!("Unexpected non-Pair operand")
266                         }
267                     }
268                     mir::CastKind::Misc => {
269                         assert!(cast.is_llvm_immediate());
270                         let ll_t_out = cast.immediate_llvm_type(bx.cx);
271                         if operand.layout.abi == layout::Abi::Uninhabited {
272                             return (bx, OperandRef {
273                                 val: OperandValue::Immediate(C_undef(ll_t_out)),
274                                 layout: cast,
275                             });
276                         }
277                         let r_t_in = CastTy::from_ty(operand.layout.ty)
278                             .expect("bad input type for cast");
279                         let r_t_out = CastTy::from_ty(cast.ty).expect("bad output type for cast");
280                         let ll_t_in = operand.layout.immediate_llvm_type(bx.cx);
281                         match operand.layout.variants {
282                             layout::Variants::Single { index } => {
283                                 if let Some(def) = operand.layout.ty.ty_adt_def() {
284                                     let discr_val = def
285                                         .discriminant_for_variant(bx.cx.tcx, index)
286                                         .val;
287                                     let discr = C_uint_big(ll_t_out, discr_val);
288                                     return (bx, OperandRef {
289                                         val: OperandValue::Immediate(discr),
290                                         layout: cast,
291                                     });
292                                 }
293                             }
294                             layout::Variants::Tagged { .. } |
295                             layout::Variants::NicheFilling { .. } => {},
296                         }
297                         let llval = operand.immediate();
298
299                         let mut signed = false;
300                         if let layout::Abi::Scalar(ref scalar) = operand.layout.abi {
301                             if let layout::Int(_, s) = scalar.value {
302                                 signed = s;
303
304                                 if scalar.valid_range.end > scalar.valid_range.start {
305                                     // We want `table[e as usize]` to not
306                                     // have bound checks, and this is the most
307                                     // convenient place to put the `assume`.
308
309                                     base::call_assume(&bx, bx.icmp(
310                                         llvm::IntULE,
311                                         llval,
312                                         C_uint_big(ll_t_in, scalar.valid_range.end)
313                                     ));
314                                 }
315                             }
316                         }
317
318                         let newval = match (r_t_in, r_t_out) {
319                             (CastTy::Int(_), CastTy::Int(_)) => {
320                                 bx.intcast(llval, ll_t_out, signed)
321                             }
322                             (CastTy::Float, CastTy::Float) => {
323                                 let srcsz = ll_t_in.float_width();
324                                 let dstsz = ll_t_out.float_width();
325                                 if dstsz > srcsz {
326                                     bx.fpext(llval, ll_t_out)
327                                 } else if srcsz > dstsz {
328                                     bx.fptrunc(llval, ll_t_out)
329                                 } else {
330                                     llval
331                                 }
332                             }
333                             (CastTy::Ptr(_), CastTy::Ptr(_)) |
334                             (CastTy::FnPtr, CastTy::Ptr(_)) |
335                             (CastTy::RPtr(_), CastTy::Ptr(_)) =>
336                                 bx.pointercast(llval, ll_t_out),
337                             (CastTy::Ptr(_), CastTy::Int(_)) |
338                             (CastTy::FnPtr, CastTy::Int(_)) =>
339                                 bx.ptrtoint(llval, ll_t_out),
340                             (CastTy::Int(_), CastTy::Ptr(_)) => {
341                                 let usize_llval = bx.intcast(llval, bx.cx.isize_ty, signed);
342                                 bx.inttoptr(usize_llval, ll_t_out)
343                             }
344                             (CastTy::Int(_), CastTy::Float) =>
345                                 cast_int_to_float(&bx, signed, llval, ll_t_in, ll_t_out),
346                             (CastTy::Float, CastTy::Int(IntTy::I)) =>
347                                 cast_float_to_int(&bx, true, llval, ll_t_in, ll_t_out),
348                             (CastTy::Float, CastTy::Int(_)) =>
349                                 cast_float_to_int(&bx, false, llval, ll_t_in, ll_t_out),
350                             _ => bug!("unsupported cast: {:?} to {:?}", operand.layout.ty, cast.ty)
351                         };
352                         OperandValue::Immediate(newval)
353                     }
354                 };
355                 (bx, OperandRef {
356                     val,
357                     layout: cast
358                 })
359             }
360
361             mir::Rvalue::Ref(_, bk, ref place) => {
362                 let tr_place = self.trans_place(&bx, place);
363
364                 let ty = tr_place.layout.ty;
365
366                 // Note: places are indirect, so storing the `llval` into the
367                 // destination effectively creates a reference.
368                 let val = if !bx.cx.type_has_metadata(ty) {
369                     OperandValue::Immediate(tr_place.llval)
370                 } else {
371                     OperandValue::Pair(tr_place.llval, tr_place.llextra)
372                 };
373                 (bx, OperandRef {
374                     val,
375                     layout: self.cx.layout_of(self.cx.tcx.mk_ref(
376                         self.cx.tcx.types.re_erased,
377                         ty::TypeAndMut { ty, mutbl: bk.to_mutbl_lossy() }
378                     )),
379                 })
380             }
381
382             mir::Rvalue::Len(ref place) => {
383                 let size = self.evaluate_array_len(&bx, place);
384                 let operand = OperandRef {
385                     val: OperandValue::Immediate(size),
386                     layout: bx.cx.layout_of(bx.tcx().types.usize),
387                 };
388                 (bx, operand)
389             }
390
391             mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
392                 let lhs = self.trans_operand(&bx, lhs);
393                 let rhs = self.trans_operand(&bx, rhs);
394                 let llresult = match (lhs.val, rhs.val) {
395                     (OperandValue::Pair(lhs_addr, lhs_extra),
396                      OperandValue::Pair(rhs_addr, rhs_extra)) => {
397                         self.trans_fat_ptr_binop(&bx, op,
398                                                  lhs_addr, lhs_extra,
399                                                  rhs_addr, rhs_extra,
400                                                  lhs.layout.ty)
401                     }
402
403                     (OperandValue::Immediate(lhs_val),
404                      OperandValue::Immediate(rhs_val)) => {
405                         self.trans_scalar_binop(&bx, op, lhs_val, rhs_val, lhs.layout.ty)
406                     }
407
408                     _ => bug!()
409                 };
410                 let operand = OperandRef {
411                     val: OperandValue::Immediate(llresult),
412                     layout: bx.cx.layout_of(
413                         op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
414                 };
415                 (bx, operand)
416             }
417             mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
418                 let lhs = self.trans_operand(&bx, lhs);
419                 let rhs = self.trans_operand(&bx, rhs);
420                 let result = self.trans_scalar_checked_binop(&bx, op,
421                                                              lhs.immediate(), rhs.immediate(),
422                                                              lhs.layout.ty);
423                 let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
424                 let operand_ty = bx.tcx().intern_tup(&[val_ty, bx.tcx().types.bool]);
425                 let operand = OperandRef {
426                     val: result,
427                     layout: bx.cx.layout_of(operand_ty)
428                 };
429
430                 (bx, operand)
431             }
432
433             mir::Rvalue::UnaryOp(op, ref operand) => {
434                 let operand = self.trans_operand(&bx, operand);
435                 let lloperand = operand.immediate();
436                 let is_float = operand.layout.ty.is_fp();
437                 let llval = match op {
438                     mir::UnOp::Not => bx.not(lloperand),
439                     mir::UnOp::Neg => if is_float {
440                         bx.fneg(lloperand)
441                     } else {
442                         bx.neg(lloperand)
443                     }
444                 };
445                 (bx, OperandRef {
446                     val: OperandValue::Immediate(llval),
447                     layout: operand.layout,
448                 })
449             }
450
451             mir::Rvalue::Discriminant(ref place) => {
452                 let discr_ty = rvalue.ty(&*self.mir, bx.tcx());
453                 let discr =  self.trans_place(&bx, place)
454                     .trans_get_discr(&bx, discr_ty);
455                 (bx, OperandRef {
456                     val: OperandValue::Immediate(discr),
457                     layout: self.cx.layout_of(discr_ty)
458                 })
459             }
460
461             mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
462                 assert!(bx.cx.type_is_sized(ty));
463                 let val = C_usize(bx.cx, bx.cx.size_of(ty).bytes());
464                 let tcx = bx.tcx();
465                 (bx, OperandRef {
466                     val: OperandValue::Immediate(val),
467                     layout: self.cx.layout_of(tcx.types.usize),
468                 })
469             }
470
471             mir::Rvalue::NullaryOp(mir::NullOp::Box, content_ty) => {
472                 let content_ty: Ty<'tcx> = self.monomorphize(&content_ty);
473                 let (size, align) = bx.cx.size_and_align_of(content_ty);
474                 let llsize = C_usize(bx.cx, size.bytes());
475                 let llalign = C_usize(bx.cx, align.abi());
476                 let box_layout = bx.cx.layout_of(bx.tcx().mk_box(content_ty));
477                 let llty_ptr = box_layout.llvm_type(bx.cx);
478
479                 // Allocate space:
480                 let def_id = match bx.tcx().lang_items().require(ExchangeMallocFnLangItem) {
481                     Ok(id) => id,
482                     Err(s) => {
483                         bx.sess().fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
484                     }
485                 };
486                 let instance = ty::Instance::mono(bx.tcx(), def_id);
487                 let r = callee::get_fn(bx.cx, instance);
488                 let val = bx.pointercast(bx.call(r, &[llsize, llalign], None), llty_ptr);
489
490                 let operand = OperandRef {
491                     val: OperandValue::Immediate(val),
492                     layout: box_layout,
493                 };
494                 (bx, operand)
495             }
496             mir::Rvalue::Use(ref operand) => {
497                 let operand = self.trans_operand(&bx, operand);
498                 (bx, operand)
499             }
500             mir::Rvalue::Repeat(..) |
501             mir::Rvalue::Aggregate(..) => {
502                 // According to `rvalue_creates_operand`, only ZST
503                 // aggregate rvalues are allowed to be operands.
504                 let ty = rvalue.ty(self.mir, self.cx.tcx);
505                 (bx, OperandRef::new_zst(self.cx,
506                     self.cx.layout_of(self.monomorphize(&ty))))
507             }
508         }
509     }
510
511     fn evaluate_array_len(&mut self,
512                           bx: &Builder<'a, 'tcx>,
513                           place: &mir::Place<'tcx>) -> ValueRef
514     {
515         // ZST are passed as operands and require special handling
516         // because trans_place() panics if Local is operand.
517         if let mir::Place::Local(index) = *place {
518             if let LocalRef::Operand(Some(op)) = self.locals[index] {
519                 if let ty::TyArray(_, n) = op.layout.ty.sty {
520                     let n = n.val.unwrap_u64();
521                     return common::C_usize(bx.cx, n);
522                 }
523             }
524         }
525         // use common size calculation for non zero-sized types
526         let tr_value = self.trans_place(&bx, place);
527         return tr_value.len(bx.cx);
528     }
529
530     pub fn trans_scalar_binop(&mut self,
531                               bx: &Builder<'a, 'tcx>,
532                               op: mir::BinOp,
533                               lhs: ValueRef,
534                               rhs: ValueRef,
535                               input_ty: Ty<'tcx>) -> ValueRef {
536         let is_float = input_ty.is_fp();
537         let is_signed = input_ty.is_signed();
538         let is_nil = input_ty.is_nil();
539         match op {
540             mir::BinOp::Add => if is_float {
541                 bx.fadd(lhs, rhs)
542             } else {
543                 bx.add(lhs, rhs)
544             },
545             mir::BinOp::Sub => if is_float {
546                 bx.fsub(lhs, rhs)
547             } else {
548                 bx.sub(lhs, rhs)
549             },
550             mir::BinOp::Mul => if is_float {
551                 bx.fmul(lhs, rhs)
552             } else {
553                 bx.mul(lhs, rhs)
554             },
555             mir::BinOp::Div => if is_float {
556                 bx.fdiv(lhs, rhs)
557             } else if is_signed {
558                 bx.sdiv(lhs, rhs)
559             } else {
560                 bx.udiv(lhs, rhs)
561             },
562             mir::BinOp::Rem => if is_float {
563                 bx.frem(lhs, rhs)
564             } else if is_signed {
565                 bx.srem(lhs, rhs)
566             } else {
567                 bx.urem(lhs, rhs)
568             },
569             mir::BinOp::BitOr => bx.or(lhs, rhs),
570             mir::BinOp::BitAnd => bx.and(lhs, rhs),
571             mir::BinOp::BitXor => bx.xor(lhs, rhs),
572             mir::BinOp::Offset => bx.inbounds_gep(lhs, &[rhs]),
573             mir::BinOp::Shl => common::build_unchecked_lshift(bx, lhs, rhs),
574             mir::BinOp::Shr => common::build_unchecked_rshift(bx, input_ty, lhs, rhs),
575             mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt |
576             mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_nil {
577                 C_bool(bx.cx, match op {
578                     mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false,
579                     mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true,
580                     _ => unreachable!()
581                 })
582             } else if is_float {
583                 bx.fcmp(
584                     base::bin_op_to_fcmp_predicate(op.to_hir_binop()),
585                     lhs, rhs
586                 )
587             } else {
588                 bx.icmp(
589                     base::bin_op_to_icmp_predicate(op.to_hir_binop(), is_signed),
590                     lhs, rhs
591                 )
592             }
593         }
594     }
595
596     pub fn trans_fat_ptr_binop(&mut self,
597                                bx: &Builder<'a, 'tcx>,
598                                op: mir::BinOp,
599                                lhs_addr: ValueRef,
600                                lhs_extra: ValueRef,
601                                rhs_addr: ValueRef,
602                                rhs_extra: ValueRef,
603                                _input_ty: Ty<'tcx>)
604                                -> ValueRef {
605         match op {
606             mir::BinOp::Eq => {
607                 bx.and(
608                     bx.icmp(llvm::IntEQ, lhs_addr, rhs_addr),
609                     bx.icmp(llvm::IntEQ, lhs_extra, rhs_extra)
610                 )
611             }
612             mir::BinOp::Ne => {
613                 bx.or(
614                     bx.icmp(llvm::IntNE, lhs_addr, rhs_addr),
615                     bx.icmp(llvm::IntNE, lhs_extra, rhs_extra)
616                 )
617             }
618             mir::BinOp::Le | mir::BinOp::Lt |
619             mir::BinOp::Ge | mir::BinOp::Gt => {
620                 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
621                 let (op, strict_op) = match op {
622                     mir::BinOp::Lt => (llvm::IntULT, llvm::IntULT),
623                     mir::BinOp::Le => (llvm::IntULE, llvm::IntULT),
624                     mir::BinOp::Gt => (llvm::IntUGT, llvm::IntUGT),
625                     mir::BinOp::Ge => (llvm::IntUGE, llvm::IntUGT),
626                     _ => bug!(),
627                 };
628
629                 bx.or(
630                     bx.icmp(strict_op, lhs_addr, rhs_addr),
631                     bx.and(
632                         bx.icmp(llvm::IntEQ, lhs_addr, rhs_addr),
633                         bx.icmp(op, lhs_extra, rhs_extra)
634                     )
635                 )
636             }
637             _ => {
638                 bug!("unexpected fat ptr binop");
639             }
640         }
641     }
642
643     pub fn trans_scalar_checked_binop(&mut self,
644                                       bx: &Builder<'a, 'tcx>,
645                                       op: mir::BinOp,
646                                       lhs: ValueRef,
647                                       rhs: ValueRef,
648                                       input_ty: Ty<'tcx>) -> OperandValue {
649         // This case can currently arise only from functions marked
650         // with #[rustc_inherit_overflow_checks] and inlined from
651         // another crate (mostly core::num generic/#[inline] fns),
652         // while the current crate doesn't use overflow checks.
653         if !bx.cx.check_overflow {
654             let val = self.trans_scalar_binop(bx, op, lhs, rhs, input_ty);
655             return OperandValue::Pair(val, C_bool(bx.cx, false));
656         }
657
658         let (val, of) = match op {
659             // These are checked using intrinsics
660             mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
661                 let oop = match op {
662                     mir::BinOp::Add => OverflowOp::Add,
663                     mir::BinOp::Sub => OverflowOp::Sub,
664                     mir::BinOp::Mul => OverflowOp::Mul,
665                     _ => unreachable!()
666                 };
667                 let intrinsic = get_overflow_intrinsic(oop, bx, input_ty);
668                 let res = bx.call(intrinsic, &[lhs, rhs], None);
669
670                 (bx.extract_value(res, 0),
671                  bx.extract_value(res, 1))
672             }
673             mir::BinOp::Shl | mir::BinOp::Shr => {
674                 let lhs_llty = val_ty(lhs);
675                 let rhs_llty = val_ty(rhs);
676                 let invert_mask = common::shift_mask_val(&bx, lhs_llty, rhs_llty, true);
677                 let outer_bits = bx.and(rhs, invert_mask);
678
679                 let of = bx.icmp(llvm::IntNE, outer_bits, C_null(rhs_llty));
680                 let val = self.trans_scalar_binop(bx, op, lhs, rhs, input_ty);
681
682                 (val, of)
683             }
684             _ => {
685                 bug!("Operator `{:?}` is not a checkable operator", op)
686             }
687         };
688
689         OperandValue::Pair(val, of)
690     }
691
692     pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool {
693         match *rvalue {
694             mir::Rvalue::Ref(..) |
695             mir::Rvalue::Len(..) |
696             mir::Rvalue::Cast(..) | // (*)
697             mir::Rvalue::BinaryOp(..) |
698             mir::Rvalue::CheckedBinaryOp(..) |
699             mir::Rvalue::UnaryOp(..) |
700             mir::Rvalue::Discriminant(..) |
701             mir::Rvalue::NullaryOp(..) |
702             mir::Rvalue::Use(..) => // (*)
703                 true,
704             mir::Rvalue::Repeat(..) |
705             mir::Rvalue::Aggregate(..) => {
706                 let ty = rvalue.ty(self.mir, self.cx.tcx);
707                 let ty = self.monomorphize(&ty);
708                 self.cx.layout_of(ty).is_zst()
709             }
710         }
711
712         // (*) this is only true if the type is suitable
713     }
714 }
715
716 #[derive(Copy, Clone)]
717 enum OverflowOp {
718     Add, Sub, Mul
719 }
720
721 fn get_overflow_intrinsic(oop: OverflowOp, bx: &Builder, ty: Ty) -> ValueRef {
722     use syntax::ast::IntTy::*;
723     use syntax::ast::UintTy::*;
724     use rustc::ty::{TyInt, TyUint};
725
726     let tcx = bx.tcx();
727
728     let new_sty = match ty.sty {
729         TyInt(Isize) => match &tcx.sess.target.target.target_pointer_width[..] {
730             "16" => TyInt(I16),
731             "32" => TyInt(I32),
732             "64" => TyInt(I64),
733             _ => panic!("unsupported target word size")
734         },
735         TyUint(Usize) => match &tcx.sess.target.target.target_pointer_width[..] {
736             "16" => TyUint(U16),
737             "32" => TyUint(U32),
738             "64" => TyUint(U64),
739             _ => panic!("unsupported target word size")
740         },
741         ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
742         _ => panic!("tried to get overflow intrinsic for op applied to non-int type")
743     };
744
745     let name = match oop {
746         OverflowOp::Add => match new_sty {
747             TyInt(I8) => "llvm.sadd.with.overflow.i8",
748             TyInt(I16) => "llvm.sadd.with.overflow.i16",
749             TyInt(I32) => "llvm.sadd.with.overflow.i32",
750             TyInt(I64) => "llvm.sadd.with.overflow.i64",
751             TyInt(I128) => "llvm.sadd.with.overflow.i128",
752
753             TyUint(U8) => "llvm.uadd.with.overflow.i8",
754             TyUint(U16) => "llvm.uadd.with.overflow.i16",
755             TyUint(U32) => "llvm.uadd.with.overflow.i32",
756             TyUint(U64) => "llvm.uadd.with.overflow.i64",
757             TyUint(U128) => "llvm.uadd.with.overflow.i128",
758
759             _ => unreachable!(),
760         },
761         OverflowOp::Sub => match new_sty {
762             TyInt(I8) => "llvm.ssub.with.overflow.i8",
763             TyInt(I16) => "llvm.ssub.with.overflow.i16",
764             TyInt(I32) => "llvm.ssub.with.overflow.i32",
765             TyInt(I64) => "llvm.ssub.with.overflow.i64",
766             TyInt(I128) => "llvm.ssub.with.overflow.i128",
767
768             TyUint(U8) => "llvm.usub.with.overflow.i8",
769             TyUint(U16) => "llvm.usub.with.overflow.i16",
770             TyUint(U32) => "llvm.usub.with.overflow.i32",
771             TyUint(U64) => "llvm.usub.with.overflow.i64",
772             TyUint(U128) => "llvm.usub.with.overflow.i128",
773
774             _ => unreachable!(),
775         },
776         OverflowOp::Mul => match new_sty {
777             TyInt(I8) => "llvm.smul.with.overflow.i8",
778             TyInt(I16) => "llvm.smul.with.overflow.i16",
779             TyInt(I32) => "llvm.smul.with.overflow.i32",
780             TyInt(I64) => "llvm.smul.with.overflow.i64",
781             TyInt(I128) => "llvm.smul.with.overflow.i128",
782
783             TyUint(U8) => "llvm.umul.with.overflow.i8",
784             TyUint(U16) => "llvm.umul.with.overflow.i16",
785             TyUint(U32) => "llvm.umul.with.overflow.i32",
786             TyUint(U64) => "llvm.umul.with.overflow.i64",
787             TyUint(U128) => "llvm.umul.with.overflow.i128",
788
789             _ => unreachable!(),
790         },
791     };
792
793     bx.cx.get_intrinsic(&name)
794 }
795
796 fn cast_int_to_float(bx: &Builder,
797                      signed: bool,
798                      x: ValueRef,
799                      int_ty: Type,
800                      float_ty: Type) -> ValueRef {
801     // Most integer types, even i128, fit into [-f32::MAX, f32::MAX] after rounding.
802     // It's only u128 -> f32 that can cause overflows (i.e., should yield infinity).
803     // LLVM's uitofp produces undef in those cases, so we manually check for that case.
804     let is_u128_to_f32 = !signed && int_ty.int_width() == 128 && float_ty.float_width() == 32;
805     if is_u128_to_f32 {
806         // All inputs greater or equal to (f32::MAX + 0.5 ULP) are rounded to infinity,
807         // and for everything else LLVM's uitofp works just fine.
808         let max = C_uint_big(int_ty, MAX_F32_PLUS_HALF_ULP);
809         let overflow = bx.icmp(llvm::IntUGE, x, max);
810         let infinity_bits = C_u32(bx.cx, ieee::Single::INFINITY.to_bits() as u32);
811         let infinity = consts::bitcast(infinity_bits, float_ty);
812         bx.select(overflow, infinity, bx.uitofp(x, float_ty))
813     } else {
814         if signed {
815             bx.sitofp(x, float_ty)
816         } else {
817             bx.uitofp(x, float_ty)
818         }
819     }
820 }
821
822 fn cast_float_to_int(bx: &Builder,
823                      signed: bool,
824                      x: ValueRef,
825                      float_ty: Type,
826                      int_ty: Type) -> ValueRef {
827     let fptosui_result = if signed {
828         bx.fptosi(x, int_ty)
829     } else {
830         bx.fptoui(x, int_ty)
831     };
832
833     if !bx.sess().opts.debugging_opts.saturating_float_casts {
834         return fptosui_result;
835     }
836     // LLVM's fpto[su]i returns undef when the input x is infinite, NaN, or does not fit into the
837     // destination integer type after rounding towards zero. This `undef` value can cause UB in
838     // safe code (see issue #10184), so we implement a saturating conversion on top of it:
839     // Semantically, the mathematical value of the input is rounded towards zero to the next
840     // mathematical integer, and then the result is clamped into the range of the destination
841     // integer type. Positive and negative infinity are mapped to the maximum and minimum value of
842     // the destination integer type. NaN is mapped to 0.
843     //
844     // Define f_min and f_max as the largest and smallest (finite) floats that are exactly equal to
845     // a value representable in int_ty.
846     // They are exactly equal to int_ty::{MIN,MAX} if float_ty has enough significand bits.
847     // Otherwise, int_ty::MAX must be rounded towards zero, as it is one less than a power of two.
848     // int_ty::MIN, however, is either zero or a negative power of two and is thus exactly
849     // representable. Note that this only works if float_ty's exponent range is sufficiently large.
850     // f16 or 256 bit integers would break this property. Right now the smallest float type is f32
851     // with exponents ranging up to 127, which is barely enough for i128::MIN = -2^127.
852     // On the other hand, f_max works even if int_ty::MAX is greater than float_ty::MAX. Because
853     // we're rounding towards zero, we just get float_ty::MAX (which is always an integer).
854     // This already happens today with u128::MAX = 2^128 - 1 > f32::MAX.
855     fn compute_clamp_bounds<F: Float>(signed: bool, int_ty: Type) -> (u128, u128) {
856         let rounded_min = F::from_i128_r(int_min(signed, int_ty), Round::TowardZero);
857         assert_eq!(rounded_min.status, Status::OK);
858         let rounded_max = F::from_u128_r(int_max(signed, int_ty), Round::TowardZero);
859         assert!(rounded_max.value.is_finite());
860         (rounded_min.value.to_bits(), rounded_max.value.to_bits())
861     }
862     fn int_max(signed: bool, int_ty: Type) -> u128 {
863         let shift_amount = 128 - int_ty.int_width();
864         if signed {
865             i128::MAX as u128 >> shift_amount
866         } else {
867             u128::MAX >> shift_amount
868         }
869     }
870     fn int_min(signed: bool, int_ty: Type) -> i128 {
871         if signed {
872             i128::MIN >> (128 - int_ty.int_width())
873         } else {
874             0
875         }
876     }
877     let float_bits_to_llval = |bits| {
878         let bits_llval = match float_ty.float_width() {
879             32 => C_u32(bx.cx, bits as u32),
880             64 => C_u64(bx.cx, bits as u64),
881             n => bug!("unsupported float width {}", n),
882         };
883         consts::bitcast(bits_llval, float_ty)
884     };
885     let (f_min, f_max) = match float_ty.float_width() {
886         32 => compute_clamp_bounds::<ieee::Single>(signed, int_ty),
887         64 => compute_clamp_bounds::<ieee::Double>(signed, int_ty),
888         n => bug!("unsupported float width {}", n),
889     };
890     let f_min = float_bits_to_llval(f_min);
891     let f_max = float_bits_to_llval(f_max);
892     // To implement saturation, we perform the following steps:
893     //
894     // 1. Cast x to an integer with fpto[su]i. This may result in undef.
895     // 2. Compare x to f_min and f_max, and use the comparison results to select:
896     //  a) int_ty::MIN if x < f_min or x is NaN
897     //  b) int_ty::MAX if x > f_max
898     //  c) the result of fpto[su]i otherwise
899     // 3. If x is NaN, return 0.0, otherwise return the result of step 2.
900     //
901     // This avoids resulting undef because values in range [f_min, f_max] by definition fit into the
902     // destination type. It creates an undef temporary, but *producing* undef is not UB. Our use of
903     // undef does not introduce any non-determinism either.
904     // More importantly, the above procedure correctly implements saturating conversion.
905     // Proof (sketch):
906     // If x is NaN, 0 is returned by definition.
907     // Otherwise, x is finite or infinite and thus can be compared with f_min and f_max.
908     // This yields three cases to consider:
909     // (1) if x in [f_min, f_max], the result of fpto[su]i is returned, which agrees with
910     //     saturating conversion for inputs in that range.
911     // (2) if x > f_max, then x is larger than int_ty::MAX. This holds even if f_max is rounded
912     //     (i.e., if f_max < int_ty::MAX) because in those cases, nextUp(f_max) is already larger
913     //     than int_ty::MAX. Because x is larger than int_ty::MAX, the return value of int_ty::MAX
914     //     is correct.
915     // (3) if x < f_min, then x is smaller than int_ty::MIN. As shown earlier, f_min exactly equals
916     //     int_ty::MIN and therefore the return value of int_ty::MIN is correct.
917     // QED.
918
919     // Step 1 was already performed above.
920
921     // Step 2: We use two comparisons and two selects, with %s1 being the result:
922     //     %less_or_nan = fcmp ult %x, %f_min
923     //     %greater = fcmp olt %x, %f_max
924     //     %s0 = select %less_or_nan, int_ty::MIN, %fptosi_result
925     //     %s1 = select %greater, int_ty::MAX, %s0
926     // Note that %less_or_nan uses an *unordered* comparison. This comparison is true if the
927     // operands are not comparable (i.e., if x is NaN). The unordered comparison ensures that s1
928     // becomes int_ty::MIN if x is NaN.
929     // Performance note: Unordered comparison can be lowered to a "flipped" comparison and a
930     // negation, and the negation can be merged into the select. Therefore, it not necessarily any
931     // more expensive than a ordered ("normal") comparison. Whether these optimizations will be
932     // performed is ultimately up to the backend, but at least x86 does perform them.
933     let less_or_nan = bx.fcmp(llvm::RealULT, x, f_min);
934     let greater = bx.fcmp(llvm::RealOGT, x, f_max);
935     let int_max = C_uint_big(int_ty, int_max(signed, int_ty));
936     let int_min = C_uint_big(int_ty, int_min(signed, int_ty) as u128);
937     let s0 = bx.select(less_or_nan, int_min, fptosui_result);
938     let s1 = bx.select(greater, int_max, s0);
939
940     // Step 3: NaN replacement.
941     // For unsigned types, the above step already yielded int_ty::MIN == 0 if x is NaN.
942     // Therefore we only need to execute this step for signed integer types.
943     if signed {
944         // LLVM has no isNaN predicate, so we use (x == x) instead
945         bx.select(bx.fcmp(llvm::RealOEQ, x, x), s1, C_uint(int_ty, 0))
946     } else {
947         s1
948     }
949 }