]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/common.rs
Rollup merge of #105661 - lcnr:evaluate-new, r=compiler-errors
[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 = rhs as i64; // Truncates on purpose in case rhs is actually an unsigned value
166         fx.bcx.ins().icmp_imm(intcc, lhs, rhs)
167     }
168 }
169
170 pub(crate) fn type_zero_value(bcx: &mut FunctionBuilder<'_>, ty: Type) -> Value {
171     if ty == types::I128 {
172         let zero = bcx.ins().iconst(types::I64, 0);
173         bcx.ins().iconcat(zero, zero)
174     } else {
175         bcx.ins().iconst(ty, 0)
176     }
177 }
178
179 pub(crate) fn type_min_max_value(
180     bcx: &mut FunctionBuilder<'_>,
181     ty: Type,
182     signed: bool,
183 ) -> (Value, Value) {
184     assert!(ty.is_int());
185
186     if ty == types::I128 {
187         if signed {
188             let min = i128::MIN as u128;
189             let min_lsb = bcx.ins().iconst(types::I64, min as u64 as i64);
190             let min_msb = bcx.ins().iconst(types::I64, (min >> 64) as u64 as i64);
191             let min = bcx.ins().iconcat(min_lsb, min_msb);
192
193             let max = i128::MAX as u128;
194             let max_lsb = bcx.ins().iconst(types::I64, max as u64 as i64);
195             let max_msb = bcx.ins().iconst(types::I64, (max >> 64) as u64 as i64);
196             let max = bcx.ins().iconcat(max_lsb, max_msb);
197
198             return (min, max);
199         } else {
200             let min_half = bcx.ins().iconst(types::I64, 0);
201             let min = bcx.ins().iconcat(min_half, min_half);
202
203             let max_half = bcx.ins().iconst(types::I64, u64::MAX as i64);
204             let max = bcx.ins().iconcat(max_half, max_half);
205
206             return (min, max);
207         }
208     }
209
210     let min = match (ty, signed) {
211         (types::I8, false) | (types::I16, false) | (types::I32, false) | (types::I64, false) => {
212             0i64
213         }
214         (types::I8, true) => i64::from(i8::MIN),
215         (types::I16, true) => i64::from(i16::MIN),
216         (types::I32, true) => i64::from(i32::MIN),
217         (types::I64, true) => i64::MIN,
218         _ => unreachable!(),
219     };
220
221     let max = match (ty, signed) {
222         (types::I8, false) => i64::from(u8::MAX),
223         (types::I16, false) => i64::from(u16::MAX),
224         (types::I32, false) => i64::from(u32::MAX),
225         (types::I64, false) => u64::MAX as i64,
226         (types::I8, true) => i64::from(i8::MAX),
227         (types::I16, true) => i64::from(i16::MAX),
228         (types::I32, true) => i64::from(i32::MAX),
229         (types::I64, true) => i64::MAX,
230         _ => unreachable!(),
231     };
232
233     let (min, max) = (bcx.ins().iconst(ty, min), bcx.ins().iconst(ty, max));
234
235     (min, max)
236 }
237
238 pub(crate) fn type_sign(ty: Ty<'_>) -> bool {
239     match ty.kind() {
240         ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
241         ty::Int(..) => true,
242         ty::Float(..) => false, // `signed` is unused for floats
243         _ => panic!("{}", ty),
244     }
245 }
246
247 pub(crate) struct FunctionCx<'m, 'clif, 'tcx: 'm> {
248     pub(crate) cx: &'clif mut crate::CodegenCx,
249     pub(crate) module: &'m mut dyn Module,
250     pub(crate) tcx: TyCtxt<'tcx>,
251     pub(crate) target_config: TargetFrontendConfig, // Cached from module
252     pub(crate) pointer_type: Type,                  // Cached from module
253     pub(crate) constants_cx: ConstantCx,
254     pub(crate) func_debug_cx: Option<FunctionDebugContext>,
255
256     pub(crate) instance: Instance<'tcx>,
257     pub(crate) symbol_name: String,
258     pub(crate) mir: &'tcx Body<'tcx>,
259     pub(crate) fn_abi: Option<&'tcx FnAbi<'tcx, Ty<'tcx>>>,
260
261     pub(crate) bcx: FunctionBuilder<'clif>,
262     pub(crate) block_map: IndexVec<BasicBlock, Block>,
263     pub(crate) local_map: IndexVec<Local, CPlace<'tcx>>,
264
265     /// When `#[track_caller]` is used, the implicit caller location is stored in this variable.
266     pub(crate) caller_location: Option<CValue<'tcx>>,
267
268     pub(crate) clif_comments: crate::pretty_clif::CommentWriter,
269
270     /// Last accessed source file and it's debuginfo file id.
271     ///
272     /// For optimization purposes only
273     pub(crate) last_source_file: Option<(Lrc<SourceFile>, FileId)>,
274
275     /// This should only be accessed by `CPlace::new_var`.
276     pub(crate) next_ssa_var: u32,
277 }
278
279 impl<'tcx> LayoutOfHelpers<'tcx> for FunctionCx<'_, '_, 'tcx> {
280     type LayoutOfResult = TyAndLayout<'tcx>;
281
282     #[inline]
283     fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
284         RevealAllLayoutCx(self.tcx).handle_layout_err(err, span, ty)
285     }
286 }
287
288 impl<'tcx> FnAbiOfHelpers<'tcx> for FunctionCx<'_, '_, 'tcx> {
289     type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
290
291     #[inline]
292     fn handle_fn_abi_err(
293         &self,
294         err: FnAbiError<'tcx>,
295         span: Span,
296         fn_abi_request: FnAbiRequest<'tcx>,
297     ) -> ! {
298         RevealAllLayoutCx(self.tcx).handle_fn_abi_err(err, span, fn_abi_request)
299     }
300 }
301
302 impl<'tcx> layout::HasTyCtxt<'tcx> for FunctionCx<'_, '_, 'tcx> {
303     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
304         self.tcx
305     }
306 }
307
308 impl<'tcx> rustc_target::abi::HasDataLayout for FunctionCx<'_, '_, 'tcx> {
309     fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
310         &self.tcx.data_layout
311     }
312 }
313
314 impl<'tcx> layout::HasParamEnv<'tcx> for FunctionCx<'_, '_, 'tcx> {
315     fn param_env(&self) -> ParamEnv<'tcx> {
316         ParamEnv::reveal_all()
317     }
318 }
319
320 impl<'tcx> HasTargetSpec for FunctionCx<'_, '_, 'tcx> {
321     fn target_spec(&self) -> &Target {
322         &self.tcx.sess.target
323     }
324 }
325
326 impl<'tcx> FunctionCx<'_, '_, 'tcx> {
327     pub(crate) fn monomorphize<T>(&self, value: T) -> T
328     where
329         T: TypeFoldable<'tcx> + Copy,
330     {
331         self.instance.subst_mir_and_normalize_erasing_regions(
332             self.tcx,
333             ty::ParamEnv::reveal_all(),
334             value,
335         )
336     }
337
338     pub(crate) fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
339         clif_type_from_ty(self.tcx, ty)
340     }
341
342     pub(crate) fn clif_pair_type(&self, ty: Ty<'tcx>) -> Option<(Type, Type)> {
343         clif_pair_type_from_ty(self.tcx, ty)
344     }
345
346     pub(crate) fn get_block(&self, bb: BasicBlock) -> Block {
347         *self.block_map.get(bb).unwrap()
348     }
349
350     pub(crate) fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
351         *self.local_map.get(local).unwrap_or_else(|| {
352             panic!("Local {:?} doesn't exist", local);
353         })
354     }
355
356     pub(crate) fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
357         if let Some(debug_context) = &mut self.cx.debug_context {
358             let (file, line, column) =
359                 DebugContext::get_span_loc(self.tcx, self.mir.span, source_info.span);
360
361             // add_source_file is very slow.
362             // Optimize for the common case of the current file not being changed.
363             let mut cached_file_id = None;
364             if let Some((ref last_source_file, last_file_id)) = self.last_source_file {
365                 // If the allocations are not equal, the files may still be equal, but that
366                 // doesn't matter, as this is just an optimization.
367                 if rustc_data_structures::sync::Lrc::ptr_eq(last_source_file, &file) {
368                     cached_file_id = Some(last_file_id);
369                 }
370             }
371
372             let file_id = if let Some(file_id) = cached_file_id {
373                 file_id
374             } else {
375                 debug_context.add_source_file(&file)
376             };
377
378             let source_loc =
379                 self.func_debug_cx.as_mut().unwrap().add_dbg_loc(file_id, line, column);
380             self.bcx.set_srcloc(source_loc);
381         }
382     }
383
384     // Note: must be kept in sync with get_caller_location from cg_ssa
385     pub(crate) fn get_caller_location(&mut self, mut source_info: mir::SourceInfo) -> CValue<'tcx> {
386         let span_to_caller_location = |fx: &mut FunctionCx<'_, '_, 'tcx>, span: Span| {
387             let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
388             let caller = fx.tcx.sess.source_map().lookup_char_pos(topmost.lo());
389             let const_loc = fx.tcx.const_caller_location((
390                 rustc_span::symbol::Symbol::intern(
391                     &caller.file.name.prefer_remapped().to_string_lossy(),
392                 ),
393                 caller.line as u32,
394                 caller.col_display as u32 + 1,
395             ));
396             crate::constant::codegen_const_value(fx, const_loc, fx.tcx.caller_location_ty())
397         };
398
399         // Walk up the `SourceScope`s, in case some of them are from MIR inlining.
400         // If so, the starting `source_info.span` is in the innermost inlined
401         // function, and will be replaced with outer callsite spans as long
402         // as the inlined functions were `#[track_caller]`.
403         loop {
404             let scope_data = &self.mir.source_scopes[source_info.scope];
405
406             if let Some((callee, callsite_span)) = scope_data.inlined {
407                 // Stop inside the most nested non-`#[track_caller]` function,
408                 // before ever reaching its caller (which is irrelevant).
409                 if !callee.def.requires_caller_location(self.tcx) {
410                     return span_to_caller_location(self, source_info.span);
411                 }
412                 source_info.span = callsite_span;
413             }
414
415             // Skip past all of the parents with `inlined: None`.
416             match scope_data.inlined_parent_scope {
417                 Some(parent) => source_info.scope = parent,
418                 None => break,
419             }
420         }
421
422         // No inlined `SourceScope`s, or all of them were `#[track_caller]`.
423         self.caller_location.unwrap_or_else(|| span_to_caller_location(self, source_info.span))
424     }
425
426     pub(crate) fn anonymous_str(&mut self, msg: &str) -> Value {
427         let mut data_ctx = DataContext::new();
428         data_ctx.define(msg.as_bytes().to_vec().into_boxed_slice());
429         let msg_id = self.module.declare_anonymous_data(false, false).unwrap();
430
431         // Ignore DuplicateDefinition error, as the data will be the same
432         let _ = self.module.define_data(msg_id, &data_ctx);
433
434         let local_msg_id = self.module.declare_data_in_func(msg_id, self.bcx.func);
435         if self.clif_comments.enabled() {
436             self.add_comment(local_msg_id, msg);
437         }
438         self.bcx.ins().global_value(self.pointer_type, local_msg_id)
439     }
440 }
441
442 pub(crate) struct RevealAllLayoutCx<'tcx>(pub(crate) TyCtxt<'tcx>);
443
444 impl<'tcx> LayoutOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
445     type LayoutOfResult = TyAndLayout<'tcx>;
446
447     #[inline]
448     fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
449         if let layout::LayoutError::SizeOverflow(_) = err {
450             self.0.sess.span_fatal(span, &err.to_string())
451         } else {
452             span_bug!(span, "failed to get layout for `{}`: {}", ty, err)
453         }
454     }
455 }
456
457 impl<'tcx> FnAbiOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
458     type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
459
460     #[inline]
461     fn handle_fn_abi_err(
462         &self,
463         err: FnAbiError<'tcx>,
464         span: Span,
465         fn_abi_request: FnAbiRequest<'tcx>,
466     ) -> ! {
467         if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
468             self.0.sess.span_fatal(span, &err.to_string())
469         } else {
470             match fn_abi_request {
471                 FnAbiRequest::OfFnPtr { sig, extra_args } => {
472                     span_bug!(
473                         span,
474                         "`fn_abi_of_fn_ptr({}, {:?})` failed: {}",
475                         sig,
476                         extra_args,
477                         err
478                     );
479                 }
480                 FnAbiRequest::OfInstance { instance, extra_args } => {
481                     span_bug!(
482                         span,
483                         "`fn_abi_of_instance({}, {:?})` failed: {}",
484                         instance,
485                         extra_args,
486                         err
487                     );
488                 }
489             }
490         }
491     }
492 }
493
494 impl<'tcx> layout::HasTyCtxt<'tcx> for RevealAllLayoutCx<'tcx> {
495     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
496         self.0
497     }
498 }
499
500 impl<'tcx> rustc_target::abi::HasDataLayout for RevealAllLayoutCx<'tcx> {
501     fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
502         &self.0.data_layout
503     }
504 }
505
506 impl<'tcx> layout::HasParamEnv<'tcx> for RevealAllLayoutCx<'tcx> {
507     fn param_env(&self) -> ParamEnv<'tcx> {
508         ParamEnv::reveal_all()
509     }
510 }
511
512 impl<'tcx> HasTargetSpec for RevealAllLayoutCx<'tcx> {
513     fn target_spec(&self) -> &Target {
514         &self.0.sess.target
515     }
516 }