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