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