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