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