]> git.lizzy.rs Git - rust.git/blob - src/common.rs
Move pass mode handling to abi/pass_mode.rs
[rust.git] / src / common.rs
1 use rustc::ty::layout::{FloatTy, Integer, Primitive};
2 use rustc_target::spec::{HasTargetSpec, Target};
3
4 use cranelift::codegen::ir::{Opcode, InstructionData, ValueDef};
5
6 use crate::prelude::*;
7
8 pub fn mir_var(loc: Local) -> Variable {
9     Variable::with_u32(loc.index() as u32)
10 }
11
12 pub fn pointer_ty(tcx: TyCtxt) -> types::Type {
13     match tcx.data_layout.pointer_size.bits() {
14         16 => types::I16,
15         32 => types::I32,
16         64 => types::I64,
17         bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits),
18     }
19 }
20
21 pub fn scalar_to_clif_type(tcx: TyCtxt, scalar: Scalar) -> Type {
22     match scalar.value {
23         Primitive::Int(int, _sign) => match int {
24             Integer::I8 => types::I8,
25             Integer::I16 => types::I16,
26             Integer::I32 => types::I32,
27             Integer::I64 => types::I64,
28             Integer::I128 => types::I128,
29         },
30         Primitive::Float(flt) => match flt {
31             FloatTy::F32 => types::F32,
32             FloatTy::F64 => types::F64,
33         },
34         Primitive::Pointer => pointer_ty(tcx),
35     }
36 }
37
38 pub fn clif_type_from_ty<'tcx>(
39     tcx: TyCtxt<'tcx>,
40     ty: Ty<'tcx>,
41 ) -> Option<types::Type> {
42     Some(match ty.sty {
43         ty::Bool => types::I8,
44         ty::Uint(size) => match size {
45             UintTy::U8 => types::I8,
46             UintTy::U16 => types::I16,
47             UintTy::U32 => types::I32,
48             UintTy::U64 => types::I64,
49             UintTy::U128 => types::I128,
50             UintTy::Usize => pointer_ty(tcx),
51         },
52         ty::Int(size) => match size {
53             IntTy::I8 => types::I8,
54             IntTy::I16 => types::I16,
55             IntTy::I32 => types::I32,
56             IntTy::I64 => types::I64,
57             IntTy::I128 => types::I128,
58             IntTy::Isize => pointer_ty(tcx),
59         },
60         ty::Char => types::I32,
61         ty::Float(size) => match size {
62             FloatTy::F32 => types::F32,
63             FloatTy::F64 => types::F64,
64         },
65         ty::FnPtr(_) => pointer_ty(tcx),
66         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) | ty::Ref(_, ty, _) => {
67             if ty.is_sized(tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
68                 pointer_ty(tcx)
69             } else {
70                 return None;
71             }
72         }
73         ty::Param(_) => bug!("ty param {:?}", ty),
74         _ => return None,
75     })
76 }
77
78 pub fn codegen_select(bcx: &mut FunctionBuilder, cond: Value, lhs: Value, rhs: Value) -> Value {
79     let lhs_ty = bcx.func.dfg.value_type(lhs);
80     let rhs_ty = bcx.func.dfg.value_type(rhs);
81     assert_eq!(lhs_ty, rhs_ty);
82     if lhs_ty == types::I8 || lhs_ty == types::I16 {
83         // FIXME workaround for missing encoding for select.i8
84         let lhs = bcx.ins().uextend(types::I32, lhs);
85         let rhs = bcx.ins().uextend(types::I32, rhs);
86         let res = bcx.ins().select(cond, lhs, rhs);
87         bcx.ins().ireduce(lhs_ty, res)
88     } else {
89         bcx.ins().select(cond, lhs, rhs)
90     }
91 }
92
93 pub fn codegen_icmp(
94     fx: &mut FunctionCx<'_, '_, impl Backend>,
95     intcc: IntCC,
96     lhs: Value,
97     rhs: Value,
98 ) -> Value {
99     let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
100     let rhs_ty = fx.bcx.func.dfg.value_type(rhs);
101     assert_eq!(lhs_ty, rhs_ty);
102     if lhs_ty == types::I128 {
103         // FIXME legalize `icmp.i128` in Cranelift
104
105         let (lhs_lsb, lhs_msb) = fx.bcx.ins().isplit(lhs);
106         let (rhs_lsb, rhs_msb) = fx.bcx.ins().isplit(rhs);
107
108         match intcc {
109             IntCC::Equal => {
110                 let lsb_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_lsb, rhs_lsb);
111                 let msb_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_msb, rhs_msb);
112                 fx.bcx.ins().band(lsb_eq, msb_eq)
113             }
114             IntCC::NotEqual => {
115                 let lsb_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_lsb, rhs_lsb);
116                 let msb_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_msb, rhs_msb);
117                 fx.bcx.ins().bor(lsb_ne, msb_ne)
118             }
119             _ => {
120                 // if msb_eq {
121                 //     lsb_cc
122                 // } else {
123                 //     msb_cc
124                 // }
125
126                 let msb_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_msb, rhs_msb);
127                 let lsb_cc = fx.bcx.ins().icmp(intcc, lhs_lsb, rhs_lsb);
128                 let msb_cc = fx.bcx.ins().icmp(intcc, lhs_msb, rhs_msb);
129
130                 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
131             }
132         }
133     } else {
134         fx.bcx.ins().icmp(intcc, lhs, rhs)
135     }
136 }
137
138 pub fn codegen_icmp_imm(
139     fx: &mut FunctionCx<'_, '_, impl Backend>,
140     intcc: IntCC,
141     lhs: Value,
142     rhs: i128,
143 ) -> Value {
144     let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
145     if lhs_ty == types::I128 {
146         // FIXME legalize `icmp_imm.i128` in Cranelift
147
148         let (lhs_lsb, lhs_msb) = fx.bcx.ins().isplit(lhs);
149         let (rhs_lsb, rhs_msb) = (rhs as u128 as u64 as i64, (rhs as u128 >> 64) as u64 as i64);
150
151         match intcc {
152             IntCC::Equal => {
153                 let lsb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_lsb, rhs_lsb);
154                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
155                 fx.bcx.ins().band(lsb_eq, msb_eq)
156             }
157             IntCC::NotEqual => {
158                 let lsb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_lsb, rhs_lsb);
159                 let msb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_msb, rhs_msb);
160                 fx.bcx.ins().bor(lsb_ne, msb_ne)
161             }
162             _ => {
163                 // if msb_eq {
164                 //     lsb_cc
165                 // } else {
166                 //     msb_cc
167                 // }
168
169                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
170                 let lsb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_lsb, rhs_lsb);
171                 let msb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_msb, rhs_msb);
172
173                 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
174             }
175         }
176     } else {
177         let rhs = i64::try_from(rhs).expect("codegen_icmp_imm rhs out of range for <128bit int");
178         fx.bcx.ins().icmp_imm(intcc, lhs, rhs)
179     }
180 }
181
182 fn resolve_normal_value_imm(func: &Function, val: Value) -> Option<i64> {
183     if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
184         if let InstructionData::UnaryImm {
185             opcode: Opcode::Iconst,
186             imm,
187         } = func.dfg[inst] {
188             Some(imm.into())
189         } else {
190             None
191         }
192     } else {
193         None
194     }
195 }
196
197 fn resolve_128bit_value_imm(func: &Function, val: Value) -> Option<u128> {
198     let (lsb, msb) = if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
199         if let InstructionData::Binary {
200             opcode: Opcode::Iconcat,
201             args: [lsb, msb],
202         } = func.dfg[inst] {
203             (lsb, msb)
204         } else {
205             return None;
206         }
207     } else {
208         return None;
209     };
210
211     let lsb = resolve_normal_value_imm(func, lsb)? as u64 as u128;
212     let msb = resolve_normal_value_imm(func, msb)? as u64 as u128;
213
214     Some(msb << 64 | lsb)
215 }
216
217 pub fn resolve_value_imm(func: &Function, val: Value) -> Option<u128> {
218     if func.dfg.value_type(val) == types::I128 {
219         resolve_128bit_value_imm(func, val)
220     } else {
221         resolve_normal_value_imm(func, val).map(|imm| imm as u64 as u128)
222     }
223 }
224
225 pub fn type_min_max_value(ty: Type, signed: bool) -> (i64, i64) {
226     assert!(ty.is_int());
227     let min = match (ty, signed) {
228         (types::I8 , false)
229         | (types::I16, false)
230         | (types::I32, false)
231         | (types::I64, false) => 0i64,
232         (types::I8, true) => i8::min_value() as i64,
233         (types::I16, true) => i16::min_value() as i64,
234         (types::I32, true) => i32::min_value() as i64,
235         (types::I64, true) => i64::min_value(),
236         (types::I128, _) => unimplemented!(),
237         _ => unreachable!(),
238     };
239
240     let max = match (ty, signed) {
241         (types::I8, false) => u8::max_value() as i64,
242         (types::I16, false) => u16::max_value() as i64,
243         (types::I32, false) => u32::max_value() as i64,
244         (types::I64, false) => u64::max_value() as i64,
245         (types::I8, true) => i8::max_value() as i64,
246         (types::I16, true) => i16::max_value() as i64,
247         (types::I32, true) => i32::max_value() as i64,
248         (types::I64, true) => i64::max_value(),
249         (types::I128, _) => unimplemented!(),
250         _ => unreachable!(),
251     };
252
253     (min, max)
254 }
255
256 pub fn type_sign(ty: Ty<'_>) -> bool {
257     match ty.sty {
258         ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
259         ty::Int(..) => true,
260         ty::Float(..) => false, // `signed` is unused for floats
261         _ => panic!("{}", ty),
262     }
263 }
264
265 pub struct FunctionCx<'clif, 'tcx, B: Backend + 'static> {
266     // FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
267     pub tcx: TyCtxt<'tcx>,
268     pub module: &'clif mut Module<B>,
269     pub pointer_type: Type, // Cached from module
270
271     pub instance: Instance<'tcx>,
272     pub mir: &'tcx Body<'tcx>,
273
274     pub bcx: FunctionBuilder<'clif>,
275     pub ebb_map: HashMap<BasicBlock, Ebb>,
276     pub local_map: HashMap<Local, CPlace<'tcx>>,
277
278     pub clif_comments: crate::pretty_clif::CommentWriter,
279     pub constants_cx: &'clif mut crate::constant::ConstantCx,
280     pub caches: &'clif mut Caches<'tcx>,
281     pub source_info_set: indexmap::IndexSet<SourceInfo>,
282 }
283
284 impl<'tcx, B: Backend> LayoutOf for FunctionCx<'_, 'tcx, B> {
285     type Ty = Ty<'tcx>;
286     type TyLayout = TyLayout<'tcx>;
287
288     fn layout_of(&self, ty: Ty<'tcx>) -> TyLayout<'tcx> {
289         let ty = self.monomorphize(&ty);
290         self.tcx.layout_of(ParamEnv::reveal_all().and(&ty))
291             .unwrap_or_else(|e| if let layout::LayoutError::SizeOverflow(_) = e {
292                 self.tcx.sess.fatal(&e.to_string())
293             } else {
294                 bug!("failed to get layout for `{}`: {}", ty, e)
295             })
296     }
297 }
298
299 impl<'tcx, B: Backend + 'static> layout::HasTyCtxt<'tcx> for FunctionCx<'_, 'tcx, B> {
300     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
301         self.tcx
302     }
303 }
304
305 impl<'tcx, B: Backend + 'static> layout::HasDataLayout for FunctionCx<'_, 'tcx, B> {
306     fn data_layout(&self) -> &layout::TargetDataLayout {
307         &self.tcx.data_layout
308     }
309 }
310
311 impl<'tcx, B: Backend + 'static> layout::HasParamEnv<'tcx> for FunctionCx<'_, 'tcx, B> {
312     fn param_env(&self) -> ParamEnv<'tcx> {
313         ParamEnv::reveal_all()
314     }
315 }
316
317 impl<'tcx, B: Backend + 'static> HasTargetSpec for FunctionCx<'_, 'tcx, B> {
318     fn target_spec(&self) -> &Target {
319         &self.tcx.sess.target.target
320     }
321 }
322
323 impl<'tcx, B: Backend> BackendTypes for FunctionCx<'_, 'tcx, B> {
324     type Value = Value;
325     type BasicBlock = Ebb;
326     type Type = Type;
327     type Funclet = !;
328     type DIScope = !;
329 }
330
331 impl<'tcx, B: Backend + 'static> FunctionCx<'_, 'tcx, B> {
332     pub fn monomorphize<T>(&self, value: &T) -> T
333     where
334         T: TypeFoldable<'tcx>,
335     {
336         self.tcx.subst_and_normalize_erasing_regions(
337             self.instance.substs,
338             ty::ParamEnv::reveal_all(),
339             value,
340         )
341     }
342
343     pub fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
344         clif_type_from_ty(self.tcx, self.monomorphize(&ty))
345     }
346
347     pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
348         *self.ebb_map.get(&bb).unwrap()
349     }
350
351     pub fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
352         *self.local_map.get(&local).unwrap()
353     }
354
355     pub fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
356         let (index, _) = self.source_info_set.insert_full(source_info);
357         self.bcx.set_srcloc(SourceLoc::new(index as u32));
358     }
359 }