]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/rvalue.rs
Prefixed type methods & removed trait impl for write::CodegenContext
[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};
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::Builder;
21 use callee;
22 use common::{self, IntPredicate, RealPredicate};
23 use consts;
24 use monomorphize;
25 use type_::Type;
26 use type_of::LayoutLlvmExt;
27 use value::Value;
28
29 use interfaces::{BuilderMethods, CommonMethods, CommonWriteMethods, TypeMethods};
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, bx.cx().const_usize(0)).llval;
106
107                 if let OperandValue::Immediate(v) = cg_elem.val {
108                     let align = bx.cx().const_i32(dest.align.abi() as i32);
109                     let size = bx.cx().const_usize(dest.layout.size.bytes());
110
111                     // Use llvm.memset.p0i8.* to initialize all zero arrays
112                     if bx.cx().is_const_integral(v) && bx.cx().const_to_uint(v) == 0 {
113                         let fill = bx.cx().const_u8(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 bx.cx().val_ty(v) == bx.cx().type_i8() {
121                         base::call_memset(&bx, start, v, size, align, false);
122                         return bx;
123                     }
124                 }
125
126                 let count = bx.cx().const_usize(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(bx.cx().val_ty(start), &[start], &[bx.llbb()]);
135
136                 let keep_going = header_bx.icmp(IntPredicate::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, &[bx.cx().const_usize(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(&mut self,
182                         bx: Builder<'a, 'll, 'tcx>,
183                         indirect_dest: PlaceRef<'tcx, &'ll Value>,
184                         rvalue: &mir::Rvalue<'tcx>)
185                         -> Builder<'a, 'll, 'tcx>
186     {
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(
202         &mut self,
203         bx: Builder<'a, 'll, 'tcx>,
204         rvalue: &mir::Rvalue<'tcx>
205     ) -> (Builder<'a, 'll, 'tcx>, OperandRef<'tcx, &'ll Value>) {
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                             let val = OperandValue::Immediate(bx.cx().const_undef(ll_t_out));
295                             return (bx, OperandRef {
296                                 val,
297                                 layout: cast,
298                             });
299                         }
300                         let r_t_in = CastTy::from_ty(operand.layout.ty)
301                             .expect("bad input type for cast");
302                         let r_t_out = CastTy::from_ty(cast.ty).expect("bad output type for cast");
303                         let ll_t_in = operand.layout.immediate_llvm_type(bx.cx());
304                         match operand.layout.variants {
305                             layout::Variants::Single { index } => {
306                                 if let Some(def) = operand.layout.ty.ty_adt_def() {
307                                     let discr_val = def
308                                         .discriminant_for_variant(bx.cx().tcx, index)
309                                         .val;
310                                     let discr = bx.cx().const_uint_big(ll_t_out, discr_val);
311                                     return (bx, OperandRef {
312                                         val: OperandValue::Immediate(discr),
313                                         layout: cast,
314                                     });
315                                 }
316                             }
317                             layout::Variants::Tagged { .. } |
318                             layout::Variants::NicheFilling { .. } => {},
319                         }
320                         let llval = operand.immediate();
321
322                         let mut signed = false;
323                         if let layout::Abi::Scalar(ref scalar) = operand.layout.abi {
324                             if let layout::Int(_, s) = scalar.value {
325                                 // We use `i1` for bytes that are always `0` or `1`,
326                                 // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
327                                 // let LLVM interpret the `i1` as signed, because
328                                 // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
329                                 signed = !scalar.is_bool() && s;
330
331                                 let er = scalar.valid_range_exclusive(bx.cx());
332                                 if er.end != er.start &&
333                                    scalar.valid_range.end() > scalar.valid_range.start() {
334                                     // We want `table[e as usize]` to not
335                                     // have bound checks, and this is the most
336                                     // convenient place to put the `assume`.
337
338                                     base::call_assume(&bx, bx.icmp(
339                                         IntPredicate::IntULE,
340                                         llval,
341                                         bx.cx().const_uint_big(ll_t_in, *scalar.valid_range.end())
342                                     ));
343                                 }
344                             }
345                         }
346
347                         let newval = match (r_t_in, r_t_out) {
348                             (CastTy::Int(_), CastTy::Int(_)) => {
349                                 bx.intcast(llval, ll_t_out, signed)
350                             }
351                             (CastTy::Float, CastTy::Float) => {
352                                 let srcsz = bx.cx().float_width(ll_t_in);
353                                 let dstsz = bx.cx().float_width(ll_t_out);
354                                 if dstsz > srcsz {
355                                     bx.fpext(llval, ll_t_out)
356                                 } else if srcsz > dstsz {
357                                     bx.fptrunc(llval, ll_t_out)
358                                 } else {
359                                     llval
360                                 }
361                             }
362                             (CastTy::Ptr(_), CastTy::Ptr(_)) |
363                             (CastTy::FnPtr, CastTy::Ptr(_)) |
364                             (CastTy::RPtr(_), CastTy::Ptr(_)) =>
365                                 bx.pointercast(llval, ll_t_out),
366                             (CastTy::Ptr(_), CastTy::Int(_)) |
367                             (CastTy::FnPtr, CastTy::Int(_)) =>
368                                 bx.ptrtoint(llval, ll_t_out),
369                             (CastTy::Int(_), CastTy::Ptr(_)) => {
370                                 let usize_llval = bx.intcast(llval, bx.cx().isize_ty, signed);
371                                 bx.inttoptr(usize_llval, ll_t_out)
372                             }
373                             (CastTy::Int(_), CastTy::Float) =>
374                                 cast_int_to_float(&bx, signed, llval, ll_t_in, ll_t_out),
375                             (CastTy::Float, CastTy::Int(IntTy::I)) =>
376                                 cast_float_to_int(&bx, true, llval, ll_t_in, ll_t_out),
377                             (CastTy::Float, CastTy::Int(_)) =>
378                                 cast_float_to_int(&bx, false, llval, ll_t_in, ll_t_out),
379                             _ => bug!("unsupported cast: {:?} to {:?}", operand.layout.ty, cast.ty)
380                         };
381                         OperandValue::Immediate(newval)
382                     }
383                 };
384                 (bx, OperandRef {
385                     val,
386                     layout: cast
387                 })
388             }
389
390             mir::Rvalue::Ref(_, bk, ref place) => {
391                 let cg_place = self.codegen_place(&bx, place);
392
393                 let ty = cg_place.layout.ty;
394
395                 // Note: places are indirect, so storing the `llval` into the
396                 // destination effectively creates a reference.
397                 let val = if !bx.cx().type_has_metadata(ty) {
398                     OperandValue::Immediate(cg_place.llval)
399                 } else {
400                     OperandValue::Pair(cg_place.llval, cg_place.llextra.unwrap())
401                 };
402                 (bx, OperandRef {
403                     val,
404                     layout: self.cx.layout_of(self.cx.tcx.mk_ref(
405                         self.cx.tcx.types.re_erased,
406                         ty::TypeAndMut { ty, mutbl: bk.to_mutbl_lossy() }
407                     )),
408                 })
409             }
410
411             mir::Rvalue::Len(ref place) => {
412                 let size = self.evaluate_array_len(&bx, place);
413                 let operand = OperandRef {
414                     val: OperandValue::Immediate(size),
415                     layout: bx.cx().layout_of(bx.tcx().types.usize),
416                 };
417                 (bx, operand)
418             }
419
420             mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
421                 let lhs = self.codegen_operand(&bx, lhs);
422                 let rhs = self.codegen_operand(&bx, rhs);
423                 let llresult = match (lhs.val, rhs.val) {
424                     (OperandValue::Pair(lhs_addr, lhs_extra),
425                      OperandValue::Pair(rhs_addr, rhs_extra)) => {
426                         self.codegen_fat_ptr_binop(&bx, op,
427                                                  lhs_addr, lhs_extra,
428                                                  rhs_addr, rhs_extra,
429                                                  lhs.layout.ty)
430                     }
431
432                     (OperandValue::Immediate(lhs_val),
433                      OperandValue::Immediate(rhs_val)) => {
434                         self.codegen_scalar_binop(&bx, op, lhs_val, rhs_val, lhs.layout.ty)
435                     }
436
437                     _ => bug!()
438                 };
439                 let operand = OperandRef {
440                     val: OperandValue::Immediate(llresult),
441                     layout: bx.cx().layout_of(
442                         op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
443                 };
444                 (bx, operand)
445             }
446             mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
447                 let lhs = self.codegen_operand(&bx, lhs);
448                 let rhs = self.codegen_operand(&bx, rhs);
449                 let result = self.codegen_scalar_checked_binop(&bx, op,
450                                                              lhs.immediate(), rhs.immediate(),
451                                                              lhs.layout.ty);
452                 let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
453                 let operand_ty = bx.tcx().intern_tup(&[val_ty, bx.tcx().types.bool]);
454                 let operand = OperandRef {
455                     val: result,
456                     layout: bx.cx().layout_of(operand_ty)
457                 };
458
459                 (bx, operand)
460             }
461
462             mir::Rvalue::UnaryOp(op, ref operand) => {
463                 let operand = self.codegen_operand(&bx, operand);
464                 let lloperand = operand.immediate();
465                 let is_float = operand.layout.ty.is_fp();
466                 let llval = match op {
467                     mir::UnOp::Not => bx.not(lloperand),
468                     mir::UnOp::Neg => if is_float {
469                         bx.fneg(lloperand)
470                     } else {
471                         bx.neg(lloperand)
472                     }
473                 };
474                 (bx, OperandRef {
475                     val: OperandValue::Immediate(llval),
476                     layout: operand.layout,
477                 })
478             }
479
480             mir::Rvalue::Discriminant(ref place) => {
481                 let discr_ty = rvalue.ty(&*self.mir, bx.tcx());
482                 let discr =  self.codegen_place(&bx, place)
483                     .codegen_get_discr(&bx, discr_ty);
484                 (bx, OperandRef {
485                     val: OperandValue::Immediate(discr),
486                     layout: self.cx.layout_of(discr_ty)
487                 })
488             }
489
490             mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
491                 assert!(bx.cx().type_is_sized(ty));
492                 let val = bx.cx().const_usize(bx.cx().size_of(ty).bytes());
493                 let tcx = bx.tcx();
494                 (bx, OperandRef {
495                     val: OperandValue::Immediate(val),
496                     layout: self.cx.layout_of(tcx.types.usize),
497                 })
498             }
499
500             mir::Rvalue::NullaryOp(mir::NullOp::Box, content_ty) => {
501                 let content_ty: Ty<'tcx> = self.monomorphize(&content_ty);
502                 let (size, align) = bx.cx().size_and_align_of(content_ty);
503                 let llsize = bx.cx().const_usize(size.bytes());
504                 let llalign = bx.cx().const_usize(align.abi());
505                 let box_layout = bx.cx().layout_of(bx.tcx().mk_box(content_ty));
506                 let llty_ptr = box_layout.llvm_type(bx.cx());
507
508                 // Allocate space:
509                 let def_id = match bx.tcx().lang_items().require(ExchangeMallocFnLangItem) {
510                     Ok(id) => id,
511                     Err(s) => {
512                         bx.sess().fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
513                     }
514                 };
515                 let instance = ty::Instance::mono(bx.tcx(), def_id);
516                 let r = callee::get_fn(bx.cx(), instance);
517                 let val = bx.pointercast(bx.call(r, &[llsize, llalign], None), llty_ptr);
518
519                 let operand = OperandRef {
520                     val: OperandValue::Immediate(val),
521                     layout: box_layout,
522                 };
523                 (bx, operand)
524             }
525             mir::Rvalue::Use(ref operand) => {
526                 let operand = self.codegen_operand(&bx, operand);
527                 (bx, operand)
528             }
529             mir::Rvalue::Repeat(..) |
530             mir::Rvalue::Aggregate(..) => {
531                 // According to `rvalue_creates_operand`, only ZST
532                 // aggregate rvalues are allowed to be operands.
533                 let ty = rvalue.ty(self.mir, self.cx.tcx);
534                 (bx, OperandRef::new_zst(self.cx,
535                     self.cx.layout_of(self.monomorphize(&ty))))
536             }
537         }
538     }
539
540     fn evaluate_array_len(
541         &mut self,
542         bx: &Builder<'a, 'll, 'tcx>,
543         place: &mir::Place<'tcx>,
544     ) -> &'ll Value {
545         // ZST are passed as operands and require special handling
546         // because codegen_place() panics if Local is operand.
547         if let mir::Place::Local(index) = *place {
548             if let LocalRef::Operand(Some(op)) = self.locals[index] {
549                 if let ty::Array(_, n) = op.layout.ty.sty {
550                     let n = n.unwrap_usize(bx.cx().tcx);
551                     return bx.cx().const_usize(n);
552                 }
553             }
554         }
555         // use common size calculation for non zero-sized types
556         let cg_value = self.codegen_place(&bx, place);
557         return cg_value.len(bx.cx());
558     }
559
560     pub fn codegen_scalar_binop(
561         &mut self,
562         bx: &Builder<'a, 'll, 'tcx>,
563         op: mir::BinOp,
564         lhs: &'ll Value,
565         rhs: &'ll Value,
566         input_ty: Ty<'tcx>,
567     ) -> &'ll Value {
568         let is_float = input_ty.is_fp();
569         let is_signed = input_ty.is_signed();
570         let is_unit = input_ty.is_unit();
571         match op {
572             mir::BinOp::Add => if is_float {
573                 bx.fadd(lhs, rhs)
574             } else {
575                 bx.add(lhs, rhs)
576             },
577             mir::BinOp::Sub => if is_float {
578                 bx.fsub(lhs, rhs)
579             } else {
580                 bx.sub(lhs, rhs)
581             },
582             mir::BinOp::Mul => if is_float {
583                 bx.fmul(lhs, rhs)
584             } else {
585                 bx.mul(lhs, rhs)
586             },
587             mir::BinOp::Div => if is_float {
588                 bx.fdiv(lhs, rhs)
589             } else if is_signed {
590                 bx.sdiv(lhs, rhs)
591             } else {
592                 bx.udiv(lhs, rhs)
593             },
594             mir::BinOp::Rem => if is_float {
595                 bx.frem(lhs, rhs)
596             } else if is_signed {
597                 bx.srem(lhs, rhs)
598             } else {
599                 bx.urem(lhs, rhs)
600             },
601             mir::BinOp::BitOr => bx.or(lhs, rhs),
602             mir::BinOp::BitAnd => bx.and(lhs, rhs),
603             mir::BinOp::BitXor => bx.xor(lhs, rhs),
604             mir::BinOp::Offset => bx.inbounds_gep(lhs, &[rhs]),
605             mir::BinOp::Shl => common::build_unchecked_lshift(bx, lhs, rhs),
606             mir::BinOp::Shr => common::build_unchecked_rshift(bx, input_ty, lhs, rhs),
607             mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt |
608             mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_unit {
609                 bx.cx().const_bool(match op {
610                     mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false,
611                     mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true,
612                     _ => unreachable!()
613                 })
614             } else if is_float {
615                 bx.fcmp(
616                     base::bin_op_to_fcmp_predicate(op.to_hir_binop()),
617                     lhs, rhs
618                 )
619             } else {
620                 bx.icmp(
621                     base::bin_op_to_icmp_predicate(op.to_hir_binop(), is_signed),
622                     lhs, rhs
623                 )
624             }
625         }
626     }
627
628     pub fn codegen_fat_ptr_binop(
629         &mut self,
630         bx: &Builder<'a, 'll, 'tcx>,
631         op: mir::BinOp,
632         lhs_addr: &'ll Value,
633         lhs_extra: &'ll Value,
634         rhs_addr: &'ll Value,
635         rhs_extra: &'ll Value,
636         _input_ty: Ty<'tcx>,
637     ) -> &'ll Value {
638         match op {
639             mir::BinOp::Eq => {
640                 bx.and(
641                     bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr),
642                     bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra)
643                 )
644             }
645             mir::BinOp::Ne => {
646                 bx.or(
647                     bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr),
648                     bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra)
649                 )
650             }
651             mir::BinOp::Le | mir::BinOp::Lt |
652             mir::BinOp::Ge | mir::BinOp::Gt => {
653                 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
654                 let (op, strict_op) = match op {
655                     mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
656                     mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
657                     mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
658                     mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
659                     _ => bug!(),
660                 };
661
662                 bx.or(
663                     bx.icmp(strict_op, lhs_addr, rhs_addr),
664                     bx.and(
665                         bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr),
666                         bx.icmp(op, lhs_extra, rhs_extra)
667                     )
668                 )
669             }
670             _ => {
671                 bug!("unexpected fat ptr binop");
672             }
673         }
674     }
675
676     pub fn codegen_scalar_checked_binop(&mut self,
677                                       bx: &Builder<'a, 'll, 'tcx>,
678                                       op: mir::BinOp,
679                                       lhs: &'ll Value,
680                                       rhs: &'ll Value,
681                                       input_ty: Ty<'tcx>) -> OperandValue<&'ll Value> {
682         // This case can currently arise only from functions marked
683         // with #[rustc_inherit_overflow_checks] and inlined from
684         // another crate (mostly core::num generic/#[inline] fns),
685         // while the current crate doesn't use overflow checks.
686         if !bx.cx().check_overflow {
687             let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
688             return OperandValue::Pair(val, bx.cx().const_bool(false));
689         }
690
691         let (val, of) = match op {
692             // These are checked using intrinsics
693             mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
694                 let oop = match op {
695                     mir::BinOp::Add => OverflowOp::Add,
696                     mir::BinOp::Sub => OverflowOp::Sub,
697                     mir::BinOp::Mul => OverflowOp::Mul,
698                     _ => unreachable!()
699                 };
700                 let intrinsic = get_overflow_intrinsic(oop, bx, input_ty);
701                 let res = bx.call(intrinsic, &[lhs, rhs], None);
702
703                 (bx.extract_value(res, 0),
704                  bx.extract_value(res, 1))
705             }
706             mir::BinOp::Shl | mir::BinOp::Shr => {
707                 let lhs_llty = bx.cx().val_ty(lhs);
708                 let rhs_llty = bx.cx().val_ty(rhs);
709                 let invert_mask = common::shift_mask_val(&bx, lhs_llty, rhs_llty, true);
710                 let outer_bits = bx.and(rhs, invert_mask);
711
712                 let of = bx.icmp(IntPredicate::IntNE, outer_bits, bx.cx().const_null(rhs_llty));
713                 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
714
715                 (val, of)
716             }
717             _ => {
718                 bug!("Operator `{:?}` is not a checkable operator", op)
719             }
720         };
721
722         OperandValue::Pair(val, of)
723     }
724
725     pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool {
726         match *rvalue {
727             mir::Rvalue::Ref(..) |
728             mir::Rvalue::Len(..) |
729             mir::Rvalue::Cast(..) | // (*)
730             mir::Rvalue::BinaryOp(..) |
731             mir::Rvalue::CheckedBinaryOp(..) |
732             mir::Rvalue::UnaryOp(..) |
733             mir::Rvalue::Discriminant(..) |
734             mir::Rvalue::NullaryOp(..) |
735             mir::Rvalue::Use(..) => // (*)
736                 true,
737             mir::Rvalue::Repeat(..) |
738             mir::Rvalue::Aggregate(..) => {
739                 let ty = rvalue.ty(self.mir, self.cx.tcx);
740                 let ty = self.monomorphize(&ty);
741                 self.cx.layout_of(ty).is_zst()
742             }
743         }
744
745         // (*) this is only true if the type is suitable
746     }
747 }
748
749 #[derive(Copy, Clone)]
750 enum OverflowOp {
751     Add, Sub, Mul
752 }
753
754 fn get_overflow_intrinsic(
755     oop: OverflowOp,
756     bx: &Builder<'_, 'll, '_>,
757     ty: Ty
758 ) -> &'ll Value {
759     use syntax::ast::IntTy::*;
760     use syntax::ast::UintTy::*;
761     use rustc::ty::{Int, Uint};
762
763     let tcx = bx.tcx();
764
765     let new_sty = match ty.sty {
766         Int(Isize) => Int(tcx.sess.target.isize_ty),
767         Uint(Usize) => Uint(tcx.sess.target.usize_ty),
768         ref t @ Uint(_) | ref t @ Int(_) => t.clone(),
769         _ => panic!("tried to get overflow intrinsic for op applied to non-int type")
770     };
771
772     let name = match oop {
773         OverflowOp::Add => match new_sty {
774             Int(I8) => "llvm.sadd.with.overflow.i8",
775             Int(I16) => "llvm.sadd.with.overflow.i16",
776             Int(I32) => "llvm.sadd.with.overflow.i32",
777             Int(I64) => "llvm.sadd.with.overflow.i64",
778             Int(I128) => "llvm.sadd.with.overflow.i128",
779
780             Uint(U8) => "llvm.uadd.with.overflow.i8",
781             Uint(U16) => "llvm.uadd.with.overflow.i16",
782             Uint(U32) => "llvm.uadd.with.overflow.i32",
783             Uint(U64) => "llvm.uadd.with.overflow.i64",
784             Uint(U128) => "llvm.uadd.with.overflow.i128",
785
786             _ => unreachable!(),
787         },
788         OverflowOp::Sub => match new_sty {
789             Int(I8) => "llvm.ssub.with.overflow.i8",
790             Int(I16) => "llvm.ssub.with.overflow.i16",
791             Int(I32) => "llvm.ssub.with.overflow.i32",
792             Int(I64) => "llvm.ssub.with.overflow.i64",
793             Int(I128) => "llvm.ssub.with.overflow.i128",
794
795             Uint(U8) => "llvm.usub.with.overflow.i8",
796             Uint(U16) => "llvm.usub.with.overflow.i16",
797             Uint(U32) => "llvm.usub.with.overflow.i32",
798             Uint(U64) => "llvm.usub.with.overflow.i64",
799             Uint(U128) => "llvm.usub.with.overflow.i128",
800
801             _ => unreachable!(),
802         },
803         OverflowOp::Mul => match new_sty {
804             Int(I8) => "llvm.smul.with.overflow.i8",
805             Int(I16) => "llvm.smul.with.overflow.i16",
806             Int(I32) => "llvm.smul.with.overflow.i32",
807             Int(I64) => "llvm.smul.with.overflow.i64",
808             Int(I128) => "llvm.smul.with.overflow.i128",
809
810             Uint(U8) => "llvm.umul.with.overflow.i8",
811             Uint(U16) => "llvm.umul.with.overflow.i16",
812             Uint(U32) => "llvm.umul.with.overflow.i32",
813             Uint(U64) => "llvm.umul.with.overflow.i64",
814             Uint(U128) => "llvm.umul.with.overflow.i128",
815
816             _ => unreachable!(),
817         },
818     };
819
820     bx.cx().get_intrinsic(&name)
821 }
822
823 fn cast_int_to_float(bx: &Builder<'_, 'll, '_>,
824                      signed: bool,
825                      x: &'ll Value,
826                      int_ty: &'ll Type,
827                      float_ty: &'ll Type) -> &'ll Value {
828     // Most integer types, even i128, fit into [-f32::MAX, f32::MAX] after rounding.
829     // It's only u128 -> f32 that can cause overflows (i.e., should yield infinity).
830     // LLVM's uitofp produces undef in those cases, so we manually check for that case.
831     let is_u128_to_f32 = !signed &&
832         bx.cx().int_width(int_ty) == 128 &&
833         bx.cx().float_width(float_ty) == 32;
834     if is_u128_to_f32 {
835         // All inputs greater or equal to (f32::MAX + 0.5 ULP) are rounded to infinity,
836         // and for everything else LLVM's uitofp works just fine.
837         use rustc_apfloat::ieee::Single;
838         use rustc_apfloat::Float;
839         const MAX_F32_PLUS_HALF_ULP: u128 = ((1 << (Single::PRECISION + 1)) - 1)
840                                             << (Single::MAX_EXP - Single::PRECISION as i16);
841         let max = bx.cx().const_uint_big(int_ty, MAX_F32_PLUS_HALF_ULP);
842         let overflow = bx.icmp(IntPredicate::IntUGE, x, max);
843         let infinity_bits = bx.cx().const_u32(ieee::Single::INFINITY.to_bits() as u32);
844         let infinity = consts::bitcast(infinity_bits, float_ty);
845         bx.select(overflow, infinity, bx.uitofp(x, float_ty))
846     } else {
847         if signed {
848             bx.sitofp(x, float_ty)
849         } else {
850             bx.uitofp(x, float_ty)
851         }
852     }
853 }
854
855 fn cast_float_to_int(bx: &Builder<'_, 'll, '_>,
856                      signed: bool,
857                      x: &'ll Value,
858                      float_ty: &'ll Type,
859                      int_ty: &'ll Type) -> &'ll Value {
860     let fptosui_result = if signed {
861         bx.fptosi(x, int_ty)
862     } else {
863         bx.fptoui(x, int_ty)
864     };
865
866     if !bx.sess().opts.debugging_opts.saturating_float_casts {
867         return fptosui_result;
868     }
869     // LLVM's fpto[su]i returns undef when the input x is infinite, NaN, or does not fit into the
870     // destination integer type after rounding towards zero. This `undef` value can cause UB in
871     // safe code (see issue #10184), so we implement a saturating conversion on top of it:
872     // Semantically, the mathematical value of the input is rounded towards zero to the next
873     // mathematical integer, and then the result is clamped into the range of the destination
874     // integer type. Positive and negative infinity are mapped to the maximum and minimum value of
875     // the destination integer type. NaN is mapped to 0.
876     //
877     // Define f_min and f_max as the largest and smallest (finite) floats that are exactly equal to
878     // a value representable in int_ty.
879     // They are exactly equal to int_ty::{MIN,MAX} if float_ty has enough significand bits.
880     // Otherwise, int_ty::MAX must be rounded towards zero, as it is one less than a power of two.
881     // int_ty::MIN, however, is either zero or a negative power of two and is thus exactly
882     // representable. Note that this only works if float_ty's exponent range is sufficiently large.
883     // f16 or 256 bit integers would break this property. Right now the smallest float type is f32
884     // with exponents ranging up to 127, which is barely enough for i128::MIN = -2^127.
885     // On the other hand, f_max works even if int_ty::MAX is greater than float_ty::MAX. Because
886     // we're rounding towards zero, we just get float_ty::MAX (which is always an integer).
887     // This already happens today with u128::MAX = 2^128 - 1 > f32::MAX.
888     let int_max = |signed: bool, int_ty: &'ll Type| -> u128 {
889         let shift_amount = 128 - bx.cx().int_width(int_ty);
890         if signed {
891             i128::MAX as u128 >> shift_amount
892         } else {
893             u128::MAX >> shift_amount
894         }
895     };
896     let int_min = |signed: bool, int_ty: &'ll Type| -> i128 {
897         if signed {
898             i128::MIN >> (128 - bx.cx().int_width(int_ty))
899         } else {
900             0
901         }
902     };
903
904     let compute_clamp_bounds_single = |signed: bool, int_ty: &'ll Type| -> (u128, u128) {
905         let rounded_min = ieee::Single::from_i128_r(int_min(signed, int_ty), Round::TowardZero);
906         assert_eq!(rounded_min.status, Status::OK);
907         let rounded_max = ieee::Single::from_u128_r(int_max(signed, int_ty), Round::TowardZero);
908         assert!(rounded_max.value.is_finite());
909         (rounded_min.value.to_bits(), rounded_max.value.to_bits())
910     };
911     let compute_clamp_bounds_double = |signed: bool, int_ty: &'ll Type| -> (u128, u128) {
912         let rounded_min = ieee::Double::from_i128_r(int_min(signed, int_ty), Round::TowardZero);
913         assert_eq!(rounded_min.status, Status::OK);
914         let rounded_max = ieee::Double::from_u128_r(int_max(signed, int_ty), Round::TowardZero);
915         assert!(rounded_max.value.is_finite());
916         (rounded_min.value.to_bits(), rounded_max.value.to_bits())
917     };
918
919     let float_bits_to_llval = |bits| {
920         let bits_llval = match bx.cx().float_width(float_ty) {
921             32 => bx.cx().const_u32(bits as u32),
922             64 => bx.cx().const_u64(bits as u64),
923             n => bug!("unsupported float width {}", n),
924         };
925         consts::bitcast(bits_llval, float_ty)
926     };
927     let (f_min, f_max) = match bx.cx().float_width(float_ty) {
928         32 => compute_clamp_bounds_single(signed, int_ty),
929         64 => compute_clamp_bounds_double(signed, int_ty),
930         n => bug!("unsupported float width {}", n),
931     };
932     let f_min = float_bits_to_llval(f_min);
933     let f_max = float_bits_to_llval(f_max);
934     // To implement saturation, we perform the following steps:
935     //
936     // 1. Cast x to an integer with fpto[su]i. This may result in undef.
937     // 2. Compare x to f_min and f_max, and use the comparison results to select:
938     //  a) int_ty::MIN if x < f_min or x is NaN
939     //  b) int_ty::MAX if x > f_max
940     //  c) the result of fpto[su]i otherwise
941     // 3. If x is NaN, return 0.0, otherwise return the result of step 2.
942     //
943     // This avoids resulting undef because values in range [f_min, f_max] by definition fit into the
944     // destination type. It creates an undef temporary, but *producing* undef is not UB. Our use of
945     // undef does not introduce any non-determinism either.
946     // More importantly, the above procedure correctly implements saturating conversion.
947     // Proof (sketch):
948     // If x is NaN, 0 is returned by definition.
949     // Otherwise, x is finite or infinite and thus can be compared with f_min and f_max.
950     // This yields three cases to consider:
951     // (1) if x in [f_min, f_max], the result of fpto[su]i is returned, which agrees with
952     //     saturating conversion for inputs in that range.
953     // (2) if x > f_max, then x is larger than int_ty::MAX. This holds even if f_max is rounded
954     //     (i.e., if f_max < int_ty::MAX) because in those cases, nextUp(f_max) is already larger
955     //     than int_ty::MAX. Because x is larger than int_ty::MAX, the return value of int_ty::MAX
956     //     is correct.
957     // (3) if x < f_min, then x is smaller than int_ty::MIN. As shown earlier, f_min exactly equals
958     //     int_ty::MIN and therefore the return value of int_ty::MIN is correct.
959     // QED.
960
961     // Step 1 was already performed above.
962
963     // Step 2: We use two comparisons and two selects, with %s1 being the result:
964     //     %less_or_nan = fcmp ult %x, %f_min
965     //     %greater = fcmp olt %x, %f_max
966     //     %s0 = select %less_or_nan, int_ty::MIN, %fptosi_result
967     //     %s1 = select %greater, int_ty::MAX, %s0
968     // Note that %less_or_nan uses an *unordered* comparison. This comparison is true if the
969     // operands are not comparable (i.e., if x is NaN). The unordered comparison ensures that s1
970     // becomes int_ty::MIN if x is NaN.
971     // Performance note: Unordered comparison can be lowered to a "flipped" comparison and a
972     // negation, and the negation can be merged into the select. Therefore, it not necessarily any
973     // more expensive than a ordered ("normal") comparison. Whether these optimizations will be
974     // performed is ultimately up to the backend, but at least x86 does perform them.
975     let less_or_nan = bx.fcmp(RealPredicate::RealULT, x, f_min);
976     let greater = bx.fcmp(RealPredicate::RealOGT, x, f_max);
977     let int_max = bx.cx().const_uint_big(int_ty, int_max(signed, int_ty));
978     let int_min = bx.cx().const_uint_big(int_ty, int_min(signed, int_ty) as u128);
979     let s0 = bx.select(less_or_nan, int_min, fptosui_result);
980     let s1 = bx.select(greater, int_max, s0);
981
982     // Step 3: NaN replacement.
983     // For unsigned types, the above step already yielded int_ty::MIN == 0 if x is NaN.
984     // Therefore we only need to execute this step for signed integer types.
985     if signed {
986         // LLVM has no isNaN predicate, so we use (x == x) instead
987         bx.select(bx.fcmp(RealPredicate::RealOEQ, x, x), s1, bx.cx().const_uint(int_ty, 0))
988     } else {
989         s1
990     }
991 }