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 = rhs as i64; // Truncates on purpose in case rhs is actually an unsigned value
166 fx.bcx.ins().icmp_imm(intcc, lhs, rhs)
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)
175 bcx.ins().iconst(ty, 0)
179 pub(crate) fn type_min_max_value(
180 bcx: &mut FunctionBuilder<'_>,
183 ) -> (Value, Value) {
184 assert!(ty.is_int());
186 if ty == types::I128 {
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);
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);
200 let min_half = bcx.ins().iconst(types::I64, 0);
201 let min = bcx.ins().iconcat(min_half, min_half);
203 let max_half = bcx.ins().iconst(types::I64, u64::MAX as i64);
204 let max = bcx.ins().iconcat(max_half, max_half);
210 let min = match (ty, signed) {
211 (types::I8, false) | (types::I16, false) | (types::I32, false) | (types::I64, false) => {
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,
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,
233 let (min, max) = (bcx.ins().iconst(ty, min), bcx.ins().iconst(ty, max));
238 pub(crate) fn type_sign(ty: Ty<'_>) -> bool {
240 ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
242 ty::Float(..) => false, // `signed` is unused for floats
243 _ => panic!("{}", ty),
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>,
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>>>,
261 pub(crate) bcx: FunctionBuilder<'clif>,
262 pub(crate) block_map: IndexVec<BasicBlock, Block>,
263 pub(crate) local_map: IndexVec<Local, CPlace<'tcx>>,
265 /// When `#[track_caller]` is used, the implicit caller location is stored in this variable.
266 pub(crate) caller_location: Option<CValue<'tcx>>,
268 pub(crate) clif_comments: crate::pretty_clif::CommentWriter,
270 /// Last accessed source file and it's debuginfo file id.
272 /// For optimization purposes only
273 pub(crate) last_source_file: Option<(Lrc<SourceFile>, FileId)>,
275 /// This should only be accessed by `CPlace::new_var`.
276 pub(crate) next_ssa_var: u32,
279 impl<'tcx> LayoutOfHelpers<'tcx> for FunctionCx<'_, '_, 'tcx> {
280 type LayoutOfResult = TyAndLayout<'tcx>;
283 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
284 RevealAllLayoutCx(self.tcx).handle_layout_err(err, span, ty)
288 impl<'tcx> FnAbiOfHelpers<'tcx> for FunctionCx<'_, '_, 'tcx> {
289 type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
292 fn handle_fn_abi_err(
294 err: FnAbiError<'tcx>,
296 fn_abi_request: FnAbiRequest<'tcx>,
298 RevealAllLayoutCx(self.tcx).handle_fn_abi_err(err, span, fn_abi_request)
302 impl<'tcx> layout::HasTyCtxt<'tcx> for FunctionCx<'_, '_, 'tcx> {
303 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
308 impl<'tcx> rustc_target::abi::HasDataLayout for FunctionCx<'_, '_, 'tcx> {
309 fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
310 &self.tcx.data_layout
314 impl<'tcx> layout::HasParamEnv<'tcx> for FunctionCx<'_, '_, 'tcx> {
315 fn param_env(&self) -> ParamEnv<'tcx> {
316 ParamEnv::reveal_all()
320 impl<'tcx> HasTargetSpec for FunctionCx<'_, '_, 'tcx> {
321 fn target_spec(&self) -> &Target {
322 &self.tcx.sess.target
326 impl<'tcx> FunctionCx<'_, '_, 'tcx> {
327 pub(crate) fn monomorphize<T>(&self, value: T) -> T
329 T: TypeFoldable<'tcx> + Copy,
331 self.instance.subst_mir_and_normalize_erasing_regions(
333 ty::ParamEnv::reveal_all(),
338 pub(crate) fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
339 clif_type_from_ty(self.tcx, ty)
342 pub(crate) fn clif_pair_type(&self, ty: Ty<'tcx>) -> Option<(Type, Type)> {
343 clif_pair_type_from_ty(self.tcx, ty)
346 pub(crate) fn get_block(&self, bb: BasicBlock) -> Block {
347 *self.block_map.get(bb).unwrap()
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);
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);
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);
372 let file_id = if let Some(file_id) = cached_file_id {
375 debug_context.add_source_file(&file)
379 self.func_debug_cx.as_mut().unwrap().add_dbg_loc(file_id, line, column);
380 self.bcx.set_srcloc(source_loc);
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(),
394 caller.col_display as u32 + 1,
396 crate::constant::codegen_const_value(fx, const_loc, fx.tcx.caller_location_ty())
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]`.
404 let scope_data = &self.mir.source_scopes[source_info.scope];
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);
412 source_info.span = callsite_span;
415 // Skip past all of the parents with `inlined: None`.
416 match scope_data.inlined_parent_scope {
417 Some(parent) => source_info.scope = parent,
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))
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();
431 // Ignore DuplicateDefinition error, as the data will be the same
432 let _ = self.module.define_data(msg_id, &data_ctx);
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);
438 self.bcx.ins().global_value(self.pointer_type, local_msg_id)
442 pub(crate) struct RevealAllLayoutCx<'tcx>(pub(crate) TyCtxt<'tcx>);
444 impl<'tcx> LayoutOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
445 type LayoutOfResult = TyAndLayout<'tcx>;
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())
452 span_bug!(span, "failed to get layout for `{}`: {}", ty, err)
457 impl<'tcx> FnAbiOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
458 type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
461 fn handle_fn_abi_err(
463 err: FnAbiError<'tcx>,
465 fn_abi_request: FnAbiRequest<'tcx>,
467 if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
468 self.0.sess.span_fatal(span, &err.to_string())
470 match fn_abi_request {
471 FnAbiRequest::OfFnPtr { sig, extra_args } => {
474 "`fn_abi_of_fn_ptr({}, {:?})` failed: {}",
480 FnAbiRequest::OfInstance { instance, extra_args } => {
483 "`fn_abi_of_instance({}, {:?})` failed: {}",
494 impl<'tcx> layout::HasTyCtxt<'tcx> for RevealAllLayoutCx<'tcx> {
495 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
500 impl<'tcx> rustc_target::abi::HasDataLayout for RevealAllLayoutCx<'tcx> {
501 fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
506 impl<'tcx> layout::HasParamEnv<'tcx> for RevealAllLayoutCx<'tcx> {
507 fn param_env(&self) -> ParamEnv<'tcx> {
508 ParamEnv::reveal_all()
512 impl<'tcx> HasTargetSpec for RevealAllLayoutCx<'tcx> {
513 fn target_spec(&self) -> &Target {