]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/common.rs
Add tests for #41731
[rust.git] / compiler / rustc_codegen_cranelift / src / common.rs
1 use cranelift_codegen::isa::TargetFrontendConfig;
2 use gimli::write::FileId;
3
4 use rustc_data_structures::sync::Lrc;
5 use rustc_index::vec::IndexVec;
6 use rustc_middle::ty::layout::{
7     FnAbiError, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOfHelpers,
8 };
9 use rustc_span::SourceFile;
10 use rustc_target::abi::call::FnAbi;
11 use rustc_target::abi::{Integer, Primitive};
12 use rustc_target::spec::{HasTargetSpec, Target};
13
14 use crate::constant::ConstantCx;
15 use crate::debuginfo::FunctionDebugContext;
16 use crate::prelude::*;
17
18 pub(crate) fn pointer_ty(tcx: TyCtxt<'_>) -> types::Type {
19     match tcx.data_layout.pointer_size.bits() {
20         16 => types::I16,
21         32 => types::I32,
22         64 => types::I64,
23         bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits),
24     }
25 }
26
27 pub(crate) fn scalar_to_clif_type(tcx: TyCtxt<'_>, scalar: Scalar) -> Type {
28     match scalar.primitive() {
29         Primitive::Int(int, _sign) => match int {
30             Integer::I8 => types::I8,
31             Integer::I16 => types::I16,
32             Integer::I32 => types::I32,
33             Integer::I64 => types::I64,
34             Integer::I128 => types::I128,
35         },
36         Primitive::F32 => types::F32,
37         Primitive::F64 => types::F64,
38         Primitive::Pointer => pointer_ty(tcx),
39     }
40 }
41
42 fn clif_type_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<types::Type> {
43     Some(match ty.kind() {
44         ty::Bool => types::I8,
45         ty::Uint(size) => match size {
46             UintTy::U8 => types::I8,
47             UintTy::U16 => types::I16,
48             UintTy::U32 => types::I32,
49             UintTy::U64 => types::I64,
50             UintTy::U128 => types::I128,
51             UintTy::Usize => pointer_ty(tcx),
52         },
53         ty::Int(size) => match size {
54             IntTy::I8 => types::I8,
55             IntTy::I16 => types::I16,
56             IntTy::I32 => types::I32,
57             IntTy::I64 => types::I64,
58             IntTy::I128 => types::I128,
59             IntTy::Isize => pointer_ty(tcx),
60         },
61         ty::Char => types::I32,
62         ty::Float(size) => match size {
63             FloatTy::F32 => types::F32,
64             FloatTy::F64 => types::F64,
65         },
66         ty::FnPtr(_) => pointer_ty(tcx),
67         ty::RawPtr(TypeAndMut { ty: pointee_ty, mutbl: _ }) | ty::Ref(_, pointee_ty, _) => {
68             if has_ptr_meta(tcx, *pointee_ty) {
69                 return None;
70             } else {
71                 pointer_ty(tcx)
72             }
73         }
74         ty::Adt(adt_def, _) if adt_def.repr().simd() => {
75             let (element, count) = match &tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().abi
76             {
77                 Abi::Vector { element, count } => (element.clone(), *count),
78                 _ => unreachable!(),
79             };
80
81             match scalar_to_clif_type(tcx, element).by(u32::try_from(count).unwrap()) {
82                 // Cranelift currently only implements icmp for 128bit vectors.
83                 Some(vector_ty) if vector_ty.bits() == 128 => vector_ty,
84                 _ => return None,
85             }
86         }
87         ty::Param(_) => bug!("ty param {:?}", ty),
88         _ => return None,
89     })
90 }
91
92 fn clif_pair_type_from_ty<'tcx>(
93     tcx: TyCtxt<'tcx>,
94     ty: Ty<'tcx>,
95 ) -> Option<(types::Type, types::Type)> {
96     Some(match ty.kind() {
97         ty::Tuple(types) if types.len() == 2 => {
98             let a = clif_type_from_ty(tcx, types[0])?;
99             let b = clif_type_from_ty(tcx, types[1])?;
100             if a.is_vector() || b.is_vector() {
101                 return None;
102             }
103             (a, b)
104         }
105         ty::RawPtr(TypeAndMut { ty: pointee_ty, mutbl: _ }) | ty::Ref(_, pointee_ty, _) => {
106             if has_ptr_meta(tcx, *pointee_ty) {
107                 (pointer_ty(tcx), pointer_ty(tcx))
108             } else {
109                 return None;
110             }
111         }
112         _ => return None,
113     })
114 }
115
116 /// Is a pointer to this type a fat ptr?
117 pub(crate) fn has_ptr_meta<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
118     let ptr_ty = tcx.mk_ptr(TypeAndMut { ty, mutbl: rustc_hir::Mutability::Not });
119     match &tcx.layout_of(ParamEnv::reveal_all().and(ptr_ty)).unwrap().abi {
120         Abi::Scalar(_) => false,
121         Abi::ScalarPair(_, _) => true,
122         abi => unreachable!("Abi of ptr to {:?} is {:?}???", ty, abi),
123     }
124 }
125
126 pub(crate) fn codegen_icmp_imm(
127     fx: &mut FunctionCx<'_, '_, '_>,
128     intcc: IntCC,
129     lhs: Value,
130     rhs: i128,
131 ) -> Value {
132     let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
133     if lhs_ty == types::I128 {
134         // FIXME legalize `icmp_imm.i128` in Cranelift
135
136         let (lhs_lsb, lhs_msb) = fx.bcx.ins().isplit(lhs);
137         let (rhs_lsb, rhs_msb) = (rhs as u128 as u64 as i64, (rhs as u128 >> 64) as u64 as i64);
138
139         match intcc {
140             IntCC::Equal => {
141                 let lsb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_lsb, rhs_lsb);
142                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
143                 fx.bcx.ins().band(lsb_eq, msb_eq)
144             }
145             IntCC::NotEqual => {
146                 let lsb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_lsb, rhs_lsb);
147                 let msb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_msb, rhs_msb);
148                 fx.bcx.ins().bor(lsb_ne, msb_ne)
149             }
150             _ => {
151                 // if msb_eq {
152                 //     lsb_cc
153                 // } else {
154                 //     msb_cc
155                 // }
156
157                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
158                 let lsb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_lsb, rhs_lsb);
159                 let msb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_msb, rhs_msb);
160
161                 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
162             }
163         }
164     } else {
165         let rhs = i64::try_from(rhs).expect("codegen_icmp_imm rhs out of range for <128bit int");
166         fx.bcx.ins().icmp_imm(intcc, lhs, rhs)
167     }
168 }
169
170 pub(crate) fn type_min_max_value(
171     bcx: &mut FunctionBuilder<'_>,
172     ty: Type,
173     signed: bool,
174 ) -> (Value, Value) {
175     assert!(ty.is_int());
176
177     if ty == types::I128 {
178         if signed {
179             let min = i128::MIN as u128;
180             let min_lsb = bcx.ins().iconst(types::I64, min as u64 as i64);
181             let min_msb = bcx.ins().iconst(types::I64, (min >> 64) as u64 as i64);
182             let min = bcx.ins().iconcat(min_lsb, min_msb);
183
184             let max = i128::MAX as u128;
185             let max_lsb = bcx.ins().iconst(types::I64, max as u64 as i64);
186             let max_msb = bcx.ins().iconst(types::I64, (max >> 64) as u64 as i64);
187             let max = bcx.ins().iconcat(max_lsb, max_msb);
188
189             return (min, max);
190         } else {
191             let min_half = bcx.ins().iconst(types::I64, 0);
192             let min = bcx.ins().iconcat(min_half, min_half);
193
194             let max_half = bcx.ins().iconst(types::I64, u64::MAX as i64);
195             let max = bcx.ins().iconcat(max_half, max_half);
196
197             return (min, max);
198         }
199     }
200
201     let min = match (ty, signed) {
202         (types::I8, false) | (types::I16, false) | (types::I32, false) | (types::I64, false) => {
203             0i64
204         }
205         (types::I8, true) => i64::from(i8::MIN),
206         (types::I16, true) => i64::from(i16::MIN),
207         (types::I32, true) => i64::from(i32::MIN),
208         (types::I64, true) => i64::MIN,
209         _ => unreachable!(),
210     };
211
212     let max = match (ty, signed) {
213         (types::I8, false) => i64::from(u8::MAX),
214         (types::I16, false) => i64::from(u16::MAX),
215         (types::I32, false) => i64::from(u32::MAX),
216         (types::I64, false) => u64::MAX as i64,
217         (types::I8, true) => i64::from(i8::MAX),
218         (types::I16, true) => i64::from(i16::MAX),
219         (types::I32, true) => i64::from(i32::MAX),
220         (types::I64, true) => i64::MAX,
221         _ => unreachable!(),
222     };
223
224     let (min, max) = (bcx.ins().iconst(ty, min), bcx.ins().iconst(ty, max));
225
226     (min, max)
227 }
228
229 pub(crate) fn type_sign(ty: Ty<'_>) -> bool {
230     match ty.kind() {
231         ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
232         ty::Int(..) => true,
233         ty::Float(..) => false, // `signed` is unused for floats
234         _ => panic!("{}", ty),
235     }
236 }
237
238 pub(crate) struct FunctionCx<'m, 'clif, 'tcx: 'm> {
239     pub(crate) cx: &'clif mut crate::CodegenCx,
240     pub(crate) module: &'m mut dyn Module,
241     pub(crate) tcx: TyCtxt<'tcx>,
242     pub(crate) target_config: TargetFrontendConfig, // Cached from module
243     pub(crate) pointer_type: Type,                  // Cached from module
244     pub(crate) constants_cx: ConstantCx,
245     pub(crate) func_debug_cx: Option<FunctionDebugContext>,
246
247     pub(crate) instance: Instance<'tcx>,
248     pub(crate) symbol_name: String,
249     pub(crate) mir: &'tcx Body<'tcx>,
250     pub(crate) fn_abi: Option<&'tcx FnAbi<'tcx, Ty<'tcx>>>,
251
252     pub(crate) bcx: FunctionBuilder<'clif>,
253     pub(crate) block_map: IndexVec<BasicBlock, Block>,
254     pub(crate) local_map: IndexVec<Local, CPlace<'tcx>>,
255
256     /// When `#[track_caller]` is used, the implicit caller location is stored in this variable.
257     pub(crate) caller_location: Option<CValue<'tcx>>,
258
259     pub(crate) clif_comments: crate::pretty_clif::CommentWriter,
260
261     /// Last accessed source file and it's debuginfo file id.
262     ///
263     /// For optimization purposes only
264     pub(crate) last_source_file: Option<(Lrc<SourceFile>, FileId)>,
265
266     /// This should only be accessed by `CPlace::new_var`.
267     pub(crate) next_ssa_var: u32,
268 }
269
270 impl<'tcx> LayoutOfHelpers<'tcx> for FunctionCx<'_, '_, 'tcx> {
271     type LayoutOfResult = TyAndLayout<'tcx>;
272
273     #[inline]
274     fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
275         RevealAllLayoutCx(self.tcx).handle_layout_err(err, span, ty)
276     }
277 }
278
279 impl<'tcx> FnAbiOfHelpers<'tcx> for FunctionCx<'_, '_, 'tcx> {
280     type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
281
282     #[inline]
283     fn handle_fn_abi_err(
284         &self,
285         err: FnAbiError<'tcx>,
286         span: Span,
287         fn_abi_request: FnAbiRequest<'tcx>,
288     ) -> ! {
289         RevealAllLayoutCx(self.tcx).handle_fn_abi_err(err, span, fn_abi_request)
290     }
291 }
292
293 impl<'tcx> layout::HasTyCtxt<'tcx> for FunctionCx<'_, '_, 'tcx> {
294     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
295         self.tcx
296     }
297 }
298
299 impl<'tcx> rustc_target::abi::HasDataLayout for FunctionCx<'_, '_, 'tcx> {
300     fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
301         &self.tcx.data_layout
302     }
303 }
304
305 impl<'tcx> layout::HasParamEnv<'tcx> for FunctionCx<'_, '_, 'tcx> {
306     fn param_env(&self) -> ParamEnv<'tcx> {
307         ParamEnv::reveal_all()
308     }
309 }
310
311 impl<'tcx> HasTargetSpec for FunctionCx<'_, '_, 'tcx> {
312     fn target_spec(&self) -> &Target {
313         &self.tcx.sess.target
314     }
315 }
316
317 impl<'tcx> FunctionCx<'_, '_, 'tcx> {
318     pub(crate) fn monomorphize<T>(&self, value: T) -> T
319     where
320         T: TypeFoldable<'tcx> + Copy,
321     {
322         self.instance.subst_mir_and_normalize_erasing_regions(
323             self.tcx,
324             ty::ParamEnv::reveal_all(),
325             value,
326         )
327     }
328
329     pub(crate) fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
330         clif_type_from_ty(self.tcx, ty)
331     }
332
333     pub(crate) fn clif_pair_type(&self, ty: Ty<'tcx>) -> Option<(Type, Type)> {
334         clif_pair_type_from_ty(self.tcx, ty)
335     }
336
337     pub(crate) fn get_block(&self, bb: BasicBlock) -> Block {
338         *self.block_map.get(bb).unwrap()
339     }
340
341     pub(crate) fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
342         *self.local_map.get(local).unwrap_or_else(|| {
343             panic!("Local {:?} doesn't exist", local);
344         })
345     }
346
347     pub(crate) fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
348         if let Some(debug_context) = &mut self.cx.debug_context {
349             let (file, line, column) =
350                 DebugContext::get_span_loc(self.tcx, self.mir.span, source_info.span);
351
352             // add_source_file is very slow.
353             // Optimize for the common case of the current file not being changed.
354             let mut cached_file_id = None;
355             if let Some((ref last_source_file, last_file_id)) = self.last_source_file {
356                 // If the allocations are not equal, the files may still be equal, but that
357                 // doesn't matter, as this is just an optimization.
358                 if rustc_data_structures::sync::Lrc::ptr_eq(last_source_file, &file) {
359                     cached_file_id = Some(last_file_id);
360                 }
361             }
362
363             let file_id = if let Some(file_id) = cached_file_id {
364                 file_id
365             } else {
366                 debug_context.add_source_file(&file)
367             };
368
369             let source_loc =
370                 self.func_debug_cx.as_mut().unwrap().add_dbg_loc(file_id, line, column);
371             self.bcx.set_srcloc(source_loc);
372         }
373     }
374
375     // Note: must be kept in sync with get_caller_location from cg_ssa
376     pub(crate) fn get_caller_location(&mut self, mut source_info: mir::SourceInfo) -> CValue<'tcx> {
377         let span_to_caller_location = |fx: &mut FunctionCx<'_, '_, 'tcx>, span: Span| {
378             let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
379             let caller = fx.tcx.sess.source_map().lookup_char_pos(topmost.lo());
380             let const_loc = fx.tcx.const_caller_location((
381                 rustc_span::symbol::Symbol::intern(
382                     &caller.file.name.prefer_remapped().to_string_lossy(),
383                 ),
384                 caller.line as u32,
385                 caller.col_display as u32 + 1,
386             ));
387             crate::constant::codegen_const_value(fx, const_loc, fx.tcx.caller_location_ty())
388         };
389
390         // Walk up the `SourceScope`s, in case some of them are from MIR inlining.
391         // If so, the starting `source_info.span` is in the innermost inlined
392         // function, and will be replaced with outer callsite spans as long
393         // as the inlined functions were `#[track_caller]`.
394         loop {
395             let scope_data = &self.mir.source_scopes[source_info.scope];
396
397             if let Some((callee, callsite_span)) = scope_data.inlined {
398                 // Stop inside the most nested non-`#[track_caller]` function,
399                 // before ever reaching its caller (which is irrelevant).
400                 if !callee.def.requires_caller_location(self.tcx) {
401                     return span_to_caller_location(self, source_info.span);
402                 }
403                 source_info.span = callsite_span;
404             }
405
406             // Skip past all of the parents with `inlined: None`.
407             match scope_data.inlined_parent_scope {
408                 Some(parent) => source_info.scope = parent,
409                 None => break,
410             }
411         }
412
413         // No inlined `SourceScope`s, or all of them were `#[track_caller]`.
414         self.caller_location.unwrap_or_else(|| span_to_caller_location(self, source_info.span))
415     }
416
417     pub(crate) fn anonymous_str(&mut self, msg: &str) -> Value {
418         let mut data_ctx = DataContext::new();
419         data_ctx.define(msg.as_bytes().to_vec().into_boxed_slice());
420         let msg_id = self.module.declare_anonymous_data(false, false).unwrap();
421
422         // Ignore DuplicateDefinition error, as the data will be the same
423         let _ = self.module.define_data(msg_id, &data_ctx);
424
425         let local_msg_id = self.module.declare_data_in_func(msg_id, self.bcx.func);
426         if self.clif_comments.enabled() {
427             self.add_comment(local_msg_id, msg);
428         }
429         self.bcx.ins().global_value(self.pointer_type, local_msg_id)
430     }
431 }
432
433 pub(crate) struct RevealAllLayoutCx<'tcx>(pub(crate) TyCtxt<'tcx>);
434
435 impl<'tcx> LayoutOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
436     type LayoutOfResult = TyAndLayout<'tcx>;
437
438     #[inline]
439     fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
440         if let layout::LayoutError::SizeOverflow(_) = err {
441             self.0.sess.span_fatal(span, &err.to_string())
442         } else {
443             span_bug!(span, "failed to get layout for `{}`: {}", ty, err)
444         }
445     }
446 }
447
448 impl<'tcx> FnAbiOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
449     type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
450
451     #[inline]
452     fn handle_fn_abi_err(
453         &self,
454         err: FnAbiError<'tcx>,
455         span: Span,
456         fn_abi_request: FnAbiRequest<'tcx>,
457     ) -> ! {
458         if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
459             self.0.sess.span_fatal(span, &err.to_string())
460         } else {
461             match fn_abi_request {
462                 FnAbiRequest::OfFnPtr { sig, extra_args } => {
463                     span_bug!(
464                         span,
465                         "`fn_abi_of_fn_ptr({}, {:?})` failed: {}",
466                         sig,
467                         extra_args,
468                         err
469                     );
470                 }
471                 FnAbiRequest::OfInstance { instance, extra_args } => {
472                     span_bug!(
473                         span,
474                         "`fn_abi_of_instance({}, {:?})` failed: {}",
475                         instance,
476                         extra_args,
477                         err
478                     );
479                 }
480             }
481         }
482     }
483 }
484
485 impl<'tcx> layout::HasTyCtxt<'tcx> for RevealAllLayoutCx<'tcx> {
486     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
487         self.0
488     }
489 }
490
491 impl<'tcx> rustc_target::abi::HasDataLayout for RevealAllLayoutCx<'tcx> {
492     fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
493         &self.0.data_layout
494     }
495 }
496
497 impl<'tcx> layout::HasParamEnv<'tcx> for RevealAllLayoutCx<'tcx> {
498     fn param_env(&self) -> ParamEnv<'tcx> {
499         ParamEnv::reveal_all()
500     }
501 }
502
503 impl<'tcx> HasTargetSpec for RevealAllLayoutCx<'tcx> {
504     fn target_spec(&self) -> &Target {
505         &self.0.sess.target
506     }
507 }