]> git.lizzy.rs Git - rust.git/blob - src/common.rs
Store pairs in SSA
[rust.git] / src / common.rs
1 use rustc_target::abi::{Integer, Primitive};
2 use rustc_target::spec::{HasTargetSpec, Target};
3 use rustc_index::vec::IndexVec;
4
5 use cranelift_codegen::ir::{InstructionData, Opcode, ValueDef};
6
7 use crate::prelude::*;
8
9 pub(crate) fn pointer_ty(tcx: TyCtxt<'_>) -> types::Type {
10     match tcx.data_layout.pointer_size.bits() {
11         16 => types::I16,
12         32 => types::I32,
13         64 => types::I64,
14         bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits),
15     }
16 }
17
18 pub(crate) fn scalar_to_clif_type(tcx: TyCtxt<'_>, scalar: Scalar) -> Type {
19     match scalar.value {
20         Primitive::Int(int, _sign) => match int {
21             Integer::I8 => types::I8,
22             Integer::I16 => types::I16,
23             Integer::I32 => types::I32,
24             Integer::I64 => types::I64,
25             Integer::I128 => types::I128,
26         },
27         Primitive::F32 => types::F32,
28         Primitive::F64 => types::F64,
29         Primitive::Pointer => pointer_ty(tcx),
30     }
31 }
32
33 fn clif_type_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<types::Type> {
34     Some(match ty.kind {
35         ty::Bool => types::I8,
36         ty::Uint(size) => match size {
37             UintTy::U8 => types::I8,
38             UintTy::U16 => types::I16,
39             UintTy::U32 => types::I32,
40             UintTy::U64 => types::I64,
41             UintTy::U128 => types::I128,
42             UintTy::Usize => pointer_ty(tcx),
43         },
44         ty::Int(size) => match size {
45             IntTy::I8 => types::I8,
46             IntTy::I16 => types::I16,
47             IntTy::I32 => types::I32,
48             IntTy::I64 => types::I64,
49             IntTy::I128 => types::I128,
50             IntTy::Isize => pointer_ty(tcx),
51         },
52         ty::Char => types::I32,
53         ty::Float(size) => match size {
54             FloatTy::F32 => types::F32,
55             FloatTy::F64 => types::F64,
56         },
57         ty::FnPtr(_) => pointer_ty(tcx),
58         ty::RawPtr(TypeAndMut { ty: pointee_ty, mutbl: _ }) | ty::Ref(_, pointee_ty, _) => {
59             if has_ptr_meta(tcx, pointee_ty) {
60                 return None;
61             } else {
62                 pointer_ty(tcx)
63             }
64         }
65         ty::Param(_) => bug!("ty param {:?}", ty),
66         _ => return None,
67     })
68 }
69
70 fn clif_pair_type_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<(types::Type, types::Type)> {
71     Some(match ty.kind {
72         ty::Tuple(substs) if substs.len() == 2 => {
73             let mut types = substs.types();
74             (
75                 clif_type_from_ty(tcx, types.next().unwrap())?,
76                 clif_type_from_ty(tcx, types.next().unwrap())?,
77             )
78         }
79         _ => return None,
80     })
81 }
82
83 /// Is a pointer to this type a fat ptr?
84 pub(crate) fn has_ptr_meta<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
85     let ptr_ty = tcx.mk_ptr(TypeAndMut { ty, mutbl: rustc_hir::Mutability::Not });
86     match &tcx.layout_of(ParamEnv::reveal_all().and(ptr_ty)).unwrap().abi {
87         Abi::Scalar(_) => false,
88         Abi::ScalarPair(_, _) => true,
89         abi => unreachable!("Abi of ptr to {:?} is {:?}???", ty, abi),
90     }
91 }
92
93 pub(crate) fn codegen_icmp_imm(
94     fx: &mut FunctionCx<'_, '_, impl Backend>,
95     intcc: IntCC,
96     lhs: Value,
97     rhs: i128,
98 ) -> Value {
99     let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
100     if lhs_ty == types::I128 {
101         // FIXME legalize `icmp_imm.i128` in Cranelift
102
103         let (lhs_lsb, lhs_msb) = fx.bcx.ins().isplit(lhs);
104         let (rhs_lsb, rhs_msb) = (rhs as u128 as u64 as i64, (rhs as u128 >> 64) as u64 as i64);
105
106         match intcc {
107             IntCC::Equal => {
108                 let lsb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_lsb, rhs_lsb);
109                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
110                 fx.bcx.ins().band(lsb_eq, msb_eq)
111             }
112             IntCC::NotEqual => {
113                 let lsb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_lsb, rhs_lsb);
114                 let msb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_msb, rhs_msb);
115                 fx.bcx.ins().bor(lsb_ne, msb_ne)
116             }
117             _ => {
118                 // if msb_eq {
119                 //     lsb_cc
120                 // } else {
121                 //     msb_cc
122                 // }
123
124                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
125                 let lsb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_lsb, rhs_lsb);
126                 let msb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_msb, rhs_msb);
127
128                 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
129             }
130         }
131     } else {
132         let rhs = i64::try_from(rhs).expect("codegen_icmp_imm rhs out of range for <128bit int");
133         fx.bcx.ins().icmp_imm(intcc, lhs, rhs)
134     }
135 }
136
137 fn resolve_normal_value_imm(func: &Function, val: Value) -> Option<i64> {
138     if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
139         if let InstructionData::UnaryImm {
140             opcode: Opcode::Iconst,
141             imm,
142         } = func.dfg[inst]
143         {
144             Some(imm.into())
145         } else {
146             None
147         }
148     } else {
149         None
150     }
151 }
152
153 fn resolve_128bit_value_imm(func: &Function, val: Value) -> Option<u128> {
154     let (lsb, msb) = if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
155         if let InstructionData::Binary {
156             opcode: Opcode::Iconcat,
157             args: [lsb, msb],
158         } = func.dfg[inst]
159         {
160             (lsb, msb)
161         } else {
162             return None;
163         }
164     } else {
165         return None;
166     };
167
168     let lsb = resolve_normal_value_imm(func, lsb)? as u64 as u128;
169     let msb = resolve_normal_value_imm(func, msb)? as u64 as u128;
170
171     Some(msb << 64 | lsb)
172 }
173
174 pub(crate) fn resolve_value_imm(func: &Function, val: Value) -> Option<u128> {
175     if func.dfg.value_type(val) == types::I128 {
176         resolve_128bit_value_imm(func, val)
177     } else {
178         resolve_normal_value_imm(func, val).map(|imm| imm as u64 as u128)
179     }
180 }
181
182 pub(crate) fn type_min_max_value(bcx: &mut FunctionBuilder<'_>, ty: Type, signed: bool) -> (Value, Value) {
183     assert!(ty.is_int());
184
185     if ty == types::I128 {
186         if signed {
187             let min = i128::MIN as u128;
188             let min_lsb = bcx.ins().iconst(types::I64, min as u64 as i64);
189             let min_msb = bcx.ins().iconst(types::I64, (min >> 64) as u64 as i64);
190             let min = bcx.ins().iconcat(min_lsb, min_msb);
191
192             let max = i128::MIN as u128;
193             let max_lsb = bcx.ins().iconst(types::I64, max as u64 as i64);
194             let max_msb = bcx.ins().iconst(types::I64, (max >> 64) as u64 as i64);
195             let max = bcx.ins().iconcat(max_lsb, max_msb);
196
197             return (min, max);
198         } else {
199             let min_half = bcx.ins().iconst(types::I64, 0);
200             let min = bcx.ins().iconcat(min_half, min_half);
201
202             let max_half = bcx.ins().iconst(types::I64, u64::MAX as i64);
203             let max = bcx.ins().iconcat(max_half, max_half);
204
205             return (min, max);
206         }
207     }
208
209     let min = match (ty, signed) {
210         (types::I8, false) | (types::I16, false) | (types::I32, false) | (types::I64, false) => {
211             0i64
212         }
213         (types::I8, true) => i8::MIN as i64,
214         (types::I16, true) => i16::MIN as i64,
215         (types::I32, true) => i32::MIN as i64,
216         (types::I64, true) => i64::MIN,
217         _ => unreachable!(),
218     };
219
220     let max = match (ty, signed) {
221         (types::I8, false) => u8::MAX as i64,
222         (types::I16, false) => u16::MAX as i64,
223         (types::I32, false) => u32::MAX as i64,
224         (types::I64, false) => u64::MAX as i64,
225         (types::I8, true) => i8::MAX as i64,
226         (types::I16, true) => i16::MAX as i64,
227         (types::I32, true) => i32::MAX as i64,
228         (types::I64, true) => i64::MAX,
229         _ => unreachable!(),
230     };
231
232     let (min, max) = (bcx.ins().iconst(ty, min), bcx.ins().iconst(ty, max));
233
234     (min, max)
235 }
236
237 pub(crate) fn type_sign(ty: Ty<'_>) -> bool {
238     match ty.kind {
239         ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
240         ty::Int(..) => true,
241         ty::Float(..) => false, // `signed` is unused for floats
242         _ => panic!("{}", ty),
243     }
244 }
245
246 pub(crate) struct FunctionCx<'clif, 'tcx, B: Backend + 'static> {
247     // FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
248     pub(crate) tcx: TyCtxt<'tcx>,
249     pub(crate) module: &'clif mut Module<B>,
250     pub(crate) pointer_type: Type, // Cached from module
251
252     pub(crate) instance: Instance<'tcx>,
253     pub(crate) mir: &'tcx Body<'tcx>,
254
255     pub(crate) bcx: FunctionBuilder<'clif>,
256     pub(crate) block_map: IndexVec<BasicBlock, Block>,
257     pub(crate) local_map: FxHashMap<Local, CPlace<'tcx>>,
258
259     /// When `#[track_caller]` is used, the implicit caller location is stored in this variable.
260     pub(crate) caller_location: Option<CValue<'tcx>>,
261
262     /// See [crate::optimize::code_layout] for more information.
263     pub(crate) cold_blocks: EntitySet<Block>,
264
265     pub(crate) clif_comments: crate::pretty_clif::CommentWriter,
266     pub(crate) constants_cx: &'clif mut crate::constant::ConstantCx,
267     pub(crate) vtables: &'clif mut FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
268
269     pub(crate) source_info_set: indexmap::IndexSet<SourceInfo>,
270
271     /// This should only be accessed by `CPlace::new_var`.
272     pub(crate) next_ssa_var: u32,
273 }
274
275 impl<'tcx, B: Backend> LayoutOf for FunctionCx<'_, 'tcx, B> {
276     type Ty = Ty<'tcx>;
277     type TyAndLayout = TyAndLayout<'tcx>;
278
279     fn layout_of(&self, ty: Ty<'tcx>) -> TyAndLayout<'tcx> {
280         assert!(!ty.needs_subst());
281         self.tcx
282             .layout_of(ParamEnv::reveal_all().and(&ty))
283             .unwrap_or_else(|e| {
284                 if let layout::LayoutError::SizeOverflow(_) = e {
285                     self.tcx.sess.fatal(&e.to_string())
286                 } else {
287                     bug!("failed to get layout for `{}`: {}", ty, e)
288                 }
289             })
290     }
291 }
292
293 impl<'tcx, B: Backend + 'static> layout::HasTyCtxt<'tcx> for FunctionCx<'_, 'tcx, B> {
294     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
295         self.tcx
296     }
297 }
298
299 impl<'tcx, B: Backend + 'static> rustc_target::abi::HasDataLayout for FunctionCx<'_, 'tcx, B> {
300     fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
301         &self.tcx.data_layout
302     }
303 }
304
305 impl<'tcx, B: Backend + 'static> layout::HasParamEnv<'tcx> for FunctionCx<'_, 'tcx, B> {
306     fn param_env(&self) -> ParamEnv<'tcx> {
307         ParamEnv::reveal_all()
308     }
309 }
310
311 impl<'tcx, B: Backend + 'static> HasTargetSpec for FunctionCx<'_, 'tcx, B> {
312     fn target_spec(&self) -> &Target {
313         &self.tcx.sess.target.target
314     }
315 }
316
317 impl<'tcx, B: Backend + 'static> FunctionCx<'_, 'tcx, B> {
318     pub(crate) fn monomorphize<T>(&self, value: &T) -> T
319     where
320         T: TypeFoldable<'tcx> + Copy,
321     {
322         if let Some(substs) = self.instance.substs_for_mir_body() {
323             self.tcx.subst_and_normalize_erasing_regions(
324                 substs,
325                 ty::ParamEnv::reveal_all(),
326                 value,
327             )
328         } else {
329             self.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), *value)
330         }
331     }
332
333     pub(crate) fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
334         clif_type_from_ty(self.tcx, ty)
335     }
336
337     pub(crate) fn clif_pair_type(&self, ty: Ty<'tcx>) -> Option<(Type, Type)> {
338         clif_pair_type_from_ty(self.tcx, ty)
339     }
340
341     pub(crate) fn get_block(&self, bb: BasicBlock) -> Block {
342         *self.block_map.get(bb).unwrap()
343     }
344
345     pub(crate) fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
346         *self.local_map.get(&local).unwrap_or_else(|| {
347             panic!("Local {:?} doesn't exist", local);
348         })
349     }
350
351     pub(crate) fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
352         let (index, _) = self.source_info_set.insert_full(source_info);
353         self.bcx.set_srcloc(SourceLoc::new(index as u32));
354     }
355
356     pub(crate) fn get_caller_location(&mut self, span: Span) -> CValue<'tcx> {
357         if let Some(loc) = self.caller_location {
358             // `#[track_caller]` is used; return caller location instead of current location.
359             return loc;
360         }
361
362         let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
363         let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
364         let const_loc = self.tcx.const_caller_location((
365             rustc_span::symbol::Symbol::intern(&caller.file.name.to_string()),
366             caller.line as u32,
367             caller.col_display as u32 + 1,
368         ));
369         crate::constant::trans_const_value(
370             self,
371             ty::Const::from_value(self.tcx, const_loc, self.tcx.caller_location_ty()),
372         )
373     }
374
375     pub(crate) fn triple(&self) -> &target_lexicon::Triple {
376         self.module.isa().triple()
377     }
378
379     pub(crate) fn anonymous_str(&mut self, prefix: &str, msg: &str) -> Value {
380         use std::collections::hash_map::DefaultHasher;
381         use std::hash::{Hash, Hasher};
382
383         let mut hasher = DefaultHasher::new();
384         msg.hash(&mut hasher);
385         let msg_hash = hasher.finish();
386         let mut data_ctx = DataContext::new();
387         data_ctx.define(msg.as_bytes().to_vec().into_boxed_slice());
388         let msg_id = self
389             .module
390             .declare_data(
391                 &format!("__{}_{:08x}", prefix, msg_hash),
392                 Linkage::Local,
393                 false,
394                 false,
395                 None,
396             )
397             .unwrap();
398
399         // Ignore DuplicateDefinition error, as the data will be the same
400         let _ = self.module.define_data(msg_id, &data_ctx);
401
402         let local_msg_id = self.module.declare_data_in_func(msg_id, self.bcx.func);
403         #[cfg(debug_assertions)]
404         {
405             self.add_comment(local_msg_id, msg);
406         }
407         self.bcx.ins().global_value(self.pointer_type, local_msg_id)
408     }
409 }