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