1 use cranelift_codegen::isa::TargetFrontendConfig;
2 use gimli::write::FileId;
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,
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};
14 use crate::constant::ConstantCx;
15 use crate::debuginfo::FunctionDebugContext;
16 use crate::prelude::*;
18 pub(crate) fn pointer_ty(tcx: TyCtxt<'_>) -> types::Type {
19 match tcx.data_layout.pointer_size.bits() {
23 bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits),
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,
36 Primitive::F32 => types::F32,
37 Primitive::F64 => types::F64,
38 Primitive::Pointer => pointer_ty(tcx),
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),
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),
61 ty::Char => types::I32,
62 ty::Float(size) => match size {
63 FloatTy::F32 => types::F32,
64 FloatTy::F64 => types::F64,
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) {
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
77 Abi::Vector { element, count } => (element.clone(), *count),
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,
87 ty::Param(_) => bug!("ty param {:?}", ty),
92 fn clif_pair_type_from_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() {
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))
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),
126 pub(crate) fn codegen_icmp_imm(
127 fx: &mut FunctionCx<'_, '_, '_>,
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
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);
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)
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)
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);
161 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
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)
170 pub(crate) fn type_min_max_value(
171 bcx: &mut FunctionBuilder<'_>,
174 ) -> (Value, Value) {
175 assert!(ty.is_int());
177 if ty == types::I128 {
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);
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);
191 let min_half = bcx.ins().iconst(types::I64, 0);
192 let min = bcx.ins().iconcat(min_half, min_half);
194 let max_half = bcx.ins().iconst(types::I64, u64::MAX as i64);
195 let max = bcx.ins().iconcat(max_half, max_half);
201 let min = match (ty, signed) {
202 (types::I8, false) | (types::I16, false) | (types::I32, false) | (types::I64, false) => {
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,
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,
224 let (min, max) = (bcx.ins().iconst(ty, min), bcx.ins().iconst(ty, max));
229 pub(crate) fn type_sign(ty: Ty<'_>) -> bool {
231 ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
233 ty::Float(..) => false, // `signed` is unused for floats
234 _ => panic!("{}", ty),
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>,
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>>>,
252 pub(crate) bcx: FunctionBuilder<'clif>,
253 pub(crate) block_map: IndexVec<BasicBlock, Block>,
254 pub(crate) local_map: IndexVec<Local, CPlace<'tcx>>,
256 /// When `#[track_caller]` is used, the implicit caller location is stored in this variable.
257 pub(crate) caller_location: Option<CValue<'tcx>>,
259 pub(crate) clif_comments: crate::pretty_clif::CommentWriter,
261 /// Last accessed source file and it's debuginfo file id.
263 /// For optimization purposes only
264 pub(crate) last_source_file: Option<(Lrc<SourceFile>, FileId)>,
266 /// This should only be accessed by `CPlace::new_var`.
267 pub(crate) next_ssa_var: u32,
270 impl<'tcx> LayoutOfHelpers<'tcx> for FunctionCx<'_, '_, 'tcx> {
271 type LayoutOfResult = TyAndLayout<'tcx>;
274 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
275 RevealAllLayoutCx(self.tcx).handle_layout_err(err, span, ty)
279 impl<'tcx> FnAbiOfHelpers<'tcx> for FunctionCx<'_, '_, 'tcx> {
280 type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
283 fn handle_fn_abi_err(
285 err: FnAbiError<'tcx>,
287 fn_abi_request: FnAbiRequest<'tcx>,
289 RevealAllLayoutCx(self.tcx).handle_fn_abi_err(err, span, fn_abi_request)
293 impl<'tcx> layout::HasTyCtxt<'tcx> for FunctionCx<'_, '_, 'tcx> {
294 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
299 impl<'tcx> rustc_target::abi::HasDataLayout for FunctionCx<'_, '_, 'tcx> {
300 fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
301 &self.tcx.data_layout
305 impl<'tcx> layout::HasParamEnv<'tcx> for FunctionCx<'_, '_, 'tcx> {
306 fn param_env(&self) -> ParamEnv<'tcx> {
307 ParamEnv::reveal_all()
311 impl<'tcx> HasTargetSpec for FunctionCx<'_, '_, 'tcx> {
312 fn target_spec(&self) -> &Target {
313 &self.tcx.sess.target
317 impl<'tcx> FunctionCx<'_, '_, 'tcx> {
318 pub(crate) fn monomorphize<T>(&self, value: T) -> T
320 T: TypeFoldable<'tcx> + Copy,
322 self.instance.subst_mir_and_normalize_erasing_regions(
324 ty::ParamEnv::reveal_all(),
329 pub(crate) fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
330 clif_type_from_ty(self.tcx, ty)
333 pub(crate) fn clif_pair_type(&self, ty: Ty<'tcx>) -> Option<(Type, Type)> {
334 clif_pair_type_from_ty(self.tcx, ty)
337 pub(crate) fn get_block(&self, bb: BasicBlock) -> Block {
338 *self.block_map.get(bb).unwrap()
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);
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);
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);
363 let file_id = if let Some(file_id) = cached_file_id {
366 debug_context.add_source_file(&file)
370 self.func_debug_cx.as_mut().unwrap().add_dbg_loc(file_id, line, column);
371 self.bcx.set_srcloc(source_loc);
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(),
385 caller.col_display as u32 + 1,
387 crate::constant::codegen_const_value(fx, const_loc, fx.tcx.caller_location_ty())
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]`.
395 let scope_data = &self.mir.source_scopes[source_info.scope];
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);
403 source_info.span = callsite_span;
406 // Skip past all of the parents with `inlined: None`.
407 match scope_data.inlined_parent_scope {
408 Some(parent) => source_info.scope = parent,
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))
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();
422 // Ignore DuplicateDefinition error, as the data will be the same
423 let _ = self.module.define_data(msg_id, &data_ctx);
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);
429 self.bcx.ins().global_value(self.pointer_type, local_msg_id)
433 pub(crate) struct RevealAllLayoutCx<'tcx>(pub(crate) TyCtxt<'tcx>);
435 impl<'tcx> LayoutOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
436 type LayoutOfResult = TyAndLayout<'tcx>;
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())
443 span_bug!(span, "failed to get layout for `{}`: {}", ty, err)
448 impl<'tcx> FnAbiOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
449 type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
452 fn handle_fn_abi_err(
454 err: FnAbiError<'tcx>,
456 fn_abi_request: FnAbiRequest<'tcx>,
458 if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
459 self.0.sess.span_fatal(span, &err.to_string())
461 match fn_abi_request {
462 FnAbiRequest::OfFnPtr { sig, extra_args } => {
465 "`fn_abi_of_fn_ptr({}, {:?})` failed: {}",
471 FnAbiRequest::OfInstance { instance, extra_args } => {
474 "`fn_abi_of_instance({}, {:?})` failed: {}",
485 impl<'tcx> layout::HasTyCtxt<'tcx> for RevealAllLayoutCx<'tcx> {
486 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
491 impl<'tcx> rustc_target::abi::HasDataLayout for RevealAllLayoutCx<'tcx> {
492 fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
497 impl<'tcx> layout::HasParamEnv<'tcx> for RevealAllLayoutCx<'tcx> {
498 fn param_env(&self) -> ParamEnv<'tcx> {
499 ParamEnv::reveal_all()
503 impl<'tcx> HasTargetSpec for RevealAllLayoutCx<'tcx> {
504 fn target_spec(&self) -> &Target {