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