]> git.lizzy.rs Git - rust.git/blob - src/num.rs
Fold `vtable_trait_upcasting_coercion_new_vptr_slot` logic into obligation processing.
[rust.git] / src / num.rs
1 //! Various operations on integer and floating-point numbers
2
3 use crate::prelude::*;
4
5 pub(crate) fn bin_op_to_intcc(bin_op: BinOp, signed: bool) -> Option<IntCC> {
6     use BinOp::*;
7     use IntCC::*;
8     Some(match bin_op {
9         Eq => Equal,
10         Lt => {
11             if signed {
12                 SignedLessThan
13             } else {
14                 UnsignedLessThan
15             }
16         }
17         Le => {
18             if signed {
19                 SignedLessThanOrEqual
20             } else {
21                 UnsignedLessThanOrEqual
22             }
23         }
24         Ne => NotEqual,
25         Ge => {
26             if signed {
27                 SignedGreaterThanOrEqual
28             } else {
29                 UnsignedGreaterThanOrEqual
30             }
31         }
32         Gt => {
33             if signed {
34                 SignedGreaterThan
35             } else {
36                 UnsignedGreaterThan
37             }
38         }
39         _ => return None,
40     })
41 }
42
43 fn codegen_compare_bin_op<'tcx>(
44     fx: &mut FunctionCx<'_, '_, 'tcx>,
45     bin_op: BinOp,
46     signed: bool,
47     lhs: Value,
48     rhs: Value,
49 ) -> CValue<'tcx> {
50     let intcc = crate::num::bin_op_to_intcc(bin_op, signed).unwrap();
51     let val = fx.bcx.ins().icmp(intcc, lhs, rhs);
52     let val = fx.bcx.ins().bint(types::I8, val);
53     CValue::by_val(val, fx.layout_of(fx.tcx.types.bool))
54 }
55
56 pub(crate) fn codegen_binop<'tcx>(
57     fx: &mut FunctionCx<'_, '_, 'tcx>,
58     bin_op: BinOp,
59     in_lhs: CValue<'tcx>,
60     in_rhs: CValue<'tcx>,
61 ) -> CValue<'tcx> {
62     match bin_op {
63         BinOp::Eq | BinOp::Lt | BinOp::Le | BinOp::Ne | BinOp::Ge | BinOp::Gt => {
64             match in_lhs.layout().ty.kind() {
65                 ty::Bool | ty::Uint(_) | ty::Int(_) | ty::Char => {
66                     let signed = type_sign(in_lhs.layout().ty);
67                     let lhs = in_lhs.load_scalar(fx);
68                     let rhs = in_rhs.load_scalar(fx);
69
70                     return codegen_compare_bin_op(fx, bin_op, signed, lhs, rhs);
71                 }
72                 _ => {}
73             }
74         }
75         _ => {}
76     }
77
78     match in_lhs.layout().ty.kind() {
79         ty::Bool => crate::num::codegen_bool_binop(fx, bin_op, in_lhs, in_rhs),
80         ty::Uint(_) | ty::Int(_) => crate::num::codegen_int_binop(fx, bin_op, in_lhs, in_rhs),
81         ty::Float(_) => crate::num::codegen_float_binop(fx, bin_op, in_lhs, in_rhs),
82         ty::RawPtr(..) | ty::FnPtr(..) => crate::num::codegen_ptr_binop(fx, bin_op, in_lhs, in_rhs),
83         _ => unreachable!("{:?}({:?}, {:?})", bin_op, in_lhs.layout().ty, in_rhs.layout().ty),
84     }
85 }
86
87 pub(crate) fn codegen_bool_binop<'tcx>(
88     fx: &mut FunctionCx<'_, '_, 'tcx>,
89     bin_op: BinOp,
90     in_lhs: CValue<'tcx>,
91     in_rhs: CValue<'tcx>,
92 ) -> CValue<'tcx> {
93     let lhs = in_lhs.load_scalar(fx);
94     let rhs = in_rhs.load_scalar(fx);
95
96     let b = fx.bcx.ins();
97     let res = match bin_op {
98         BinOp::BitXor => b.bxor(lhs, rhs),
99         BinOp::BitAnd => b.band(lhs, rhs),
100         BinOp::BitOr => b.bor(lhs, rhs),
101         // Compare binops handles by `codegen_binop`.
102         _ => unreachable!("{:?}({:?}, {:?})", bin_op, in_lhs, in_rhs),
103     };
104
105     CValue::by_val(res, fx.layout_of(fx.tcx.types.bool))
106 }
107
108 pub(crate) fn codegen_int_binop<'tcx>(
109     fx: &mut FunctionCx<'_, '_, 'tcx>,
110     bin_op: BinOp,
111     in_lhs: CValue<'tcx>,
112     in_rhs: CValue<'tcx>,
113 ) -> CValue<'tcx> {
114     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
115         assert_eq!(
116             in_lhs.layout().ty,
117             in_rhs.layout().ty,
118             "int binop requires lhs and rhs of same type"
119         );
120     }
121
122     if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, false, in_lhs, in_rhs) {
123         return res;
124     }
125
126     let signed = type_sign(in_lhs.layout().ty);
127
128     let lhs = in_lhs.load_scalar(fx);
129     let rhs = in_rhs.load_scalar(fx);
130
131     let b = fx.bcx.ins();
132     let val = match bin_op {
133         BinOp::Add => b.iadd(lhs, rhs),
134         BinOp::Sub => b.isub(lhs, rhs),
135         BinOp::Mul => b.imul(lhs, rhs),
136         BinOp::Div => {
137             if signed {
138                 b.sdiv(lhs, rhs)
139             } else {
140                 b.udiv(lhs, rhs)
141             }
142         }
143         BinOp::Rem => {
144             if signed {
145                 b.srem(lhs, rhs)
146             } else {
147                 b.urem(lhs, rhs)
148             }
149         }
150         BinOp::BitXor => b.bxor(lhs, rhs),
151         BinOp::BitAnd => b.band(lhs, rhs),
152         BinOp::BitOr => b.bor(lhs, rhs),
153         BinOp::Shl => {
154             let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
155             let actual_shift = fx.bcx.ins().band_imm(rhs, i64::from(lhs_ty.bits() - 1));
156             fx.bcx.ins().ishl(lhs, actual_shift)
157         }
158         BinOp::Shr => {
159             let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
160             let actual_shift = fx.bcx.ins().band_imm(rhs, i64::from(lhs_ty.bits() - 1));
161             if signed {
162                 fx.bcx.ins().sshr(lhs, actual_shift)
163             } else {
164                 fx.bcx.ins().ushr(lhs, actual_shift)
165             }
166         }
167         // Compare binops handles by `codegen_binop`.
168         _ => unreachable!("{:?}({:?}, {:?})", bin_op, in_lhs.layout().ty, in_rhs.layout().ty),
169     };
170
171     CValue::by_val(val, in_lhs.layout())
172 }
173
174 pub(crate) fn codegen_checked_int_binop<'tcx>(
175     fx: &mut FunctionCx<'_, '_, 'tcx>,
176     bin_op: BinOp,
177     in_lhs: CValue<'tcx>,
178     in_rhs: CValue<'tcx>,
179 ) -> CValue<'tcx> {
180     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
181         assert_eq!(
182             in_lhs.layout().ty,
183             in_rhs.layout().ty,
184             "checked int binop requires lhs and rhs of same type"
185         );
186     }
187
188     let lhs = in_lhs.load_scalar(fx);
189     let rhs = in_rhs.load_scalar(fx);
190
191     if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, true, in_lhs, in_rhs) {
192         return res;
193     }
194
195     let signed = type_sign(in_lhs.layout().ty);
196
197     let (res, has_overflow) = match bin_op {
198         BinOp::Add => {
199             /*let (val, c_out) = fx.bcx.ins().iadd_cout(lhs, rhs);
200             (val, c_out)*/
201             // FIXME(CraneStation/cranelift#849) legalize iadd_cout for i8 and i16
202             let val = fx.bcx.ins().iadd(lhs, rhs);
203             let has_overflow = if !signed {
204                 fx.bcx.ins().icmp(IntCC::UnsignedLessThan, val, lhs)
205             } else {
206                 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
207                 let slt = fx.bcx.ins().icmp(IntCC::SignedLessThan, val, lhs);
208                 fx.bcx.ins().bxor(rhs_is_negative, slt)
209             };
210             (val, has_overflow)
211         }
212         BinOp::Sub => {
213             /*let (val, b_out) = fx.bcx.ins().isub_bout(lhs, rhs);
214             (val, b_out)*/
215             // FIXME(CraneStation/cranelift#849) legalize isub_bout for i8 and i16
216             let val = fx.bcx.ins().isub(lhs, rhs);
217             let has_overflow = if !signed {
218                 fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, val, lhs)
219             } else {
220                 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
221                 let sgt = fx.bcx.ins().icmp(IntCC::SignedGreaterThan, val, lhs);
222                 fx.bcx.ins().bxor(rhs_is_negative, sgt)
223             };
224             (val, has_overflow)
225         }
226         BinOp::Mul => {
227             let ty = fx.bcx.func.dfg.value_type(lhs);
228             match ty {
229                 types::I8 | types::I16 | types::I32 if !signed => {
230                     let lhs = fx.bcx.ins().uextend(ty.double_width().unwrap(), lhs);
231                     let rhs = fx.bcx.ins().uextend(ty.double_width().unwrap(), rhs);
232                     let val = fx.bcx.ins().imul(lhs, rhs);
233                     let has_overflow = fx.bcx.ins().icmp_imm(
234                         IntCC::UnsignedGreaterThan,
235                         val,
236                         (1 << ty.bits()) - 1,
237                     );
238                     let val = fx.bcx.ins().ireduce(ty, val);
239                     (val, has_overflow)
240                 }
241                 types::I8 | types::I16 | types::I32 if signed => {
242                     let lhs = fx.bcx.ins().sextend(ty.double_width().unwrap(), lhs);
243                     let rhs = fx.bcx.ins().sextend(ty.double_width().unwrap(), rhs);
244                     let val = fx.bcx.ins().imul(lhs, rhs);
245                     let has_underflow =
246                         fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, val, -(1 << (ty.bits() - 1)));
247                     let has_overflow = fx.bcx.ins().icmp_imm(
248                         IntCC::SignedGreaterThan,
249                         val,
250                         (1 << (ty.bits() - 1)) - 1,
251                     );
252                     let val = fx.bcx.ins().ireduce(ty, val);
253                     (val, fx.bcx.ins().bor(has_underflow, has_overflow))
254                 }
255                 types::I64 => {
256                     let val = fx.bcx.ins().imul(lhs, rhs);
257                     let has_overflow = if !signed {
258                         let val_hi = fx.bcx.ins().umulhi(lhs, rhs);
259                         fx.bcx.ins().icmp_imm(IntCC::NotEqual, val_hi, 0)
260                     } else {
261                         // Based on LLVM's instruction sequence for compiling
262                         // a.checked_mul(b).is_some() to riscv64gc:
263                         // mulh    a2, a0, a1
264                         // mul     a0, a0, a1
265                         // srai    a0, a0, 63
266                         // xor     a0, a0, a2
267                         // snez    a0, a0
268                         let val_hi = fx.bcx.ins().smulhi(lhs, rhs);
269                         let val_sign = fx.bcx.ins().sshr_imm(val, i64::from(ty.bits() - 1));
270                         let xor = fx.bcx.ins().bxor(val_hi, val_sign);
271                         fx.bcx.ins().icmp_imm(IntCC::NotEqual, xor, 0)
272                     };
273                     (val, has_overflow)
274                 }
275                 types::I128 => {
276                     unreachable!("i128 should have been handled by codegen_i128::maybe_codegen")
277                 }
278                 _ => unreachable!("invalid non-integer type {}", ty),
279             }
280         }
281         BinOp::Shl => {
282             let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
283             let masked_shift = fx.bcx.ins().band_imm(rhs, i64::from(lhs_ty.bits() - 1));
284             let val = fx.bcx.ins().ishl(lhs, masked_shift);
285             let ty = fx.bcx.func.dfg.value_type(val);
286             let max_shift = i64::from(ty.bits()) - 1;
287             let has_overflow = fx.bcx.ins().icmp_imm(IntCC::UnsignedGreaterThan, rhs, max_shift);
288             (val, has_overflow)
289         }
290         BinOp::Shr => {
291             let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
292             let masked_shift = fx.bcx.ins().band_imm(rhs, i64::from(lhs_ty.bits() - 1));
293             let val = if !signed {
294                 fx.bcx.ins().ushr(lhs, masked_shift)
295             } else {
296                 fx.bcx.ins().sshr(lhs, masked_shift)
297             };
298             let ty = fx.bcx.func.dfg.value_type(val);
299             let max_shift = i64::from(ty.bits()) - 1;
300             let has_overflow = fx.bcx.ins().icmp_imm(IntCC::UnsignedGreaterThan, rhs, max_shift);
301             (val, has_overflow)
302         }
303         _ => bug!("binop {:?} on checked int/uint lhs: {:?} rhs: {:?}", bin_op, in_lhs, in_rhs),
304     };
305
306     let has_overflow = fx.bcx.ins().bint(types::I8, has_overflow);
307
308     let out_layout = fx.layout_of(fx.tcx.mk_tup([in_lhs.layout().ty, fx.tcx.types.bool].iter()));
309     CValue::by_val_pair(res, has_overflow, out_layout)
310 }
311
312 pub(crate) fn codegen_float_binop<'tcx>(
313     fx: &mut FunctionCx<'_, '_, 'tcx>,
314     bin_op: BinOp,
315     in_lhs: CValue<'tcx>,
316     in_rhs: CValue<'tcx>,
317 ) -> CValue<'tcx> {
318     assert_eq!(in_lhs.layout().ty, in_rhs.layout().ty);
319
320     let lhs = in_lhs.load_scalar(fx);
321     let rhs = in_rhs.load_scalar(fx);
322
323     let b = fx.bcx.ins();
324     let res = match bin_op {
325         BinOp::Add => b.fadd(lhs, rhs),
326         BinOp::Sub => b.fsub(lhs, rhs),
327         BinOp::Mul => b.fmul(lhs, rhs),
328         BinOp::Div => b.fdiv(lhs, rhs),
329         BinOp::Rem => {
330             let name = match in_lhs.layout().ty.kind() {
331                 ty::Float(FloatTy::F32) => "fmodf",
332                 ty::Float(FloatTy::F64) => "fmod",
333                 _ => bug!(),
334             };
335             return fx.easy_call(name, &[in_lhs, in_rhs], in_lhs.layout().ty);
336         }
337         BinOp::Eq | BinOp::Lt | BinOp::Le | BinOp::Ne | BinOp::Ge | BinOp::Gt => {
338             let fltcc = match bin_op {
339                 BinOp::Eq => FloatCC::Equal,
340                 BinOp::Lt => FloatCC::LessThan,
341                 BinOp::Le => FloatCC::LessThanOrEqual,
342                 BinOp::Ne => FloatCC::NotEqual,
343                 BinOp::Ge => FloatCC::GreaterThanOrEqual,
344                 BinOp::Gt => FloatCC::GreaterThan,
345                 _ => unreachable!(),
346             };
347             let val = fx.bcx.ins().fcmp(fltcc, lhs, rhs);
348             let val = fx.bcx.ins().bint(types::I8, val);
349             return CValue::by_val(val, fx.layout_of(fx.tcx.types.bool));
350         }
351         _ => unreachable!("{:?}({:?}, {:?})", bin_op, in_lhs, in_rhs),
352     };
353
354     CValue::by_val(res, in_lhs.layout())
355 }
356
357 pub(crate) fn codegen_ptr_binop<'tcx>(
358     fx: &mut FunctionCx<'_, '_, 'tcx>,
359     bin_op: BinOp,
360     in_lhs: CValue<'tcx>,
361     in_rhs: CValue<'tcx>,
362 ) -> CValue<'tcx> {
363     let is_thin_ptr = in_lhs
364         .layout()
365         .ty
366         .builtin_deref(true)
367         .map(|TypeAndMut { ty, mutbl: _ }| !has_ptr_meta(fx.tcx, ty))
368         .unwrap_or(true);
369
370     if is_thin_ptr {
371         match bin_op {
372             BinOp::Eq | BinOp::Lt | BinOp::Le | BinOp::Ne | BinOp::Ge | BinOp::Gt => {
373                 let lhs = in_lhs.load_scalar(fx);
374                 let rhs = in_rhs.load_scalar(fx);
375
376                 codegen_compare_bin_op(fx, bin_op, false, lhs, rhs)
377             }
378             BinOp::Offset => {
379                 let pointee_ty = in_lhs.layout().ty.builtin_deref(true).unwrap().ty;
380                 let (base, offset) = (in_lhs, in_rhs.load_scalar(fx));
381                 let pointee_size = fx.layout_of(pointee_ty).size.bytes();
382                 let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
383                 let base_val = base.load_scalar(fx);
384                 let res = fx.bcx.ins().iadd(base_val, ptr_diff);
385                 CValue::by_val(res, base.layout())
386             }
387             _ => unreachable!("{:?}({:?}, {:?})", bin_op, in_lhs, in_rhs),
388         }
389     } else {
390         let (lhs_ptr, lhs_extra) = in_lhs.load_scalar_pair(fx);
391         let (rhs_ptr, rhs_extra) = in_rhs.load_scalar_pair(fx);
392
393         let res = match bin_op {
394             BinOp::Eq => {
395                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
396                 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
397                 fx.bcx.ins().band(ptr_eq, extra_eq)
398             }
399             BinOp::Ne => {
400                 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
401                 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
402                 fx.bcx.ins().bor(ptr_ne, extra_ne)
403             }
404             BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
405                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
406
407                 let ptr_cmp =
408                     fx.bcx.ins().icmp(bin_op_to_intcc(bin_op, false).unwrap(), lhs_ptr, rhs_ptr);
409                 let extra_cmp = fx.bcx.ins().icmp(
410                     bin_op_to_intcc(bin_op, false).unwrap(),
411                     lhs_extra,
412                     rhs_extra,
413                 );
414
415                 fx.bcx.ins().select(ptr_eq, extra_cmp, ptr_cmp)
416             }
417             _ => panic!("bin_op {:?} on ptr", bin_op),
418         };
419
420         CValue::by_val(fx.bcx.ins().bint(types::I8, res), fx.layout_of(fx.tcx.types.bool))
421     }
422 }