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