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